You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by sa...@apache.org on 2016/06/16 08:12:02 UTC
[01/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Repository: cloudstack
Updated Branches:
refs/heads/deploy-from-snapshot 6c3c9ea91 -> 44ba14d17
fix bug where the countdown would be on multiple lines
Example of problem:
ATTENTION: Merging pull request #731 from remibergsma/centos7-kvm into 'master' branch in 5 seconds. CTRL+c to abort..
-n 5
-n 4
-n 3
-n 2
-n 1
-n 0
Should be compatible with more environments if printf is used instead.
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/9a24109f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/9a24109f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/9a24109f
Branch: refs/heads/deploy-from-snapshot
Commit: 9a24109f9545b024e916b297a403bdd299ecba11
Parents: fed5c2b
Author: Remi Bergsma <gi...@remi.nl>
Authored: Mon Aug 24 13:42:48 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Mon Aug 24 16:00:48 2015 +0200
----------------------------------------------------------------------
tools/git/git-pr | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/9a24109f/tools/git/git-pr
----------------------------------------------------------------------
diff --git a/tools/git/git-pr b/tools/git/git-pr
index 49eee79..2e0b275 100755
--- a/tools/git/git-pr
+++ b/tools/git/git-pr
@@ -207,10 +207,11 @@ echo "${prTitle}${prBody}" >> ${tmpMessageFile}
echo "ATTENTION: Merging pull request #${prId} from ${prOriginBranch} into '${currentBranch}' branch in 5 seconds. CTRL+c to abort.."
sec=5
while [ $sec -ge 0 ]; do
- echo -n "${sec} "
+ printf "${sec} "
sec=$((sec-1))
sleep 1
done
+echo
echo "INFO: Executing the merge now.. Git output below:"
echo "INFO: ***********************************************************************************"
[23/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/net/NetUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/NetUtils.java b/utils/src/com/cloud/utils/net/NetUtils.java
deleted file mode 100644
index 883129b..0000000
--- a/utils/src/com/cloud/utils/net/NetUtils.java
+++ /dev/null
@@ -1,1550 +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 com.cloud.utils.net;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.InterfaceAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.net.URI;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Formatter;
-import java.util.List;
-import java.util.Random;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.commons.lang.SystemUtils;
-import org.apache.commons.net.util.SubnetUtils;
-import org.apache.commons.validator.routines.InetAddressValidator;
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.IteratorUtil;
-import com.cloud.utils.Pair;
-import com.cloud.utils.script.Script;
-import com.googlecode.ipv6.IPv6Address;
-import com.googlecode.ipv6.IPv6AddressRange;
-import com.googlecode.ipv6.IPv6Network;
-
-public class NetUtils {
- protected final static Logger s_logger = Logger.getLogger(NetUtils.class);
-
- private static final int MAX_CIDR = 32;
- private static final int RFC_3021_31_BIT_CIDR = 31;
-
- public final static String HTTP_PORT = "80";
- public final static String HTTPS_PORT = "443";
- public final static int VPN_PORT = 500;
- public final static int VPN_NATT_PORT = 4500;
- public final static int VPN_L2TP_PORT = 1701;
- public final static int HAPROXY_STATS_PORT = 8081;
-
- public final static String UDP_PROTO = "udp";
- public final static String TCP_PROTO = "tcp";
- public final static String ANY_PROTO = "any";
- public final static String ICMP_PROTO = "icmp";
- public final static String ALL_PROTO = "all";
- public final static String HTTP_PROTO = "http";
- public final static String SSL_PROTO = "ssl";
-
- public final static String ALL_CIDRS = "0.0.0.0/0";
- public final static int PORT_RANGE_MIN = 0;
- public final static int PORT_RANGE_MAX = 65535;
-
- public final static int DEFAULT_AUTOSCALE_VM_DESTROY_TIME = 2 * 60; // Grace period before Vm is destroyed
- public final static int DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME = 30;
- public final static int DEFAULT_AUTOSCALE_POLICY_QUIET_TIME = 5 * 60;
- private final static Random s_rand = new Random(System.currentTimeMillis());
-
- public static long createSequenceBasedMacAddress(final long macAddress) {
- return macAddress | 0x060000000000l | (long)s_rand.nextInt(32768) << 25 & 0x00fffe000000l;
- }
-
- public static String getHostName() {
- try {
- final InetAddress localAddr = InetAddress.getLocalHost();
- if (localAddr != null) {
- return localAddr.getHostName();
- }
- } catch (final UnknownHostException e) {
- s_logger.warn("UnknownHostException when trying to get host name. ", e);
- }
- return "localhost";
- }
-
- public static InetAddress getLocalInetAddress() {
- try {
- return InetAddress.getLocalHost();
- } catch (final UnknownHostException e) {
- s_logger.warn("UnknownHostException in getLocalInetAddress().", e);
- return null;
- }
- }
-
- public static String resolveToIp(final String host) {
- try {
- final InetAddress addr = InetAddress.getByName(host);
- return ipFromInetAddress(addr);
- } catch (final UnknownHostException e) {
- s_logger.warn("Unable to resolve " + host + " to IP due to UnknownHostException");
- return null;
- }
- }
-
- public static InetAddress[] getAllLocalInetAddresses() {
- final List<InetAddress> addrList = new ArrayList<InetAddress>();
- try {
- for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
- if (ifc.isUp() && !ifc.isVirtual()) {
- for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
- addrList.add(addr);
- }
- }
- }
- } catch (final SocketException e) {
- s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
- }
-
- final InetAddress[] addrs = new InetAddress[addrList.size()];
- if (addrList.size() > 0) {
- System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
- }
- return addrs;
- }
-
- public static String[] getLocalCidrs() {
- final String defaultHostIp = getDefaultHostIp();
-
- final List<String> cidrList = new ArrayList<String>();
- try {
- for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
- if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
- for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
- final InetAddress addr = address.getAddress();
- final int prefixLength = address.getNetworkPrefixLength();
- if (prefixLength < MAX_CIDR && prefixLength > 0) {
- final String ip = ipFromInetAddress(addr);
- if (ip.equalsIgnoreCase(defaultHostIp)) {
- cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
- }
- }
- }
- }
- }
- } catch (final SocketException e) {
- s_logger.warn("UnknownHostException in getLocalCidrs().", e);
- }
-
- return cidrList.toArray(new String[0]);
- }
-
- public static String getDefaultHostIp() {
- if (SystemUtils.IS_OS_WINDOWS) {
- final Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*");
- try {
- final Process result = Runtime.getRuntime().exec("route print -4");
- final BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
-
- String line = output.readLine();
- while (line != null) {
- final Matcher matcher = pattern.matcher(line);
- if (matcher.find()) {
- return matcher.group(2);
- }
- line = output.readLine();
- }
- } catch (final IOException e) {
- s_logger.debug("Caught IOException", e);
- }
- return null;
- } else {
- NetworkInterface nic = null;
- final String pubNic = getDefaultEthDevice();
-
- if (pubNic == null) {
- return null;
- }
-
- try {
- nic = NetworkInterface.getByName(pubNic);
- } catch (final SocketException e) {
- return null;
- }
-
- String[] info = null;
- try {
- info = NetUtils.getNetworkParams(nic);
- } catch (final NullPointerException ignored) {
- s_logger.debug("Caught NullPointerException when trying to getDefaultHostIp");
- }
- if (info != null) {
- return info[0];
- }
- return null;
- }
- }
-
- public static String getDefaultEthDevice() {
- if (SystemUtils.IS_OS_MAC) {
- final String defDev = Script.runSimpleBashScript("/sbin/route -n get default 2> /dev/null | grep interface | awk '{print $2}'");
- return defDev;
- }
- final String defaultRoute = Script.runSimpleBashScript("/sbin/route | grep default");
-
- if (defaultRoute == null) {
- return null;
- }
-
- final String[] defaultRouteList = defaultRoute.split("\\s+");
-
- if (defaultRouteList.length != 8) {
- return null;
- }
-
- return defaultRouteList[7];
- }
-
- public static InetAddress getFirstNonLoopbackLocalInetAddress() {
- final InetAddress[] addrs = getAllLocalInetAddresses();
- if (addrs != null) {
- for (final InetAddress addr : addrs) {
- if (s_logger.isInfoEnabled()) {
- s_logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);
- }
-
- if (!addr.isLoopbackAddress()) {
- return addr;
- }
- }
- }
-
- s_logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length);
- return null;
- }
-
- public static InetAddress[] getInterfaceInetAddresses(final String ifName) {
- final List<InetAddress> addrList = new ArrayList<InetAddress>();
- try {
- for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
- if (ifc.isUp() && !ifc.isVirtual() && ifc.getName().equals(ifName)) {
- for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
- addrList.add(addr);
- }
- }
- }
- } catch (final SocketException e) {
- s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
- }
-
- final InetAddress[] addrs = new InetAddress[addrList.size()];
- if (addrList.size() > 0) {
- System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
- }
- return addrs;
- }
-
- public static String getLocalIPString() {
- final InetAddress addr = getLocalInetAddress();
- if (addr != null) {
- return ipFromInetAddress(addr);
- }
-
- return "127.0.0.1";
- }
-
- public static String ipFromInetAddress(final InetAddress addr) {
- assert addr != null;
-
- final byte[] ipBytes = addr.getAddress();
- final StringBuffer sb = new StringBuffer();
- sb.append(ipBytes[0] & 0xff).append(".");
- sb.append(ipBytes[1] & 0xff).append(".");
- sb.append(ipBytes[2] & 0xff).append(".");
- sb.append(ipBytes[3] & 0xff);
-
- return sb.toString();
- }
-
- public static boolean isLocalAddress(final InetAddress addr) {
- final InetAddress[] addrs = getAllLocalInetAddresses();
-
- if (addrs != null) {
- for (final InetAddress self : addrs) {
- if (self.equals(addr)) {
- return true;
- }
- }
- }
- return false;
- }
-
- public static boolean isLocalAddress(final String strAddress) {
-
- InetAddress addr;
- try {
- addr = InetAddress.getByName(strAddress);
- return isLocalAddress(addr);
- } catch (final UnknownHostException e) {
- }
- return false;
- }
-
- public static String getMacAddress(final InetAddress address) {
- final StringBuffer sb = new StringBuffer();
- final Formatter formatter = new Formatter(sb);
- try {
- final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
- final byte[] mac = ni.getHardwareAddress();
-
- for (int i = 0; i < mac.length; i++) {
- formatter.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : "");
- }
- } catch (final SocketException e) {
- s_logger.error("SocketException when trying to retrieve MAC address", e);
- } finally {
- formatter.close();
- }
- return sb.toString();
- }
-
- public static long getMacAddressAsLong(final InetAddress address) {
- long macAddressAsLong = 0;
- try {
- final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
- final byte[] mac = ni.getHardwareAddress();
-
- for (int i = 0; i < mac.length; i++) {
- macAddressAsLong |= (long)(mac[i] & 0xff) << (mac.length - i - 1) * 8;
- }
-
- } catch (final SocketException e) {
- s_logger.error("SocketException when trying to retrieve MAC address", e);
- }
-
- return macAddressAsLong;
- }
-
- /**
- * This method will fail in case we have a 31 Bit prefix network
- * See RFC 3021.
- *
- * In order to avoid calling this method, please check the <code>NetUtils.is31PrefixCidr(cidr)</code> first.
- */
- public static boolean ipRangesOverlap(final String startIp1, final String endIp1, final String startIp2, final String endIp2) {
- final long startIp1Long = ip2Long(startIp1);
- long endIp1Long = startIp1Long;
- if (endIp1 != null) {
- endIp1Long = ip2Long(endIp1);
- }
- final long startIp2Long = ip2Long(startIp2);
- long endIp2Long = startIp2Long;
- if (endIp2 != null) {
- endIp2Long = ip2Long(endIp2);
- }
-
- if (startIp1Long == startIp2Long || startIp1Long == endIp2Long || endIp1Long == startIp2Long || endIp1Long == endIp2Long) {
- return true;
- } else if (startIp1Long > startIp2Long && startIp1Long < endIp2Long) {
- return true;
- } else if (endIp1Long > startIp2Long && endIp1Long < endIp2Long) {
- return true;
- } else if (startIp2Long > startIp1Long && startIp2Long < endIp1Long) {
- return true;
- } else if (endIp2Long > startIp1Long && endIp2Long < endIp1Long) {
- return true;
- } else {
- return false;
- }
- }
-
- public static long ip2Long(final String ip) {
- final String[] tokens = ip.split("[.]");
- assert tokens.length == 4;
- long result = 0;
- for (int i = 0; i < tokens.length; i++) {
- try {
- result = result << 8 | Integer.parseInt(tokens[i]);
- } catch (final NumberFormatException e) {
- throw new RuntimeException("Incorrect number", e);
- }
- }
-
- return result;
- }
-
- public static String long2Ip(final long ip) {
- final StringBuilder result = new StringBuilder(15);
- result.append(ip >> 24 & 0xff).append(".");
- result.append(ip >> 16 & 0xff).append(".");
- result.append(ip >> 8 & 0xff).append(".");
- result.append(ip & 0xff);
-
- return result.toString();
- }
-
- public static long mac2Long(final String macAddress) {
- final String[] tokens = macAddress.split(":");
- assert tokens.length == 6;
- long result = 0;
- for (int i = 0; i < tokens.length; i++) {
- result = result << 8;
- result |= Integer.parseInt(tokens[i], 16);
- }
- return result;
- }
-
- public static String[] getNicParams(final String nicName) {
- try {
- final NetworkInterface nic = NetworkInterface.getByName(nicName);
- return getNetworkParams(nic);
- } catch (final SocketException e) {
- return null;
- }
- }
-
- public static String[] getNetworkParams(final NetworkInterface nic) {
- final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
- if (addrs == null || addrs.size() == 0) {
- return null;
- }
- InterfaceAddress addr = null;
- for (final InterfaceAddress iaddr : addrs) {
- final InetAddress inet = iaddr.getAddress();
- if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
- addr = iaddr;
- break;
- }
- }
- if (addr == null) {
- return null;
- }
- final String[] result = new String[3];
- result[0] = addr.getAddress().getHostAddress();
- try {
- final byte[] mac = nic.getHardwareAddress();
- result[1] = byte2Mac(mac);
- } catch (final SocketException e) {
- s_logger.debug("Caught exception when trying to get the mac address ", e);
- }
-
- result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
- return result;
- }
-
- public static String prefix2Netmask(final short prefix) {
- long addr = 0;
- for (int i = 0; i < prefix; i++) {
- addr = addr | 1 << 31 - i;
- }
-
- return long2Ip(addr);
- }
-
- public static String byte2Mac(final byte[] m) {
- final StringBuilder result = new StringBuilder(17);
- final Formatter formatter = new Formatter(result);
- formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
- formatter.close();
- return result.toString();
- }
-
- public static String long2Mac(final long macAddress) {
- final StringBuilder result = new StringBuilder(17);
- try (Formatter formatter = new Formatter(result)) {
- formatter.format("%02x:%02x:%02x:%02x:%02x:%02x",
- macAddress >> 40 & 0xff, macAddress >> 32 & 0xff,
- macAddress >> 24 & 0xff, macAddress >> 16 & 0xff,
- macAddress >> 8 & 0xff, macAddress & 0xff);
- }
- return result.toString();
- }
-
- public static boolean isValidPrivateIp(final String ipAddress, final String guestIPAddress) {
-
- final InetAddress privIp = parseIpAddress(ipAddress);
- if (privIp == null) {
- return false;
- }
- if (!privIp.isSiteLocalAddress()) {
- return false;
- }
-
- String firstGuestOctet = "10";
- if (guestIPAddress != null && !guestIPAddress.isEmpty()) {
- final String[] guestIPList = guestIPAddress.split("\\.");
- firstGuestOctet = guestIPList[0];
- }
-
- final String[] ipList = ipAddress.split("\\.");
- if (!ipList[0].equals(firstGuestOctet)) {
- return false;
- }
-
- return true;
- }
-
- public static boolean isSiteLocalAddress(final String ipAddress) {
- if (ipAddress == null) {
- return false;
- } else {
- final InetAddress ip = parseIpAddress(ipAddress);
- if(ip != null) {
- return ip.isSiteLocalAddress();
- }
- return false;
- }
- }
-
- public static boolean validIpRange(final String startIP, final String endIP) {
- if (endIP == null || endIP.isEmpty()) {
- return true;
- }
-
- final long startIPLong = NetUtils.ip2Long(startIP);
- final long endIPLong = NetUtils.ip2Long(endIP);
- return startIPLong <= endIPLong;
- }
-
- public static boolean isValidIp(final String ip) {
- final InetAddressValidator validator = InetAddressValidator.getInstance();
-
- return validator.isValidInet4Address(ip);
- }
-
- public static boolean is31PrefixCidr(final String cidr) {
- final boolean isValidCird = isValidCIDR(cidr);
- if (isValidCird){
- final String[] cidrPair = cidr.split("\\/");
- final String cidrSize = cidrPair[1];
-
- final int cidrSizeNum = Integer.parseInt(cidrSize);
- if (cidrSizeNum == RFC_3021_31_BIT_CIDR) {
- return true;
- }
- }
- return false;
- }
-
- public static boolean isValidCIDR(final String cidr) {
- if (cidr == null || cidr.isEmpty()) {
- return false;
- }
- final String[] cidrPair = cidr.split("\\/");
- if (cidrPair.length != 2) {
- return false;
- }
- final String cidrAddress = cidrPair[0];
- final String cidrSize = cidrPair[1];
- if (!isValidIp(cidrAddress)) {
- return false;
- }
- int cidrSizeNum = -1;
-
- try {
- cidrSizeNum = Integer.parseInt(cidrSize);
- } catch (final Exception e) {
- return false;
- }
-
- if (cidrSizeNum < 0 || cidrSizeNum > MAX_CIDR) {
- return false;
- }
-
- return true;
- }
-
- public static boolean isValidNetmask(final String netmask) {
- if (!isValidIp(netmask)) {
- return false;
- }
-
- final long ip = ip2Long(netmask);
- int count = 0;
- boolean finished = false;
- for (int i = 31; i >= 0; i--) {
- if ((ip >> i & 0x1) == 0) {
- finished = true;
- } else {
- if (finished) {
- return false;
- }
- count += 1;
- }
- }
-
- if (count == 0) {
- return false;
- }
-
- return true;
- }
-
- private static InetAddress parseIpAddress(final String address) {
- final StringTokenizer st = new StringTokenizer(address, ".");
- final byte[] bytes = new byte[4];
-
- if (st.countTokens() == 4) {
- try {
- for (int i = 0; i < 4; i++) {
- bytes[i] = (byte)Integer.parseInt(st.nextToken());
- }
- return InetAddress.getByAddress(address, bytes);
- } catch (final NumberFormatException nfe) {
- return null;
- } catch (final UnknownHostException uhe) {
- return null;
- }
- }
- return null;
- }
-
- public static String getCidrFromGatewayAndNetmask(final String gatewayStr, final String netmaskStr) {
- final long netmask = ip2Long(netmaskStr);
- final long gateway = ip2Long(gatewayStr);
- final long firstPart = gateway & netmask;
- final long size = getCidrSize(netmaskStr);
- return long2Ip(firstPart) + "/" + size;
- }
-
- public static String[] getIpRangeFromCidr(final String cidr, final long size) {
- assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
- final String[] result = new String[2];
- final long ip = ip2Long(cidr);
- final long startNetMask = ip2Long(getCidrNetmask(size));
- final long start = (ip & startNetMask) + 1;
- long end = start;
-
- end = end >> MAX_CIDR - size;
-
- end++;
- end = (end << MAX_CIDR - size) - 2;
-
- result[0] = long2Ip(start);
- result[1] = long2Ip(end);
-
- return result;
- }
-
- public static Set<Long> getAllIpsFromCidr(final String cidr, final long size, final Set<Long> usedIps) {
- assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
- final Set<Long> result = new TreeSet<Long>();
- final long ip = ip2Long(cidr);
- final long startNetMask = ip2Long(getCidrNetmask(size));
- long start = (ip & startNetMask) + 1;
- long end = start;
-
- end = end >> MAX_CIDR - size;
-
- end++;
- end = (end << MAX_CIDR - size) - 2;
- int maxIps = 255; // get 255 ips as maximum
- while (start <= end && maxIps > 0) {
- if (!usedIps.contains(start)) {
- result.add(start);
- maxIps--;
- }
- start++;
- }
-
- return result;
- }
-
- /**
- * Given a cidr, this method returns an ip address within the range but
- * is not in the avoid list.
- *
- * @param startIp ip that the cidr starts with
- * @param size size of the cidr
- * @param avoid set of ips to avoid
- * @return ip that is within the cidr range but not in the avoid set. -1 if unable to find one.
- */
- public static long getRandomIpFromCidr(final String startIp, final int size, final SortedSet<Long> avoid) {
- return getRandomIpFromCidr(ip2Long(startIp), size, avoid);
-
- }
-
- /**
- * Given a cidr, this method returns an ip address within the range but
- * is not in the avoid list.
- * Note: the gateway address has to be specified in the avoid list
- *
- * @param cidr ip that the cidr starts with
- * @param size size of the cidr
- * @param avoid set of ips to avoid
- * @return ip that is within the cidr range but not in the avoid set. -1 if unable to find one.
- */
- public static long getRandomIpFromCidr(final long cidr, final int size, final SortedSet<Long> avoid) {
- assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
-
- final long startNetMask = ip2Long(getCidrNetmask(size));
- final long startIp = (cidr & startNetMask) + 1; //exclude the first ip since it isnt valid, e.g., 192.168.10.0
- int range = 1 << MAX_CIDR - size; //e.g., /24 = 2^8 = 256
- range = range - 1; //exclude end of the range since that is the broadcast address, e.g., 192.168.10.255
-
- if (avoid.size() >= range) {
- return -1;
- }
-
- //Reduce the range by the size of the avoid set
- //e.g., cidr = 192.168.10.0, size = /24, avoid = 192.168.10.1, 192.168.10.20, 192.168.10.254
- // range = 2^8 - 1 - 3 = 252
- range = range - avoid.size();
- final int next = s_rand.nextInt(range); //note: nextInt excludes last value
- long ip = startIp + next;
- for (final Long avoidable : avoid) {
- if (ip >= avoidable) {
- ip++;
- } else {
- break;
- }
- }
-
- return ip;
- }
-
- public static String getIpRangeStartIpFromCidr(final String cidr, final long size) {
- final long ip = ip2Long(cidr);
- final long startNetMask = ip2Long(getCidrNetmask(size));
- final long start = (ip & startNetMask) + 1;
- return long2Ip(start);
- }
-
- public static String getIpRangeEndIpFromCidr(final String cidr, final long size) {
- final long ip = ip2Long(cidr);
- final long startNetMask = ip2Long(getCidrNetmask(size));
- final long start = (ip & startNetMask) + 1;
- long end = start;
- end = end >> MAX_CIDR - size;
-
- end++;
- end = (end << MAX_CIDR - size) - 2;
- return long2Ip(end);
- }
-
- public static boolean sameSubnet(final String ip1, final String ip2, final String netmask) {
- if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
- return true;
- }
- final String subnet1 = NetUtils.getSubNet(ip1, netmask);
- final String subnet2 = NetUtils.getSubNet(ip2, netmask);
-
- return subnet1.equals(subnet2);
- }
-
- public static boolean sameSubnetCIDR(final String ip1, final String ip2, final long cidrSize) {
- if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
- return true;
- }
- final String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize);
- final String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize);
-
- return subnet1.equals(subnet2);
- }
-
- public static String getSubNet(final String ip, final String netmask) {
- final long ipAddr = ip2Long(ip);
- final long subnet = ip2Long(netmask);
- final long result = ipAddr & subnet;
- return long2Ip(result);
- }
-
- public static String getCidrSubNet(final String ip, final long cidrSize) {
- final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSize << MAX_CIDR - cidrSize;
- final String netmask = NetUtils.long2Ip(numericNetmask);
- return getSubNet(ip, netmask);
- }
-
- public static String ipAndNetMaskToCidr(final String ip, final String netmask) {
- if (!isValidIp(ip)) {
- return null;
- }
-
- if (!isValidNetmask(netmask)) {
- return null;
- }
-
- final long ipAddr = ip2Long(ip);
- final long subnet = ip2Long(netmask);
- final long result = ipAddr & subnet;
- int bits = subnet == 0 ? 0 : 1;
- long subnet2 = subnet;
- while ((subnet2 = subnet2 >> 1 & subnet) != 0) {
- bits++;
- }
-
- return long2Ip(result) + "/" + Integer.toString(bits);
- }
-
- public static String[] ipAndNetMaskToRange(final String ip, final String netmask) {
- final long ipAddr = ip2Long(ip);
- long subnet = ip2Long(netmask);
- final long start = (ipAddr & subnet) + 1;
- long end = start;
- int bits = subnet == 0 ? 0 : 1;
- while ((subnet = subnet >> 1 & subnet) != 0) {
- bits++;
- }
- end = end >> MAX_CIDR - bits;
-
- end++;
- end = (end << MAX_CIDR - bits) - 2;
-
- return new String[] {long2Ip(start), long2Ip(end)};
-
- }
-
- public static Pair<String, Integer> getCidr(final String cidr) {
- final String[] tokens = cidr.split("/");
- return new Pair<String, Integer>(tokens[0], Integer.parseInt(tokens[1]));
- }
-
- public static enum SupersetOrSubset {
- isSuperset, isSubset, neitherSubetNorSuperset, sameSubnet, errorInCidrFormat
- }
-
- public static SupersetOrSubset isNetowrkASubsetOrSupersetOfNetworkB(final String cidrA, final String cidrB) {
- final Long[] cidrALong = cidrToLong(cidrA);
- final Long[] cidrBLong = cidrToLong(cidrB);
- long shift = 0;
- if (cidrALong == null || cidrBLong == null) {
- //implies error in the cidr format
- return SupersetOrSubset.errorInCidrFormat;
- }
- if (cidrALong[1] >= cidrBLong[1]) {
- shift = MAX_CIDR - cidrBLong[1];
- } else {
- shift = MAX_CIDR - cidrALong[1];
- }
- final long result = (cidrALong[0] >> shift) - (cidrBLong[0] >> shift);
- if (result == 0) {
- if (cidrALong[1] < cidrBLong[1]) {
- //this implies cidrA is super set of cidrB
- return SupersetOrSubset.isSuperset;
- } else if (cidrALong[1].equals(cidrBLong[1])) {
- //this implies both the cidrs are equal
- return SupersetOrSubset.sameSubnet;
- }
- // implies cidrA is subset of cidrB
- return SupersetOrSubset.isSubset;
- }
- //this implies no overlap.
- return SupersetOrSubset.neitherSubetNorSuperset;
- }
-
- public static boolean isNetworkAWithinNetworkB(final String cidrA, final String cidrB) {
- final Long[] cidrALong = cidrToLong(cidrA);
- final Long[] cidrBLong = cidrToLong(cidrB);
- if (cidrALong == null || cidrBLong == null) {
- return false;
- }
- final long shift = MAX_CIDR - cidrBLong[1];
- return cidrALong[0] >> shift == cidrBLong[0] >> shift;
- }
-
- public static Long[] cidrToLong(final String cidr) {
- if (cidr == null || cidr.isEmpty()) {
- return null;
- }
- final String[] cidrPair = cidr.split("\\/");
- if (cidrPair.length != 2) {
- return null;
- }
- final String cidrAddress = cidrPair[0];
- final String cidrSize = cidrPair[1];
- if (!isValidIp(cidrAddress)) {
- return null;
- }
- int cidrSizeNum = -1;
-
- try {
- cidrSizeNum = Integer.parseInt(cidrSize);
- } catch (final Exception e) {
- return null;
- }
- final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSizeNum << MAX_CIDR - cidrSizeNum;
- final long ipAddr = ip2Long(cidrAddress);
- final Long[] cidrlong = {ipAddr & numericNetmask, (long)cidrSizeNum};
- return cidrlong;
-
- }
-
- public static String getCidrSubNet(final String cidr) {
- if (cidr == null || cidr.isEmpty()) {
- return null;
- }
- final String[] cidrPair = cidr.split("\\/");
- if (cidrPair.length != 2) {
- return null;
- }
- final String cidrAddress = cidrPair[0];
- final String cidrSize = cidrPair[1];
- if (!isValidIp(cidrAddress)) {
- return null;
- }
- int cidrSizeNum = -1;
-
- try {
- cidrSizeNum = Integer.parseInt(cidrSize);
- } catch (final Exception e) {
- return null;
- }
- final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSizeNum << MAX_CIDR - cidrSizeNum;
- final String netmask = NetUtils.long2Ip(numericNetmask);
- return getSubNet(cidrAddress, netmask);
- }
-
- public static String getCidrNetmask(final long cidrSize) {
- final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSize << MAX_CIDR - cidrSize;
- return long2Ip(numericNetmask);
- }
-
- public static String getCidrNetmask(final String cidr) {
- final String[] cidrPair = cidr.split("\\/");
- final long guestCidrSize = Long.parseLong(cidrPair[1]);
- return getCidrNetmask(guestCidrSize);
- }
-
- public static String cidr2Netmask(final String cidr) {
- final String[] tokens = cidr.split("\\/");
- return getCidrNetmask(Integer.parseInt(tokens[1]));
- }
-
- public static long getCidrSize(final String netmask) {
- final long ip = ip2Long(netmask);
- int count = 0;
- for (int i = 0; i < MAX_CIDR; i++) {
- if ((ip >> i & 0x1) == 0) {
- count++;
- } else {
- break;
- }
- }
-
- return MAX_CIDR - count;
- }
-
- public static boolean isValidPort(final String p) {
- try {
- final int port = Integer.parseInt(p);
- return !(port > 65535 || port < 1);
- } catch (final NumberFormatException e) {
- return false;
- }
- }
-
- public static boolean isValidPort(final int p) {
- return !(p > 65535 || p < 1);
- }
-
- public static boolean isValidLBPort(final String p) {
- try {
- final int port = Integer.parseInt(p);
- return !(port > 65535 || port < 1);
- } catch (final NumberFormatException e) {
- return false;
- }
- }
-
- public static boolean isValidProto(final String p) {
- final String proto = p.toLowerCase();
- return proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO);
- }
-
- public static boolean isValidSecurityGroupProto(final String p) {
- final String proto = p.toLowerCase();
- return proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO) || proto.equals(ALL_PROTO);
- }
-
- public static boolean isValidAlgorithm(final String p) {
- final String algo = p.toLowerCase();
- return algo.equals("roundrobin") || algo.equals("leastconn") || algo.equals("source");
- }
-
- public static boolean isValidAutoScaleAction(final String p) {
- final String action = p.toLowerCase();
- return action.equals("scaleup") || action.equals("scaledown");
- }
-
- public static String getLinkLocalNetMask() {
- return "255.255.0.0";
- }
-
- public static String getLinkLocalGateway() {
- return "169.254.0.1";
- }
-
- public static String getLinkLocalCIDR() {
- return "169.254.0.0/16";
- }
-
- public static String[] getLinkLocalIPRange(final int size) {
- if (size > 16 || size <= 0) {
- return null;
- }
- /* reserve gateway */
- final String[] range = getIpRangeFromCidr(getLinkLocalGateway(), MAX_CIDR - size);
-
- if (range[0].equalsIgnoreCase(getLinkLocalGateway())) {
- /* remove the gateway */
- long ip = ip2Long(range[0]);
- ip += 1;
- range[0] = long2Ip(ip);
- }
- return range;
- }
-
- public static String getLinkLocalIpEnd() {
- final String[] cidrPair = getLinkLocalCIDR().split("\\/");
- final String cidr = cidrPair[0];
-
- return getIpRangeEndIpFromCidr(cidr, MAX_CIDR - Long.parseLong(cidrPair[1]));
- }
-
- public static String portRangeToString(final int portRange[]) {
- return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]);
- }
-
- public static boolean verifyDomainNameLabel(final String hostName, final boolean isHostName) {
- // must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a
- // case-insensitive manner),
- // the digits '0' through '9', and the hyphen ('-').
- // Can not start with a hyphen and digit, and must not end with a hyphen
- // If it's a host name, don't allow to start with digit
-
- if (hostName.length() > 63 || hostName.length() < 1) {
- s_logger.warn("Domain name label must be between 1 and 63 characters long");
- return false;
- } else if (!hostName.toLowerCase().matches("[a-z0-9-]*")) {
- s_logger.warn("Domain name label may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner)");
- return false;
- } else if (hostName.startsWith("-") || hostName.endsWith("-")) {
- s_logger.warn("Domain name label can not start with a hyphen and digit, and must not end with a hyphen");
- return false;
- } else if (isHostName && hostName.matches("^[0-9-].*")) {
- s_logger.warn("Host name can't start with digit");
- return false;
- }
-
- return true;
- }
-
- public static boolean verifyDomainName(final String domainName) {
- // don't allow domain name length to exceed 190 chars (190 + 63 (max host name length) = 253 = max domainName length
- if (domainName.length() < 1 || domainName.length() > 190) {
- s_logger.trace("Domain name must be between 1 and 190 characters long");
- return false;
- }
-
- if (domainName.startsWith(".") || domainName.endsWith(".")) {
- s_logger.trace("Domain name can't start or end with .");
- return false;
- }
-
- final String[] domainNameLabels = domainName.split("\\.");
-
- for (int i = 0; i < domainNameLabels.length; i++) {
- if (!verifyDomainNameLabel(domainNameLabels[i], false)) {
- s_logger.warn("Domain name label " + domainNameLabels[i] + " is incorrect");
- return false;
- }
- }
-
- return true;
- }
-
- public static String getDhcpRange(final String cidr) {
- final String[] splitResult = cidr.split("\\/");
- final long size = Long.parseLong(splitResult[1]);
- return NetUtils.getIpRangeStartIpFromCidr(splitResult[0], size);
- }
-
- // Check if 2 CIDRs have exactly same IP Range
- public static boolean isSameIpRange(final String cidrA, final String cidrB) {
-
- if (!NetUtils.isValidCIDR(cidrA)) {
- s_logger.info("Invalid value of cidr " + cidrA);
- return false;
- }
- if (!NetUtils.isValidCIDR(cidrB)) {
- s_logger.info("Invalid value of cidr " + cidrB);
- return false;
- }
- final String[] cidrPairFirst = cidrA.split("\\/");
- final String[] cidrPairSecond = cidrB.split("\\/");
-
- final Long networkSizeFirst = Long.valueOf(cidrPairFirst[1]);
- final Long networkSizeSecond = Long.valueOf(cidrPairSecond[1]);
- final String ipRangeFirst[] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeFirst);
- final String ipRangeSecond[] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeSecond);
-
- final long startIpFirst = NetUtils.ip2Long(ipRangeFirst[0]);
- final long endIpFirst = NetUtils.ip2Long(ipRangeFirst[1]);
- final long startIpSecond = NetUtils.ip2Long(ipRangeSecond[0]);
- final long endIpSecond = NetUtils.ip2Long(ipRangeSecond[1]);
- if (startIpFirst == startIpSecond && endIpFirst == endIpSecond) {
- return true;
- }
- return false;
- }
-
- public static boolean validateGuestCidr(final String cidr) {
- // RFC 1918 - The Internet Assigned Numbers Authority (IANA) has reserved the
- // following three blocks of the IP address space for private internets:
- // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
- // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
- // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
-
- final String cidr1 = "10.0.0.0/8";
- final String cidr2 = "172.16.0.0/12";
- final String cidr3 = "192.168.0.0/16";
-
- if (!isValidCIDR(cidr)) {
- s_logger.warn("Cidr " + cidr + " is not valid");
- return false;
- }
-
- if (isNetworkAWithinNetworkB(cidr, cidr1) || isNetworkAWithinNetworkB(cidr, cidr2) || isNetworkAWithinNetworkB(cidr, cidr3)) {
- return true;
- } else {
- s_logger.warn("cidr " + cidr + " is not RFC 1918 compliant");
- return false;
- }
- }
-
- public static boolean verifyInstanceName(final String instanceName) {
- //instance name for cloudstack vms shouldn't contain - and spaces
- if (instanceName.contains("-") || instanceName.contains(" ") || instanceName.contains("+")) {
- s_logger.warn("Instance name can not contain hyphen, spaces and \"+\" char");
- return false;
- }
-
- return true;
- }
-
- public static boolean isNetworksOverlap(final String cidrA, final String cidrB) {
- final Long[] cidrALong = cidrToLong(cidrA);
- final Long[] cidrBLong = cidrToLong(cidrB);
- if (cidrALong == null || cidrBLong == null) {
- return false;
- }
- final long shift = MAX_CIDR - (cidrALong[1] > cidrBLong[1] ? cidrBLong[1] : cidrALong[1]);
- return cidrALong[0] >> shift == cidrBLong[0] >> shift;
- }
-
- public static boolean isValidS2SVpnPolicy(final String policys) {
- if (policys == null || policys.isEmpty()) {
- return false;
- }
- for (final String policy : policys.split(",")) {
- if (policy.isEmpty()) {
- return false;
- }
- final String cipherHash = policy.split(";")[0];
- if (cipherHash.isEmpty()) {
- return false;
- }
- final String[] list = cipherHash.split("-");
- if (list.length != 2) {
- return false;
- }
- final String cipher = list[0];
- final String hash = list[1];
- if (!cipher.matches("3des|aes128|aes192|aes256")) {
- return false;
- }
- if (!hash.matches("md5|sha1")) {
- return false;
- }
- String pfsGroup = null;
- if (!policy.equals(cipherHash)) {
- pfsGroup = policy.split(";")[1];
- }
- if (pfsGroup != null && !pfsGroup.matches("modp1024|modp1536")) {
- return false;
- }
- }
- return true;
- }
-
- public static boolean isValidCidrList(final String cidrList) {
- for (final String guestCidr : cidrList.split(",")) {
- if (!isValidCIDR(guestCidr)) {
- return false;
- }
- }
- return true;
- }
-
- public static boolean validateGuestCidrList(final String guestCidrList) {
- for (final String guestCidr : guestCidrList.split(",")) {
- if (!validateGuestCidr(guestCidr)) {
- return false;
- }
- }
- return true;
- }
-
- public static boolean validateIcmpType(final long icmpType) {
- //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
- if (!(icmpType >= 0 && icmpType <= 255)) {
- s_logger.warn("impcType is not within 0-255 range");
- return false;
- }
- return true;
- }
-
- public static boolean validateIcmpCode(final long icmpCode) {
-
- //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
- if (!(icmpCode >= 0 && icmpCode <= 15)) {
- s_logger.warn("Icmp code should be within 0-15 range");
- return false;
- }
-
- return true;
- }
-
- public static boolean isValidIpv6(final String ip) {
- try {
- IPv6Address.fromString(ip);
- } catch (final IllegalArgumentException ex) {
- return false;
- }
- return true;
- }
-
- public static boolean isValidIp6Cidr(final String ip6Cidr) {
- try {
- IPv6Network.fromString(ip6Cidr);
- } catch (final IllegalArgumentException ex) {
- return false;
- }
- return true;
- }
-
- public static int getIp6CidrSize(final String ip6Cidr) {
- IPv6Network network = null;
- try {
- network = IPv6Network.fromString(ip6Cidr);
- } catch (final IllegalArgumentException ex) {
- return 0;
- }
- return network.getNetmask().asPrefixLength();
- }
-
- // Can cover 127 bits
- public static String getIp6FromRange(final String ip6Range) {
- final String[] ips = ip6Range.split("-");
- final String startIp = ips[0];
- final IPv6Address start = IPv6Address.fromString(startIp);
- final BigInteger gap = countIp6InRange(ip6Range);
- BigInteger next = new BigInteger(gap.bitLength(), s_rand);
- while (next.compareTo(gap) >= 0) {
- next = new BigInteger(gap.bitLength(), s_rand);
- }
- InetAddress resultAddr = null;
- final BigInteger startInt = convertIPv6AddressToBigInteger(start);
- if (startInt != null) {
- final BigInteger resultInt = startInt.add(next);
- try {
- resultAddr = InetAddress.getByAddress(resultInt.toByteArray());
- } catch (final UnknownHostException e) {
- return null;
- }
- }
- if( resultAddr != null) {
- final IPv6Address ip = IPv6Address.fromInetAddress(resultAddr);
- return ip.toString();
- }
- return null;
- }
-
- //RFC3315, section 9.4
- public static String getDuidLL(final String macAddress) {
- final String duid = "00:03:00:01:" + macAddress;
- return duid;
- }
-
- private static BigInteger convertIPv6AddressToBigInteger(final IPv6Address addr) {
- InetAddress inetAddr;
- try {
- inetAddr = addr.toInetAddress();
- } catch (final UnknownHostException e) {
- return null;
- }
- return new BigInteger(inetAddr.getAddress());
- }
-
- // Can cover 127 bits
- public static BigInteger countIp6InRange(final String ip6Range) {
- if (ip6Range == null) {
- return null;
- }
- final String[] ips = ip6Range.split("-");
- final String startIp = ips[0];
- String endIp = ips[0];
- if (ips.length > 1) {
- endIp = ips[1];
- }
- try {
- final BigInteger startInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(startIp));
- final BigInteger endInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(endIp));
- if (endInt != null && startInt != null && startInt.compareTo(endInt) <= 0) {
- return endInt.subtract(startInt).add(BigInteger.ONE);
- }
- } catch (final IllegalArgumentException ex) {
- s_logger.error("Failed to convert a string to an IPv6 address", ex);
- }
- return null;
- }
-
- public static boolean isIp6InRange(final String ip6, final String ip6Range) {
- if (ip6Range == null) {
- return false;
- }
- final String[] ips = ip6Range.split("-");
- final String startIp = ips[0];
- String endIp = null;
- if (ips.length > 1) {
- endIp = ips[1];
- }
- final IPv6Address start = IPv6Address.fromString(startIp);
- final IPv6Address end = IPv6Address.fromString(endIp);
- final IPv6Address ip = IPv6Address.fromString(ip6);
- if (start.compareTo(ip) <= 0 && end.compareTo(ip) >= 0) {
- return true;
- }
- return false;
- }
-
- public static boolean isIp6InNetwork(final String ip6, final String ip6Cidr) {
- IPv6Network network = null;
- try {
- network = IPv6Network.fromString(ip6Cidr);
- } catch (final IllegalArgumentException ex) {
- return false;
- }
- final IPv6Address ip = IPv6Address.fromString(ip6);
- return network.contains(ip);
- }
-
- public static boolean isIp6RangeOverlap(final String ipRange1, final String ipRange2) {
- String[] ips = ipRange1.split("-");
- final String startIp1 = ips[0];
- String endIp1 = null;
- if (ips.length > 1) {
- endIp1 = ips[1];
- }
- final IPv6Address start1 = IPv6Address.fromString(startIp1);
- final IPv6Address end1 = IPv6Address.fromString(endIp1);
- final IPv6AddressRange range1 = IPv6AddressRange.fromFirstAndLast(start1, end1);
- ips = ipRange2.split("-");
- final String startIp2 = ips[0];
- String endIp2 = null;
- if (ips.length > 1) {
- endIp2 = ips[1];
- }
- final IPv6Address start2 = IPv6Address.fromString(startIp2);
- final IPv6Address end2 = IPv6Address.fromString(endIp2);
- final IPv6AddressRange range2 = IPv6AddressRange.fromFirstAndLast(start2, end2);
- return range1.overlaps(range2);
- }
-
- public static String getNextIp6InRange(final String currentIp, final String ipRange) {
- final String[] ips = ipRange.split("-");
- final String startIp = ips[0];
- String endIp = null;
- if (ips.length > 1) {
- endIp = ips[1];
- }
- final IPv6Address start = IPv6Address.fromString(startIp);
- final IPv6Address end = IPv6Address.fromString(endIp);
- final IPv6Address current = IPv6Address.fromString(currentIp);
- IPv6Address result = null;
- if (current.equals(end)) {
- result = start;
- } else {
- result = current.add(1);
- }
- String resultIp = null;
- if (result != null) {
- resultIp = result.toString();
- }
- return resultIp;
- }
-
- public static String standardizeIp6Address(final String ip6Addr) {
- try {
- return IPv6Address.fromString(ip6Addr).toString();
- } catch (final IllegalArgumentException ex) {
- throw new IllegalArgumentException("Invalid IPv6 address: " + ex.getMessage());
- }
- }
-
- public static String standardizeIp6Cidr(final String ip6Cidr){
- try {
- return IPv6Network.fromString(ip6Cidr).toString();
- } catch (final IllegalArgumentException ex) {
- throw new IllegalArgumentException("Invalid IPv6 CIDR: " + ex.getMessage());
- }
- }
-
- static final String VLAN_PREFIX = "vlan://";
- static final int VLAN_PREFIX_LENGTH = VLAN_PREFIX.length();
-
- public static boolean isValidVlan(String vlan) {
- if (null == vlan || "".equals(vlan)) {
- return false;
- }
- if (vlan.startsWith(VLAN_PREFIX)) {
- vlan = vlan.substring(VLAN_PREFIX_LENGTH);
- }
- try {
- final int vnet = Integer.parseInt(vlan);
- if (vnet <= 0 || vnet >= 4095) { // the valid range is 1- 4094
- return false;
- }
- return true;
- } catch (final NumberFormatException e) {
- return false;
- }
- }
-
- static final String VLAN_UNTAGGED = "untagged";
-
- public static boolean isSameIsolationId(String one, String other) {
- // check nulls
- // check empty strings
- if ((one == null || one.isEmpty()) && (other == null || other.isEmpty())) {
- return true;
- }
- if (one == null || other == null) {
- return false;
- }
- // check 'untagged'
- if (one.contains(VLAN_UNTAGGED) && other.contains(VLAN_UNTAGGED)) {
- return true;
- }
- // if one is a number check the other as number and as 'vlan://' + number
- if (one.startsWith(VLAN_PREFIX)) {
- one = one.substring(VLAN_PREFIX_LENGTH);
- }
- if (other.startsWith(VLAN_PREFIX)) {
- other = other.substring(VLAN_PREFIX_LENGTH);
- }
- // check valid uris or numbers
- if (one.equalsIgnoreCase(other)) {
- return true;
- }
-
- return false;
- }
-
- // Attention maintainers: these pvlan functions should take into account code
- // in Networks.BroadcastDomainType, where URI construction is done for other
- // types of BroadcastDomainTypes
- public static URI generateUriForPvlan(final String primaryVlan, final String isolatedPvlan) {
- return URI.create("pvlan://" + primaryVlan + "-i" + isolatedPvlan);
- }
-
- public static String getPrimaryPvlanFromUri(final URI uri) {
- final String[] vlans = uri.getHost().split("-");
- if (vlans.length < 1) {
- return null;
- }
- return vlans[0];
- }
-
- public static String getIsolatedPvlanFromUri(final URI uri) {
- final String[] vlans = uri.getHost().split("-");
- if (vlans.length < 2) {
- return null;
- }
- for (final String vlan : vlans) {
- if (vlan.startsWith("i")) {
- return vlan.replace("i", " ").trim();
- }
- }
- return null;
- }
-
- public static String generateMacOnIncrease(final String baseMac, final long l) {
- long mac = mac2Long(baseMac);
- if (l > 0xFFFFl) {
- return null;
- }
- mac = mac + (l << 24);
- mac = mac & 0x06FFFFFFFFFFl;
- return long2Mac(mac);
- }
-
- public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) {
- if (!isValidIp(ipAddress)) {
- return false;
- }
- if (!isValidCIDR(cidr)) {
- return false;
- }
-
- // check if the gatewayip is the part of the ip range being added.
- // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links
- // GW Netmask Stat IP End IP
- // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1
- // https://tools.ietf.org/html/rfc3021
- // Added by Wilder Rodrigues
- final SubnetUtils subnetUtils = new SubnetUtils(cidr);
- subnetUtils.setInclusiveHostCount(true);
-
- final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress);
-
- return isInRange;
- }
-
- public static Boolean IsIpEqualToNetworkOrBroadCastIp(final String requestedIp, final String cidr, final long size) {
- assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
-
- final long ip = ip2Long(cidr);
- final long startNetMask = ip2Long(getCidrNetmask(size));
-
- final long start = ip & startNetMask;
- long end = start;
-
- end = end >> MAX_CIDR - size;
-
- end++;
- end = (end << MAX_CIDR - size) - 1;
-
- final long reqIp = ip2Long(requestedIp);
- if (reqIp == start || reqIp == end) {
- return true;
- }
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/net/NfsUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/NfsUtils.java b/utils/src/com/cloud/utils/net/NfsUtils.java
deleted file mode 100644
index 23c1007..0000000
--- a/utils/src/com/cloud/utils/net/NfsUtils.java
+++ /dev/null
@@ -1,55 +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 com.cloud.utils.net;
-
-import java.io.File;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-public class NfsUtils {
-
- public static String url2Mount(String urlStr) throws URISyntaxException {
- URI url;
- url = new URI(urlStr);
- return url.getHost() + ":" + url.getPath();
- }
-
- public static String uri2Mount(URI uri) {
- return uri.getHost() + ":" + uri.getPath();
- }
-
- public static String url2PathSafeString(String urlStr) {
- String safe = urlStr.replace(File.separatorChar, '-');
- safe = safe.replace("?", "");
- safe = safe.replace("*", "");
- safe = safe.replace("\\", "");
- safe = safe.replace("/", "");
- return safe;
- }
-
- public static String getHostPart(String nfsPath) {
- String toks[] = nfsPath.split(":");
- if (toks != null && toks.length == 2) {
- return toks[0];
- }
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/net/UrlUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/UrlUtil.java b/utils/src/com/cloud/utils/net/UrlUtil.java
deleted file mode 100644
index 539486e..0000000
--- a/utils/src/com/cloud/utils/net/UrlUtil.java
+++ /dev/null
@@ -1,63 +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 com.cloud.utils.net;
-
-import java.net.URI;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-
-public class UrlUtil {
- public final static Map<String, String> parseQueryParameters(String query) {
- HashMap<String, String> values = new HashMap<String, String>();
- parseQueryParameters(query, false, values);
-
- return values;
- }
-
- public final static Map<String, String> parseQueryParameters(URL url) {
- return parseQueryParameters(url.getQuery());
- }
-
- public final static Map<String, String> parseQueryParameters(URI url) {
- return parseQueryParameters(url.getQuery());
- }
-
- public final static void parseQueryParameters(String query, boolean lowercaseKeys, Map<String, String> params) {
- if (query == null) {
- return;
- }
-
- if (query.startsWith("?")) {
- query = query.substring(1);
- }
-
- String[] parts = query.split("&");
- for (String part : parts) {
- String[] tokens = part.split("=");
-
- if (lowercaseKeys) {
- tokens[0] = tokens[0].toLowerCase();
- }
-
- params.put(tokens[0], tokens[1]);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/HandlerFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/HandlerFactory.java b/utils/src/com/cloud/utils/nio/HandlerFactory.java
deleted file mode 100644
index f6b9c82..0000000
--- a/utils/src/com/cloud/utils/nio/HandlerFactory.java
+++ /dev/null
@@ -1,28 +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 com.cloud.utils.nio;
-
-/**
- * WorkerFactory creates and selects workers.
- */
-public interface HandlerFactory {
- public Task create(Task.Type type, Link link, byte[] data);
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/Link.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/Link.java b/utils/src/com/cloud/utils/nio/Link.java
deleted file mode 100644
index 6d6306a..0000000
--- a/utils/src/com/cloud/utils/nio/Link.java
+++ /dev/null
@@ -1,567 +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 com.cloud.utils.nio;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetSocketAddress;
-import java.net.SocketTimeoutException;
-import java.nio.ByteBuffer;
-import java.nio.channels.Channels;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.SocketChannel;
-import java.security.GeneralSecurityException;
-import java.security.KeyStore;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.cloudstack.utils.security.SSLUtils;
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.PropertiesUtil;
-import com.cloud.utils.db.DbProperties;
-
-/**
- */
-public class Link {
- private static final Logger s_logger = Logger.getLogger(Link.class);
-
- private final InetSocketAddress _addr;
- private final NioConnection _connection;
- private SelectionKey _key;
- private final ConcurrentLinkedQueue<ByteBuffer[]> _writeQueue;
- private ByteBuffer _readBuffer;
- private ByteBuffer _plaintextBuffer;
- private Object _attach;
- private boolean _readHeader;
- private boolean _gotFollowingPacket;
-
- private SSLEngine _sslEngine;
- public static final String keystoreFile = "/cloudmanagementserver.keystore";
-
- public Link(InetSocketAddress addr, NioConnection connection) {
- _addr = addr;
- _connection = connection;
- _readBuffer = ByteBuffer.allocate(2048);
- _attach = null;
- _key = null;
- _writeQueue = new ConcurrentLinkedQueue<ByteBuffer[]>();
- _readHeader = true;
- _gotFollowingPacket = false;
- }
-
- public Link(Link link) {
- this(link._addr, link._connection);
- }
-
- public Object attachment() {
- return _attach;
- }
-
- public void attach(Object attach) {
- _attach = attach;
- }
-
- public void setKey(SelectionKey key) {
- synchronized (this) {
- _key = key;
- }
- }
-
- public void setSSLEngine(SSLEngine sslEngine) {
- _sslEngine = sslEngine;
- }
-
- /**
- * No user, so comment it out.
- *
- * Static methods for reading from a channel in case
- * you need to add a client that doesn't require nio.
- * @param ch channel to read from.
- * @param bytebuffer to use.
- * @return bytes read
- * @throws IOException if not read to completion.
- public static byte[] read(SocketChannel ch, ByteBuffer buff) throws IOException {
- synchronized(buff) {
- buff.clear();
- buff.limit(4);
-
- while (buff.hasRemaining()) {
- if (ch.read(buff) == -1) {
- throw new IOException("Connection closed with -1 on reading size.");
- }
- }
-
- buff.flip();
-
- int length = buff.getInt();
- ByteArrayOutputStream output = new ByteArrayOutputStream(length);
- WritableByteChannel outCh = Channels.newChannel(output);
-
- int count = 0;
- while (count < length) {
- buff.clear();
- int read = ch.read(buff);
- if (read < 0) {
- throw new IOException("Connection closed with -1 on reading data.");
- }
- count += read;
- buff.flip();
- outCh.write(buff);
- }
-
- return output.toByteArray();
- }
- }
- */
-
- private static void doWrite(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
- SSLSession sslSession = sslEngine.getSession();
- ByteBuffer pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
- SSLEngineResult engResult;
-
- ByteBuffer headBuf = ByteBuffer.allocate(4);
-
- int totalLen = 0;
- for (ByteBuffer buffer : buffers) {
- totalLen += buffer.limit();
- }
-
- int processedLen = 0;
- while (processedLen < totalLen) {
- headBuf.clear();
- pkgBuf.clear();
- engResult = sslEngine.wrap(buffers, pkgBuf);
- if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
- engResult.getStatus() != SSLEngineResult.Status.OK) {
- throw new IOException("SSL: SSLEngine return bad result! " + engResult);
- }
-
- processedLen = 0;
- for (ByteBuffer buffer : buffers) {
- processedLen += buffer.position();
- }
-
- int dataRemaining = pkgBuf.position();
- int header = dataRemaining;
- int headRemaining = 4;
- pkgBuf.flip();
- if (processedLen < totalLen) {
- header = header | HEADER_FLAG_FOLLOWING;
- }
- headBuf.putInt(header);
- headBuf.flip();
-
- while (headRemaining > 0) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Writing Header " + headRemaining);
- }
- long count = ch.write(headBuf);
- headRemaining -= count;
- }
- while (dataRemaining > 0) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Writing Data " + dataRemaining);
- }
- long count = ch.write(pkgBuf);
- dataRemaining -= count;
- }
- }
- }
-
- /**
- * write method to write to a socket. This method writes to completion so
- * it doesn't follow the nio standard. We use this to make sure we write
- * our own protocol.
- *
- * @param ch channel to write to.
- * @param buffers buffers to write.
- * @throws IOException if unable to write to completion.
- */
- public static void write(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
- synchronized (ch) {
- doWrite(ch, buffers, sslEngine);
- }
- }
-
- /* SSL has limitation of 16k, we may need to split packets. 18000 is 16k + some extra SSL informations */
- protected static final int MAX_SIZE_PER_PACKET = 18000;
- protected static final int HEADER_FLAG_FOLLOWING = 0x10000;
-
- public byte[] read(SocketChannel ch) throws IOException {
- if (_readHeader) { // Start of a packet
- if (_readBuffer.position() == 0) {
- _readBuffer.limit(4);
- }
-
- if (ch.read(_readBuffer) == -1) {
- throw new IOException("Connection closed with -1 on reading size.");
- }
-
- if (_readBuffer.hasRemaining()) {
- s_logger.trace("Need to read the rest of the packet length");
- return null;
- }
- _readBuffer.flip();
- int header = _readBuffer.getInt();
- int readSize = (short)header;
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Packet length is " + readSize);
- }
-
- if (readSize > MAX_SIZE_PER_PACKET) {
- throw new IOException("Wrong packet size: " + readSize);
- }
-
- if (!_gotFollowingPacket) {
- _plaintextBuffer = ByteBuffer.allocate(2000);
- }
-
- if ((header & HEADER_FLAG_FOLLOWING) != 0) {
- _gotFollowingPacket = true;
- } else {
- _gotFollowingPacket = false;
- }
-
- _readBuffer.clear();
- _readHeader = false;
-
- if (_readBuffer.capacity() < readSize) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity());
- }
- _readBuffer = ByteBuffer.allocate(readSize);
- }
- _readBuffer.limit(readSize);
- }
-
- if (ch.read(_readBuffer) == -1) {
- throw new IOException("Connection closed with -1 on read.");
- }
-
- if (_readBuffer.hasRemaining()) { // We're not done yet.
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Still has " + _readBuffer.remaining());
- }
- return null;
- }
-
- _readBuffer.flip();
-
- ByteBuffer appBuf;
-
- SSLSession sslSession = _sslEngine.getSession();
- SSLEngineResult engResult;
- int remaining = 0;
-
- while (_readBuffer.hasRemaining()) {
- remaining = _readBuffer.remaining();
- appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
- engResult = _sslEngine.unwrap(_readBuffer, appBuf);
- if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
- engResult.getStatus() != SSLEngineResult.Status.OK) {
- throw new IOException("SSL: SSLEngine return bad result! " + engResult);
- }
- if (remaining == _readBuffer.remaining()) {
- throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!");
- }
-
- appBuf.flip();
- if (_plaintextBuffer.remaining() < appBuf.limit()) {
- // We need to expand _plaintextBuffer for more data
- ByteBuffer newBuffer = ByteBuffer.allocate(_plaintextBuffer.capacity() + appBuf.limit() * 5);
- _plaintextBuffer.flip();
- newBuffer.put(_plaintextBuffer);
- _plaintextBuffer = newBuffer;
- }
- _plaintextBuffer.put(appBuf);
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Done with packet: " + appBuf.limit());
- }
- }
-
- _readBuffer.clear();
- _readHeader = true;
-
- if (!_gotFollowingPacket) {
- _plaintextBuffer.flip();
- byte[] result = new byte[_plaintextBuffer.limit()];
- _plaintextBuffer.get(result);
- return result;
- } else {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Waiting for more packets");
- }
- return null;
- }
- }
-
- public void send(byte[] data) throws ClosedChannelException {
- send(data, false);
- }
-
- public void send(byte[] data, boolean close) throws ClosedChannelException {
- send(new ByteBuffer[] {ByteBuffer.wrap(data)}, close);
- }
-
- public void send(ByteBuffer[] data, boolean close) throws ClosedChannelException {
- ByteBuffer[] item = new ByteBuffer[data.length + 1];
- int remaining = 0;
- for (int i = 0; i < data.length; i++) {
- remaining += data[i].remaining();
- item[i + 1] = data[i];
- }
-
- item[0] = ByteBuffer.allocate(4);
- item[0].putInt(remaining);
- item[0].flip();
-
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Sending packet of length " + remaining);
- }
-
- _writeQueue.add(item);
- if (close) {
- _writeQueue.add(new ByteBuffer[0]);
- }
- synchronized (this) {
- if (_key == null) {
- throw new ClosedChannelException();
- }
- _connection.change(SelectionKey.OP_WRITE, _key, null);
- }
- }
-
- public void send(ByteBuffer[] data) throws ClosedChannelException {
- send(data, false);
- }
-
- public synchronized void close() {
- if (_key != null) {
- _connection.close(_key);
- }
- }
-
- public boolean write(SocketChannel ch) throws IOException {
- ByteBuffer[] data = null;
- while ((data = _writeQueue.poll()) != null) {
- if (data.length == 0) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Closing connection requested");
- }
- return true;
- }
-
- ByteBuffer[] raw_data = new ByteBuffer[data.length - 1];
- System.arraycopy(data, 1, raw_data, 0, data.length - 1);
-
- doWrite(ch, raw_data, _sslEngine);
- }
- return false;
- }
-
- public InetSocketAddress getSocketAddress() {
- return _addr;
- }
-
- public String getIpAddress() {
- return _addr.getAddress().toString();
- }
-
- public synchronized void terminated() {
- _key = null;
- }
-
- public synchronized void schedule(Task task) throws ClosedChannelException {
- if (_key == null) {
- throw new ClosedChannelException();
- }
- _connection.scheduleTask(task);
- }
-
- public static SSLContext initSSLContext(boolean isClient) throws GeneralSecurityException, IOException {
- InputStream stream;
- SSLContext sslContext = null;
- KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
- KeyStore ks = KeyStore.getInstance("JKS");
- TrustManager[] tms;
-
- File confFile = PropertiesUtil.findConfigFile("db.properties");
- if (null != confFile && !isClient) {
- final String pass = DbProperties.getDbProperties().getProperty("db.cloud.keyStorePassphrase");
- char[] passphrase = "vmops.com".toCharArray();
- if (pass != null) {
- passphrase = pass.toCharArray();
- }
- String confPath = confFile.getParent();
- String keystorePath = confPath + keystoreFile;
- if (new File(keystorePath).exists()) {
- stream = new FileInputStream(keystorePath);
- } else {
- s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue.");
- stream = NioConnection.class.getResourceAsStream("/cloud.keystore");
- passphrase = "vmops.com".toCharArray();
- }
- ks.load(stream, passphrase);
- stream.close();
- kmf.init(ks, passphrase);
- tmf.init(ks);
- tms = tmf.getTrustManagers();
- } else {
- ks.load(null, null);
- kmf.init(ks, null);
- tms = new TrustManager[1];
- tms[0] = new TrustAllManager();
- }
-
- sslContext = SSLUtils.getSSLContext();
- sslContext.init(kmf.getKeyManagers(), tms, null);
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: SSLcontext has been initialized");
- }
-
- return sslContext;
- }
-
- public static void doHandshake(SocketChannel ch, SSLEngine sslEngine, boolean isClient) throws IOException {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: begin Handshake, isClient: " + isClient);
- }
-
- SSLEngineResult engResult;
- SSLSession sslSession = sslEngine.getSession();
- HandshakeStatus hsStatus;
- ByteBuffer in_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
- ByteBuffer in_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
- ByteBuffer out_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
- ByteBuffer out_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
- int count;
- ch.socket().setSoTimeout(60 * 1000);
- InputStream inStream = ch.socket().getInputStream();
- // Use readCh to make sure the timeout on reading is working
- ReadableByteChannel readCh = Channels.newChannel(inStream);
-
- if (isClient) {
- hsStatus = SSLEngineResult.HandshakeStatus.NEED_WRAP;
- } else {
- hsStatus = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
- }
-
- while (hsStatus != SSLEngineResult.HandshakeStatus.FINISHED) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: Handshake status " + hsStatus);
- }
- engResult = null;
- if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
- out_pkgBuf.clear();
- out_appBuf.clear();
- out_appBuf.put("Hello".getBytes());
- engResult = sslEngine.wrap(out_appBuf, out_pkgBuf);
- out_pkgBuf.flip();
- int remain = out_pkgBuf.limit();
- while (remain != 0) {
- remain -= ch.write(out_pkgBuf);
- if (remain < 0) {
- throw new IOException("Too much bytes sent?");
- }
- }
- } else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
- in_appBuf.clear();
- // One packet may contained multiply operation
- if (in_pkgBuf.position() == 0 || !in_pkgBuf.hasRemaining()) {
- in_pkgBuf.clear();
- count = 0;
- try {
- count = readCh.read(in_pkgBuf);
- } catch (SocketTimeoutException ex) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Handshake reading time out! Cut the connection");
- }
- count = -1;
- }
- if (count == -1) {
- throw new IOException("Connection closed with -1 on reading size.");
- }
- in_pkgBuf.flip();
- }
- engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
- ByteBuffer tmp_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
- int loop_count = 0;
- while (engResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
- // The client is too slow? Cut it and let it reconnect
- if (loop_count > 10) {
- throw new IOException("Too many times in SSL BUFFER_UNDERFLOW, disconnect guest.");
- }
- // We need more packets to complete this operation
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: Buffer underflowed, getting more packets");
- }
- tmp_pkgBuf.clear();
- count = ch.read(tmp_pkgBuf);
- if (count == -1) {
- throw new IOException("Connection closed with -1 on reading size.");
- }
- tmp_pkgBuf.flip();
-
- in_pkgBuf.mark();
- in_pkgBuf.position(in_pkgBuf.limit());
- in_pkgBuf.limit(in_pkgBuf.limit() + tmp_pkgBuf.limit());
- in_pkgBuf.put(tmp_pkgBuf);
- in_pkgBuf.reset();
-
- in_appBuf.clear();
- engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
- loop_count++;
- }
- } else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
- Runnable run;
- while ((run = sslEngine.getDelegatedTask()) != null) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: Running delegated task!");
- }
- run.run();
- }
- } else if (hsStatus == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
- throw new IOException("NOT a handshaking!");
- }
- if (engResult != null && engResult.getStatus() != SSLEngineResult.Status.OK) {
- throw new IOException("Fail to handshake! " + engResult.getStatus());
- }
- if (engResult != null)
- hsStatus = engResult.getHandshakeStatus();
- else
- hsStatus = sslEngine.getHandshakeStatus();
- }
- }
-
-}
[06/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Create Nicira NVP devices and enable plugin at deploy
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/abb824e3
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/abb824e3
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/abb824e3
Branch: refs/heads/deploy-from-snapshot
Commit: abb824e3db0625b435fa55b49496e41efbcbc894
Parents: 2772e4d
Author: Miguel Ferreira <mi...@me.com>
Authored: Wed Aug 5 16:03:28 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 14:50:29 2015 +0200
----------------------------------------------------------------------
tools/marvin/marvin/deployDataCenter.py | 112 +++++++++++++++------------
1 file changed, 62 insertions(+), 50 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/abb824e3/tools/marvin/marvin/deployDataCenter.py
----------------------------------------------------------------------
diff --git a/tools/marvin/marvin/deployDataCenter.py b/tools/marvin/marvin/deployDataCenter.py
index 4fcd696..3dd5667 100644
--- a/tools/marvin/marvin/deployDataCenter.py
+++ b/tools/marvin/marvin/deployDataCenter.py
@@ -534,7 +534,7 @@ class DeployDataCenters(object):
netprov.physicalnetworkid = phynetwrk.id
result = self.__apiClient.addNetworkServiceProvider(netprov)
self.enableProvider(result.id)
- elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp']:
+ elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp', 'NiciraNvp']:
netprov = addNetworkServiceProvider.\
addNetworkServiceProviderCmd()
netprov.name = provider.name
@@ -548,55 +548,67 @@ class DeployDataCenters(object):
self.__addToCleanUp(
"NetworkServiceProvider",
result.id)
- for device in provider.devices:
- if provider.name == 'Netscaler':
- dev = addNetscalerLoadBalancer.\
- addNetscalerLoadBalancerCmd()
- dev.username = device.username
- dev.password = device.password
- dev.networkdevicetype = device.networkdevicetype
- dev.url = configGenerator.getDeviceUrl(device)
- dev.physicalnetworkid = phynetwrk.id
- ret = self.__apiClient.addNetscalerLoadBalancer(
- dev)
- if ret.id:
+ if provider.devices is not None:
+ for device in provider.devices:
+ if provider.name == 'Netscaler':
+ dev = addNetscalerLoadBalancer.\
+ addNetscalerLoadBalancerCmd()
+ dev.username = device.username
+ dev.password = device.password
+ dev.networkdevicetype = device.networkdevicetype
+ dev.url = configGenerator.getDeviceUrl(device)
+ dev.physicalnetworkid = phynetwrk.id
+ ret = self.__apiClient.addNetscalerLoadBalancer(
+ dev)
+ if ret.id:
+ self.__tcRunLogger.\
+ debug("==== AddNetScalerLB "
+ "Successful=====")
+ self.__addToCleanUp(
+ "NetscalerLoadBalancer",
+ ret.id)
+ elif provider.name == 'JuniperSRX':
+ dev = addSrxFirewall.addSrxFirewallCmd()
+ dev.username = device.username
+ dev.password = device.password
+ dev.networkdevicetype = device.networkdevicetype
+ dev.url = configGenerator.getDeviceUrl(device)
+ dev.physicalnetworkid = phynetwrk.id
+ ret = self.__apiClient.addSrxFirewall(dev)
+ if ret.id:
+ self.__tcRunLogger.\
+ debug("==== AddSrx "
+ "Successful=====")
+ self.__addToCleanUp("SrxFirewall", ret.id)
+ elif provider.name == 'F5BigIp':
+ dev = addF5LoadBalancer.addF5LoadBalancerCmd()
+ dev.username = device.username
+ dev.password = device.password
+ dev.networkdevicetype = device.networkdevicetype
+ dev.url = configGenerator.getDeviceUrl(device)
+ dev.physicalnetworkid = phynetwrk.id
+ ret = self.__apiClient.addF5LoadBalancer(dev)
+ if ret.id:
+ self.__tcRunLogger.\
+ debug("==== AddF5 "
+ "Successful=====")
+ self.__addToCleanUp("F5LoadBalancer", ret.id)
+ elif provider.name == 'NiciraNvp':
+ cmd = addNiciraNvpDevice.addNiciraNvpDeviceCmd()
+ cmd.hostname = device.hostname
+ cmd.username = device.username
+ cmd.password = device.password
+ cmd.transportzoneuuid = device.transportzoneuuid
+ cmd.physicalnetworkid = phynetwrk.id
+ ret = self.__apiClient.addNiciraNvpDevice(cmd)
self.__tcRunLogger.\
- debug("==== AddNetScalerLB "
- "Successful=====")
- self.__addToCleanUp(
- "NetscalerLoadBalancer",
- ret.id)
- elif provider.name == 'JuniperSRX':
- dev = addSrxFirewall.addSrxFirewallCmd()
- dev.username = device.username
- dev.password = device.password
- dev.networkdevicetype = device.networkdevicetype
- dev.url = configGenerator.getDeviceUrl(device)
- dev.physicalnetworkid = phynetwrk.id
- ret = self.__apiClient.addSrxFirewall(dev)
- if ret.id:
- self.__tcRunLogger.\
- debug("==== AddSrx "
- "Successful=====")
- self.__addToCleanUp("SrxFirewall", ret.id)
- elif provider.name == 'F5BigIp':
- dev = addF5LoadBalancer.addF5LoadBalancerCmd()
- dev.username = device.username
- dev.password = device.password
- dev.networkdevicetype = device.networkdevicetype
- dev.url = configGenerator.getDeviceUrl(device)
- dev.physicalnetworkid = phynetwrk.id
- ret = self.__apiClient.addF5LoadBalancer(dev)
- if ret.id:
- self.__tcRunLogger.\
- debug("==== AddF5 "
- "Successful=====")
- self.__addToCleanUp("F5LoadBalancer", ret.id)
- else:
- raise InvalidParameterException(
- "Device %s doesn't match "
- "any know provider "
- "type" % device)
+ debug("==== AddNiciraNvp Successful =====")
+ self.__addToCleanUp("NiciraNvp", ret.id)
+ else:
+ raise InvalidParameterException(
+ "Device %s doesn't match "
+ "any know provider "
+ "type" % device)
self.enableProvider(result.id)
except Exception as e:
print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
@@ -1133,7 +1145,7 @@ if __name__ == "__main__":
print "\n===Deploy Failed==="
tc_run_logger.debug("\n===Deploy Failed===");
exit(1)
-
+
if options.remove and os.path.isfile(options.remove) and options.input:
'''
[28/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ProcessUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ProcessUtil.java b/utils/src/com/cloud/utils/ProcessUtil.java
deleted file mode 100644
index 53137c4..0000000
--- a/utils/src/com/cloud/utils/ProcessUtil.java
+++ /dev/null
@@ -1,112 +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 com.cloud.utils;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Properties;
-
-import javax.naming.ConfigurationException;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.script.OutputInterpreter;
-import com.cloud.utils.script.Script;
-
-public class ProcessUtil {
- private static final Logger s_logger = Logger.getLogger(ProcessUtil.class.getName());
-
- // paths cannot be hardcoded
- public static void pidCheck(String pidDir, String run) throws ConfigurationException {
-
- String dir = pidDir == null ? "/var/run" : pidDir;
-
- try {
- final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
- if (propsFile == null) {
- s_logger.debug("environment.properties could not be opened");
- } else {
- final Properties props = PropertiesUtil.loadFromFile(propsFile);
- dir = props.getProperty("paths.pid");
- if (dir == null) {
- dir = pidDir == null ? "/var/run" : pidDir;
- }
- }
- } catch (IOException e) {
- s_logger.debug("environment.properties could not be opened");
- }
-
- final File pidFile = new File(dir + File.separator + run);
- try {
- if (!pidFile.createNewFile()) {
- if (!pidFile.exists()) {
- throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath() + ". Are you sure you're running as root?");
- }
-
- final String pidLine = FileUtils.readFileToString(pidFile).trim();
- if (pidLine.isEmpty()) {
- throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
- }
- try {
- final long pid = Long.parseLong(pidLine);
- final Script script = new Script("bash", 120000, s_logger);
- script.add("-c", "ps -p " + pid);
- final String result = script.execute();
- if (result == null) {
- throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
- }
- if (!pidFile.delete()) {
- throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
- }
- if (!pidFile.createNewFile()) {
- throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
- }
- } catch (final NumberFormatException e) {
- throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
- }
- }
- pidFile.deleteOnExit();
-
- final Script script = new Script("bash", 120000, s_logger);
- script.add("-c", "echo $PPID");
- final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
- script.execute(parser);
-
- final String pid = parser.getLine();
-
- FileUtils.writeStringToFile(pidFile, pid + "\n");
- } catch (final IOException e) {
- throw new CloudRuntimeException("Unable to create the " + pidFile.getAbsolutePath() + ". Are you running as root?", e);
- }
- }
-
- public static String dumpStack() {
- StringBuilder sb = new StringBuilder();
- StackTraceElement[] elems = Thread.currentThread().getStackTrace();
- if (elems != null && elems.length > 0) {
- for (StackTraceElement elem : elems) {
- sb.append("\tat ").append(elem.getMethodName()).append("(").append(elem.getFileName()).append(":").append(elem.getLineNumber()).append(")\n");
- }
- }
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/Profiler.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/Profiler.java b/utils/src/com/cloud/utils/Profiler.java
deleted file mode 100644
index f8e44bd..0000000
--- a/utils/src/com/cloud/utils/Profiler.java
+++ /dev/null
@@ -1,91 +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 com.cloud.utils;
-
-public class Profiler {
-
- private static final long MILLIS_FACTOR = 1000l;
- private static final double EXPONENT = 2d;
-
-
- private Long startTickNanoSeconds;
- private Long stopTickNanoSeconds;
-
- public long start() {
- startTickNanoSeconds = System.nanoTime();
- return startTickNanoSeconds;
- }
-
- public long stop() {
- stopTickNanoSeconds = System.nanoTime();
- return stopTickNanoSeconds;
- }
-
- /**
- * 1 millisecond = 1e+6 nanoseconds
- * 1 second = 1000 milliseconds = 1e+9 nanoseconds
- *
- * @return the duration in nanoseconds.
- */
- public long getDuration() {
- if (startTickNanoSeconds != null && stopTickNanoSeconds != null) {
- final long timeInNanoSeconds = stopTickNanoSeconds - startTickNanoSeconds;
- return timeInNanoSeconds;
- }
-
- return -1;
- }
-
- /**
- * 1 millisecond = 1e+6 nanoseconds
- * 1 second = 1000 millisecond = 1e+9 nanoseconds
- *
- * @return the duration in milliseconds.
- */
- public long getDurationInMillis() {
- if (startTickNanoSeconds != null && stopTickNanoSeconds != null) {
- final long timeInMillis = (stopTickNanoSeconds - startTickNanoSeconds) / (long)Math.pow(MILLIS_FACTOR, EXPONENT);
- return timeInMillis;
- }
-
- return -1;
- }
-
- public boolean isStarted() {
- return startTickNanoSeconds != null;
- }
-
- public boolean isStopped() {
- return stopTickNanoSeconds != null;
- }
-
- @Override
- public String toString() {
- if (startTickNanoSeconds == null) {
- return "Not Started";
- }
-
- if (stopTickNanoSeconds == null) {
- return "Started but not stopped";
- }
-
- return "Done. Duration: " + getDurationInMillis() + "ms";
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/PropertiesUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/PropertiesUtil.java b/utils/src/com/cloud/utils/PropertiesUtil.java
deleted file mode 100644
index 4cb89f7..0000000
--- a/utils/src/com/cloud/utils/PropertiesUtil.java
+++ /dev/null
@@ -1,196 +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 com.cloud.utils;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-
-public class PropertiesUtil {
- private static final Logger s_logger = Logger.getLogger(PropertiesUtil.class);
-
- /**
- * Searches the class path and local paths to find the config file.
- * @param path path to find. if it starts with / then it's absolute path.
- * @return File or null if not found at all.
- */
-
- public static File findConfigFile(String path) {
- ClassLoader cl = PropertiesUtil.class.getClassLoader();
- URL url = cl.getResource(path);
-
- if (url != null && "file".equals(url.getProtocol())) {
- return new File(url.getFile());
- }
-
- url = ClassLoader.getSystemResource(path);
- if (url != null && "file".equals(url.getProtocol())) {
- return new File(url.getFile());
- }
-
- File file = new File(path);
- if (file.exists()) {
- return file;
- }
-
- String newPath = "conf" + (path.startsWith(File.separator) ? "" : "/") + path;
- url = ClassLoader.getSystemResource(newPath);
- if (url != null && "file".equals(url.getProtocol())) {
- return new File(url.getFile());
- }
-
- url = cl.getResource(newPath);
- if (url != null && "file".equals(url.getProtocol())) {
- return new File(url.getFile());
- }
-
- newPath = "conf" + (path.startsWith(File.separator) ? "" : File.separator) + path;
- file = new File(newPath);
- if (file.exists()) {
- return file;
- }
-
- newPath = System.getProperty("catalina.home");
- if (newPath == null) {
- newPath = System.getenv("CATALINA_HOME");
- }
-
- if (newPath == null) {
- newPath = System.getenv("CATALINA_BASE");
- }
-
- if (newPath == null) {
- return null;
- }
-
- file = new File(newPath + File.separator + "conf" + File.separator + path);
- if (file.exists()) {
- return file;
- }
-
- return null;
- }
-
- public static Map<String, Object> toMap(Properties props) {
- Set<String> names = props.stringPropertyNames();
- HashMap<String, Object> map = new HashMap<String, Object>(names.size());
- for (String name : names) {
- map.put(name, props.getProperty(name));
- }
-
- return map;
- }
-
- /*
- * Returns an InputStream for the given resource
- * This is needed to read the files within a jar in classpath.
- */
- public static InputStream openStreamFromURL(String path) {
- ClassLoader cl = PropertiesUtil.class.getClassLoader();
- URL url = cl.getResource(path);
- if (url != null) {
- try {
- InputStream stream = url.openStream();
- return stream;
- } catch (IOException ioex) {
- return null;
- }
- }
- return null;
- }
-
- public static void loadFromJar(Properties properties, String configFile) throws IOException {
- InputStream stream = PropertiesUtil.openStreamFromURL(configFile);
- if (stream != null) {
- properties.load(stream);
- } else {
- s_logger.error("Unable to find properties file: " + configFile);
- }
- }
-
- // Returns key=value pairs by parsing a commands.properties/config file
- // with syntax; key=cmd;value (with this syntax cmd is stripped) and key=value
- public static Map<String, String> processConfigFile(String[] configFiles) {
- Map<String, String> configMap = new HashMap<String, String>();
- Properties preProcessedCommands = new Properties();
- for (String configFile : configFiles) {
- File commandsFile = findConfigFile(configFile);
- if (commandsFile != null) {
- try {
- loadFromFile(preProcessedCommands, commandsFile);
- } catch (IOException ioe) {
- s_logger.error("IO Exception loading properties file", ioe);
- }
- }
- else {
- // in case of a file within a jar in classpath, try to open stream using url
- try {
- loadFromJar(preProcessedCommands, configFile);
- } catch (IOException e) {
- s_logger.error("IO Exception loading properties file from jar", e);
- }
- }
- }
-
- for (Object key : preProcessedCommands.keySet()) {
- String preProcessedCommand = preProcessedCommands.getProperty((String)key);
- int splitIndex = preProcessedCommand.lastIndexOf(";");
- String value = preProcessedCommand.substring(splitIndex + 1);
- configMap.put((String)key, value);
- }
-
- return configMap;
- }
-
- /**
- * Load a Properties object with contents from a File.
- * @param properties the properties object to be loaded
- * @param file the file to load from
- * @throws IOException
- */
- public static void loadFromFile(final Properties properties, final File file)
- throws IOException {
- try (final InputStream stream = new FileInputStream(file)) {
- properties.load(stream);
- }
- }
-
- /**
- * Load the file and return the contents as a Properties object.
- * @param file the file to load
- * @return A Properties object populated
- * @throws IOException
- */
- public static Properties loadFromFile(final File file)
- throws IOException {
- final Properties properties = new Properties();
- loadFromFile(properties, file);
- return properties;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ReflectUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ReflectUtil.java b/utils/src/com/cloud/utils/ReflectUtil.java
deleted file mode 100644
index c8ae954..0000000
--- a/utils/src/com/cloud/utils/ReflectUtil.java
+++ /dev/null
@@ -1,213 +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 com.cloud.utils;
-
-import static java.beans.Introspector.getBeanInfo;
-import static java.util.Collections.emptyList;
-import static java.util.Collections.unmodifiableList;
-
-import java.beans.BeanInfo;
-import java.beans.IntrospectionException;
-import java.beans.PropertyDescriptor;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-import org.reflections.Reflections;
-import org.reflections.util.ConfigurationBuilder;
-import org.reflections.util.ClasspathHelper;
-import org.reflections.scanners.SubTypesScanner;
-import org.reflections.scanners.TypeAnnotationsScanner;
-
-import com.google.common.collect.ImmutableSet;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class ReflectUtil {
-
- private static final Logger s_logger = Logger.getLogger(ReflectUtil.class);
- private static final Logger logger = Logger.getLogger(Reflections.class);
-
- public static Pair<Class<?>, Field> getAnyField(Class<?> clazz, String fieldName) {
- try {
- return new Pair<Class<?>, Field>(clazz, clazz.getDeclaredField(fieldName));
- } catch (SecurityException e) {
- throw new CloudRuntimeException("How the heck?", e);
- } catch (NoSuchFieldException e) {
- // Do I really want this? No I don't but what can I do? It only throws the NoSuchFieldException.
- Class<?> parent = clazz.getSuperclass();
- if (parent != null) {
- return getAnyField(parent, fieldName);
- }
- return null;
- }
- }
-
- // Gets all classes with some annotation from a package
- public static Set<Class<?>> getClassesWithAnnotation(Class<? extends Annotation> annotation, String[] packageNames) {
- Reflections reflections;
- Set<Class<?>> classes = new HashSet<Class<?>>();
- ConfigurationBuilder builder=new ConfigurationBuilder();
- for (String packageName : packageNames) {
- builder.addUrls(ClasspathHelper.forPackage(packageName));
- }
- builder.setScanners(new SubTypesScanner(),new TypeAnnotationsScanner());
- reflections = new Reflections(builder);
- classes.addAll(reflections.getTypesAnnotatedWith(annotation));
- return classes;
- }
-
- // Checks against posted search classes if cmd is async
- public static boolean isCmdClassAsync(Class<?> cmdClass, Class<?>[] searchClasses) {
- boolean isAsync = false;
- Class<?> superClass = cmdClass;
-
- while (superClass != null && superClass != Object.class) {
- String superName = superClass.getName();
- for (Class<?> baseClass : searchClasses) {
- if (superName.equals(baseClass.getName())) {
- isAsync = true;
- break;
- }
- }
- if (isAsync)
- break;
- superClass = superClass.getSuperclass();
- }
- return isAsync;
- }
-
- // Returns all fields until a base class for a cmd class
- public static List<Field> getAllFieldsForClass(Class<?> cmdClass, Class<?> baseClass) {
- List<Field> fields = new ArrayList<Field>();
- Collections.addAll(fields, cmdClass.getDeclaredFields());
- Class<?> superClass = cmdClass.getSuperclass();
- while (baseClass.isAssignableFrom(superClass) && baseClass != superClass) {
- Field[] superClassFields = superClass.getDeclaredFields();
- if (superClassFields != null)
- Collections.addAll(fields, superClassFields);
- superClass = superClass.getSuperclass();
- }
- return fields;
- }
-
- /**
- * Returns all unique fields except excludeClasses for a cmd class
- * @param cmdClass the class in which fields should be collected
- * @param excludeClasses the classes whose fields must be ignored
- * @return list of fields
- */
- public static Set<Field> getAllFieldsForClass(Class<?> cmdClass, Class<?>[] excludeClasses) {
- Set<Field> fields = new HashSet<Field>();
- Collections.addAll(fields, cmdClass.getDeclaredFields());
- Class<?> superClass = cmdClass.getSuperclass();
-
- while (superClass != null && superClass != Object.class) {
- String superName = superClass.getName();
- boolean isNameEqualToSuperName = false;
- for (Class<?> baseClass : excludeClasses) {
- if (superName.equals(baseClass.getName())) {
- isNameEqualToSuperName = true;
- }
- }
-
- if (!isNameEqualToSuperName) {
- Field[] superClassFields = superClass.getDeclaredFields();
- if (superClassFields != null) {
- Collections.addAll(fields, superClassFields);
- }
- }
- superClass = superClass.getSuperclass();
- }
- return fields;
- }
-
- public static List<String> flattenProperties(final Object target, final Class<?> clazz) {
- return flattenPropeties(target, clazz, "class");
- }
-
- public static List<String> flattenPropeties(final Object target, final Class<?> clazz, final String... excludedProperties) {
- return flattenProperties(target, clazz, ImmutableSet.copyOf(excludedProperties));
- }
-
- private static List<String> flattenProperties(final Object target, final Class<?> clazz, final ImmutableSet<String> excludedProperties) {
-
- assert clazz != null;
-
- if (target == null) {
- return emptyList();
- }
-
- assert clazz.isAssignableFrom(target.getClass());
-
- try {
-
- final BeanInfo beanInfo = getBeanInfo(clazz);
- final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
-
- final List<String> serializedProperties = new ArrayList<String>();
- for (final PropertyDescriptor descriptor : descriptors) {
-
- if (excludedProperties.contains(descriptor.getName())) {
- continue;
- }
-
- serializedProperties.add(descriptor.getName());
- final Object value = descriptor.getReadMethod().invoke(target);
- serializedProperties.add(value != null ? value.toString() : "null");
-
- }
-
- return unmodifiableList(serializedProperties);
-
- } catch (IntrospectionException e) {
- s_logger.warn("Ignored IntrospectionException when serializing class " + target.getClass().getCanonicalName(), e);
- } catch (IllegalArgumentException e) {
- s_logger.warn("Ignored IllegalArgumentException when serializing class " + target.getClass().getCanonicalName(), e);
- } catch (IllegalAccessException e) {
- s_logger.warn("Ignored IllegalAccessException when serializing class " + target.getClass().getCanonicalName(), e);
- } catch (InvocationTargetException e) {
- s_logger.warn("Ignored InvocationTargetException when serializing class " + target.getClass().getCanonicalName(), e);
- }
-
- return emptyList();
-
- }
-
- public static String getEntityName(Class clz){
- if(clz == null)
- return null;
-
- String entityName = clz.getName();
- int index = entityName.lastIndexOf(".");
- if (index != -1) {
- return entityName.substring(index + 1);
- }else{
- return entityName;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ReflectionUse.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ReflectionUse.java b/utils/src/com/cloud/utils/ReflectionUse.java
deleted file mode 100644
index a5a78e2..0000000
--- a/utils/src/com/cloud/utils/ReflectionUse.java
+++ /dev/null
@@ -1,31 +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 com.cloud.utils;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-@Target({METHOD})
-@Retention(RUNTIME)
-public @interface ReflectionUse {
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/S3Utils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/S3Utils.java b/utils/src/com/cloud/utils/S3Utils.java
deleted file mode 100644
index 6efe76b..0000000
--- a/utils/src/com/cloud/utils/S3Utils.java
+++ /dev/null
@@ -1,603 +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 com.cloud.utils;
-
-import static com.amazonaws.Protocol.HTTP;
-import static com.amazonaws.Protocol.HTTPS;
-import static com.cloud.utils.StringUtils.join;
-import static java.io.File.createTempFile;
-import static java.lang.String.format;
-import static java.lang.System.currentTimeMillis;
-import static java.util.Collections.emptyList;
-import static java.util.Collections.singletonList;
-import static java.util.Collections.unmodifiableList;
-import static org.apache.commons.lang.ArrayUtils.isEmpty;
-import static org.apache.commons.lang.StringUtils.isBlank;
-import static org.apache.commons.lang.StringUtils.isNotBlank;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.UUID;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.log4j.Logger;
-
-import com.amazonaws.AmazonClientException;
-import com.amazonaws.ClientConfiguration;
-import com.amazonaws.HttpMethod;
-import com.amazonaws.auth.AWSCredentials;
-import com.amazonaws.auth.BasicAWSCredentials;
-import com.amazonaws.services.s3.AmazonS3;
-import com.amazonaws.services.s3.AmazonS3Client;
-import com.amazonaws.services.s3.model.Bucket;
-import com.amazonaws.services.s3.model.CannedAccessControlList;
-import com.amazonaws.services.s3.model.GetObjectRequest;
-import com.amazonaws.services.s3.model.ListObjectsRequest;
-import com.amazonaws.services.s3.model.ObjectListing;
-import com.amazonaws.services.s3.model.ObjectMetadata;
-import com.amazonaws.services.s3.model.PutObjectRequest;
-import com.amazonaws.services.s3.model.S3Object;
-import com.amazonaws.services.s3.model.S3ObjectSummary;
-import com.amazonaws.services.s3.transfer.TransferManager;
-import com.amazonaws.services.s3.transfer.Upload;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public final class S3Utils {
-
- private static final Logger LOGGER = Logger.getLogger(S3Utils.class);
-
- public static final String SEPARATOR = "/";
-
- private static final int MIN_BUCKET_NAME_LENGTH = 3;
- private static final int MAX_BUCKET_NAME_LENGTH = 63;
-
- private S3Utils() {
- super();
- }
-
- public static AmazonS3 acquireClient(final ClientOptions clientOptions) {
-
- final AWSCredentials credentials = new BasicAWSCredentials(clientOptions.getAccessKey(), clientOptions.getSecretKey());
-
- final ClientConfiguration configuration = new ClientConfiguration();
-
- if (clientOptions.isHttps() != null) {
- configuration.setProtocol(clientOptions.isHttps() == true ? HTTPS : HTTP);
- }
-
- if (clientOptions.getConnectionTimeout() != null) {
- configuration.setConnectionTimeout(clientOptions.getConnectionTimeout());
- }
-
- if (clientOptions.getMaxErrorRetry() != null) {
- configuration.setMaxErrorRetry(clientOptions.getMaxErrorRetry());
- }
-
- if (clientOptions.getSocketTimeout() != null) {
- configuration.setSocketTimeout(clientOptions.getSocketTimeout());
- }
-
- if (clientOptions.getUseTCPKeepAlive() != null) {
- //configuration.setUseTcpKeepAlive(clientOptions.getUseTCPKeepAlive());
- LOGGER.debug("useTCPKeepAlive not supported by old AWS SDK");
- }
-
- if (clientOptions.getConnectionTtl() != null) {
- //configuration.setConnectionTTL(clientOptions.getConnectionTtl());
- LOGGER.debug("connectionTtl not supported by old AWS SDK");
- }
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Creating S3 client with configuration: [protocol: %1$s, connectionTimeOut: " + "%2$s, maxErrorRetry: %3$s, socketTimeout: %4$s, useTCPKeepAlive: %5$s, connectionTtl: %6$s]",
- configuration.getProtocol(), configuration.getConnectionTimeout(), configuration.getMaxErrorRetry(), configuration.getSocketTimeout(),
- -1, -1));
- }
-
- final AmazonS3Client client = new AmazonS3Client(credentials, configuration);
-
- if (isNotBlank(clientOptions.getEndPoint())) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Setting the end point for S3 client %1$s to %2$s.", client, clientOptions.getEndPoint()));
- }
- client.setEndpoint(clientOptions.getEndPoint());
- }
-
- return client;
-
- }
-
- public static void putFile(final ClientOptions clientOptions, final File sourceFile, final String bucketName, final String key) {
-
- assert clientOptions != null;
- assert sourceFile != null;
- assert !isBlank(bucketName);
- assert !isBlank(key);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Sending file %1$s as S3 object %2$s in " + "bucket %3$s", sourceFile.getName(), key, bucketName));
- }
-
- acquireClient(clientOptions).putObject(bucketName, key, sourceFile);
-
- }
-
- public static void putObject(final ClientOptions clientOptions, final InputStream sourceStream, final String bucketName, final String key) {
-
- assert clientOptions != null;
- assert sourceStream != null;
- assert !isBlank(bucketName);
- assert !isBlank(key);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Sending stream as S3 object %1$s in " + "bucket %2$s", key, bucketName));
- }
-
- acquireClient(clientOptions).putObject(bucketName, key, sourceStream, null);
-
- }
-
- public static void putObject(final ClientOptions clientOptions, final PutObjectRequest req) {
-
- assert clientOptions != null;
- assert req != null;
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Sending stream as S3 object using PutObjectRequest"));
- }
-
- acquireClient(clientOptions).putObject(req);
-
- }
-
- // multi-part upload file
- public static void mputFile(final ClientOptions clientOptions, final File sourceFile, final String bucketName, final String key) throws InterruptedException {
-
- assert clientOptions != null;
- assert sourceFile != null;
- assert !isBlank(bucketName);
- assert !isBlank(key);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Multipart sending file %1$s as S3 object %2$s in " + "bucket %3$s", sourceFile.getName(), key, bucketName));
- }
- TransferManager tm = new TransferManager(S3Utils.acquireClient(clientOptions));
- Upload upload = tm.upload(bucketName, key, sourceFile);
- upload.waitForCompletion();
- }
-
- // multi-part upload object
- public static void mputObject(final ClientOptions clientOptions, final InputStream sourceStream, final String bucketName, final String key)
- throws InterruptedException {
-
- assert clientOptions != null;
- assert sourceStream != null;
- assert !isBlank(bucketName);
- assert !isBlank(key);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Multipart sending stream as S3 object %1$s in " + "bucket %2$s", key, bucketName));
- }
- TransferManager tm = new TransferManager(S3Utils.acquireClient(clientOptions));
- Upload upload = tm.upload(bucketName, key, sourceStream, null);
- upload.waitForCompletion();
- }
-
- // multi-part upload object
- public static void mputObject(final ClientOptions clientOptions, final PutObjectRequest req) throws InterruptedException {
-
- assert clientOptions != null;
- assert req != null;
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Multipart sending object to S3 using PutObjectRequest");
- }
- TransferManager tm = new TransferManager(S3Utils.acquireClient(clientOptions));
- Upload upload = tm.upload(req);
- upload.waitForCompletion();
-
- }
-
- public static void setObjectAcl(final ClientOptions clientOptions, final String bucketName, final String key, final CannedAccessControlList acl) {
-
- assert clientOptions != null;
- assert acl != null;
-
- acquireClient(clientOptions).setObjectAcl(bucketName, key, acl);
-
- }
-
- public static URL generatePresignedUrl(final ClientOptions clientOptions, final String bucketName, final String key, final Date expiration) {
-
- assert clientOptions != null;
- assert !isBlank(bucketName);
- assert !isBlank(key);
-
- return acquireClient(clientOptions).generatePresignedUrl(bucketName, key, expiration, HttpMethod.GET);
-
- }
-
- // Note that whenever S3Object is returned, client code needs to close the internal stream to avoid resource leak.
- public static S3Object getObject(final ClientOptions clientOptions, final String bucketName, final String key) {
-
- assert clientOptions != null;
- assert !isBlank(bucketName);
- assert !isBlank(key);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Get S3 object %1$s in " + "bucket %2$s", key, bucketName));
- }
-
- return acquireClient(clientOptions).getObject(bucketName, key);
-
- }
-
- @SuppressWarnings("unchecked")
- public static File getFile(final ClientOptions clientOptions, final String bucketName, final String key, final File targetDirectory,
- final FileNamingStrategy namingStrategy) {
-
- assert clientOptions != null;
- assert isNotBlank(bucketName);
- assert isNotBlank(key);
- assert targetDirectory != null && targetDirectory.isDirectory();
- assert namingStrategy != null;
-
- final AmazonS3 connection = acquireClient(clientOptions);
-
- File tempFile = null;
- try {
-
- tempFile = createTempFile(join("-", targetDirectory.getName(), currentTimeMillis(), "part"), "tmp", targetDirectory);
- tempFile.deleteOnExit();
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Downloading object %1$s from bucket %2$s to temp file %3$s", key, bucketName, tempFile.getName()));
- }
-
- try {
- connection.getObject(new GetObjectRequest(bucketName, key), tempFile);
- } catch (AmazonClientException ex) {
- // hack to handle different ETAG format generated from RiakCS for multi-part uploaded object
- String msg = ex.getMessage();
- if (!msg.contains("verify integrity")) {
- throw ex;
- }
- }
-
- final File targetFile = new File(targetDirectory, namingStrategy.determineFileName(key));
- tempFile.renameTo(targetFile);
-
- return targetFile;
-
- } catch (FileNotFoundException e) {
-
- throw new CloudRuntimeException(format("Failed open file %1$s in order to get object %2$s from bucket %3$s.", targetDirectory.getAbsoluteFile(), bucketName,
- key), e);
-
- } catch (IOException e) {
-
- throw new CloudRuntimeException(format("Unable to allocate temporary file in directory %1$s to download %2$s:%3$s from S3",
- targetDirectory.getAbsolutePath(), bucketName, key), e);
-
- } finally {
-
- if (tempFile != null) {
- tempFile.delete();
- }
-
- }
-
- }
-
- public static List<File> getDirectory(final ClientOptions clientOptions, final String bucketName, final String sourcePath, final File targetDirectory,
- final FileNamingStrategy namingStrategy) {
-
- assert clientOptions != null;
- assert isNotBlank(bucketName);
- assert isNotBlank(sourcePath);
- assert targetDirectory != null;
-
- final AmazonS3 connection = acquireClient(clientOptions);
-
- // List the objects in the source directory on S3
- final List<S3ObjectSummary> objectSummaries = listDirectory(bucketName, sourcePath, connection);
- final List<File> files = new ArrayList<File>();
-
- for (final S3ObjectSummary objectSummary : objectSummaries) {
-
- files.add(getFile(clientOptions, bucketName, objectSummary.getKey(), targetDirectory, namingStrategy));
-
- }
-
- return unmodifiableList(files);
-
- }
-
- public static List<S3ObjectSummary> getDirectory(final ClientOptions clientOptions, final String bucketName, final String sourcePath) {
- assert clientOptions != null;
- assert isNotBlank(bucketName);
- assert isNotBlank(sourcePath);
-
- final AmazonS3 connection = acquireClient(clientOptions);
-
- // List the objects in the source directory on S3
- return listDirectory(bucketName, sourcePath, connection);
- }
-
- private static List<S3ObjectSummary> listDirectory(final String bucketName, final String directory, final AmazonS3 client) {
-
- List<S3ObjectSummary> objects = new ArrayList<S3ObjectSummary>();
- ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName).withPrefix(directory + SEPARATOR);
-
- ObjectListing ol = client.listObjects(listObjectsRequest);
- if(ol.isTruncated()) {
- do {
- objects.addAll(ol.getObjectSummaries());
- listObjectsRequest.setMarker(ol.getNextMarker());
- ol = client.listObjects(listObjectsRequest);
- } while (ol.isTruncated());
- }
- else {
- objects.addAll(ol.getObjectSummaries());
- }
-
- if (objects.isEmpty()) {
- return emptyList();
- }
-
- return unmodifiableList(objects);
- }
-
- public static void putDirectory(final ClientOptions clientOptions, final String bucketName, final File directory, final FilenameFilter fileNameFilter,
- final ObjectNamingStrategy namingStrategy) {
-
- assert clientOptions != null;
- assert isNotBlank(bucketName);
- assert directory != null && directory.isDirectory();
- assert fileNameFilter != null;
- assert namingStrategy != null;
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Putting directory %1$s in S3 bucket %2$s.", directory.getAbsolutePath(), bucketName));
- }
-
- // Determine the list of files to be sent using the passed filter ...
- final File[] files = directory.listFiles(fileNameFilter);
-
- if (LOGGER.isTraceEnabled()) {
- LOGGER.trace(format("Putting files (%1$s) in S3 bucket %2$s.", ArrayUtils.toString(files, "no files found"), bucketName));
- }
-
- // Skip spinning up an S3 connection when no files will be sent ...
- if (isEmpty(files)) {
- return;
- }
-
- final AmazonS3 client = acquireClient(clientOptions);
-
- // Send the files to S3 using the passed ObjectNaming strategy to
- // determine the key ...
- for (final File file : files) {
- final String key = namingStrategy.determineKey(file);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(format("Putting file %1$s into bucket %2$s with key %3$s.", file.getAbsolutePath(), bucketName, key));
- }
- client.putObject(bucketName, key, file);
- }
-
- }
-
- public static void deleteObject(final ClientOptions clientOptions, final String bucketName, final String key) {
-
- assert clientOptions != null;
- assert isNotBlank(bucketName);
- assert isNotBlank(key);
-
- final AmazonS3 client = acquireClient(clientOptions);
-
- client.deleteObject(bucketName, key);
-
- }
-
- public static void deleteDirectory(final ClientOptions clientOptions, final String bucketName, final String directoryName) {
-
- assert clientOptions != null;
- assert isNotBlank(bucketName);
- assert isNotBlank(directoryName);
-
- final AmazonS3 client = acquireClient(clientOptions);
-
- final List<S3ObjectSummary> objects = listDirectory(bucketName, directoryName, client);
-
- for (final S3ObjectSummary object : objects) {
-
- client.deleteObject(bucketName, object.getKey());
-
- }
-
- client.deleteObject(bucketName, directoryName);
-
- }
-
- public static boolean canConnect(final ClientOptions clientOptions) {
-
- try {
-
- acquireClient(clientOptions);
- return true;
-
- } catch (AmazonClientException e) {
-
- LOGGER.warn("Ignored Exception while checking connection options", e);
- return false;
-
- }
-
- }
-
- public static boolean doesBucketExist(final ClientOptions clientOptions, final String bucketName) {
-
- assert clientOptions != null;
- assert !isBlank(bucketName);
-
- try {
-
- final List<Bucket> buckets = acquireClient(clientOptions).listBuckets();
-
- for (Bucket bucket : buckets) {
- if (bucket.getName().equals(bucketName)) {
- return true;
- }
- }
-
- return false;
-
- } catch (AmazonClientException e) {
-
- LOGGER.warn("Ignored Exception while checking bucket existence", e);
- return false;
-
- }
-
- }
-
- public static boolean canReadWriteBucket(final ClientOptions clientOptions, final String bucketName) {
-
- assert clientOptions != null;
- assert isNotBlank(bucketName);
-
- try {
-
- final AmazonS3 client = acquireClient(clientOptions);
-
- final String fileContent = "testing put and delete";
- final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes());
- final String key = UUID.randomUUID().toString() + ".txt";
-
- final ObjectMetadata metadata = new ObjectMetadata();
- metadata.setContentLength(fileContent.length());
-
- client.putObject(bucketName, key, inputStream, metadata);
- client.deleteObject(bucketName, key);
-
- return true;
-
- } catch (AmazonClientException e) {
-
- return false;
-
- }
-
- }
-
- public static List<String> checkClientOptions(ClientOptions clientOptions) {
-
- assert clientOptions != null;
-
- List<String> errorMessages = new ArrayList<String>();
-
- errorMessages.addAll(checkRequiredField("access key", clientOptions.getAccessKey()));
- errorMessages.addAll(checkRequiredField("secret key", clientOptions.getSecretKey()));
-
- errorMessages.addAll(checkOptionalField("connection timeout", clientOptions.getConnectionTimeout()));
- errorMessages.addAll(checkOptionalField("socket timeout", clientOptions.getSocketTimeout()));
- errorMessages.addAll(checkOptionalField("max error retries", clientOptions.getMaxErrorRetry()));
- errorMessages.addAll(checkOptionalField("connection ttl", clientOptions.getConnectionTtl()));
-
- return unmodifiableList(errorMessages);
-
- }
-
- public static List<String> checkBucketName(final String bucketLabel, final String bucket) {
-
- assert isNotBlank(bucketLabel);
- assert isNotBlank(bucket);
-
- final List<String> errorMessages = new ArrayList<String>();
-
- if (bucket.length() < MIN_BUCKET_NAME_LENGTH) {
- errorMessages.add(format("The length of %1$s " + "for the %2$s must have a length of at least %3$s " + "characters", bucket, bucketLabel,
- MIN_BUCKET_NAME_LENGTH));
- }
-
- if (bucket.length() > MAX_BUCKET_NAME_LENGTH) {
- errorMessages.add(format("The length of %1$s " + "for the %2$s must not have a length of at greater" + " than %3$s characters", bucket, bucketLabel,
- MAX_BUCKET_NAME_LENGTH));
- }
-
- return unmodifiableList(errorMessages);
-
- }
-
- private static List<String> checkOptionalField(final String fieldName, final Integer fieldValue) {
- if (fieldValue != null && fieldValue < 0) {
- return singletonList(format("The value of %1$s must " + "be greater than zero.", fieldName));
- }
- return emptyList();
- }
-
- private static List<String> checkRequiredField(String fieldName, String fieldValue) {
- if (isBlank(fieldValue)) {
- return singletonList(format("A %1$s must be specified.", fieldName));
- }
- return emptyList();
- }
-
- public interface ClientOptions {
-
- String getAccessKey();
-
- String getSecretKey();
-
- String getEndPoint();
-
- Boolean isHttps();
-
- Integer getConnectionTimeout();
-
- Integer getMaxErrorRetry();
-
- Integer getSocketTimeout();
-
- Boolean getUseTCPKeepAlive();
-
- Integer getConnectionTtl();
- }
-
- public interface ObjectNamingStrategy {
-
- String determineKey(File file);
-
- }
-
- public interface FileNamingStrategy {
-
- String determineFileName(String key);
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/SerialVersionUID.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/SerialVersionUID.java b/utils/src/com/cloud/utils/SerialVersionUID.java
deleted file mode 100644
index e4ea217..0000000
--- a/utils/src/com/cloud/utils/SerialVersionUID.java
+++ /dev/null
@@ -1,69 +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 com.cloud.utils;
-
-/**
- * purposes. This is purely on an honor system though. You should always
- **/
-public interface SerialVersionUID {
- public static final long Base = 0x564D4F70 << 32; // 100 brownie points if you guess what this is and tell me.
-
- public static final long UUID = Base | 0x1;
- public static final long CloudRuntimeException = Base | 0x2;
- public static final long CloudStartupServlet = Base | 0x3;
- public static final long CloudServiceImpl = Base | 0x4;
- public static final long AccountLimitException = Base | 0x5;
- public static final long InsufficientVirtualNetworkCapacityException = Base | 0x7;
- public static final long NetworkUnavailableException = Base | 0x8;
- public static final long Ip = Base | 0x9;
- public static final long UnsupportedVersionException = Base | 0xb;
- public static final long DataCenterIpAddressPK = Base | 0xc;
- public static final long UnableToExecuteException = Base | 0xd;
- public static final long ExecutionException = Base | 0xe;
- public static final long VnetKey = Base | 0xf;
- public static final long InsufficientServerCapacityException = Base | 0x10;
- public static final long InsufficientAddressCapacityException = Base | 0x11;
- public static final long ManagementServerException = Base | 0x12;
- public static final long HAStateException = Base | 0x13;
- public static final long InsufficientStorageCapacityException = Base | 0x14;
- public static final long InsufficientCapacityException = Base | 0x15;
- public static final long ConcurrentOperationException = Base | 0x16;
- public static final long AgentUnavailableException = Base | 0x17;
- public static final long OperationTimedoutException = Base | 0x18;
- public static final long StorageUnavailableException = Base | 0x19;
- public static final long InfficientVirtualNetworkCapacityException = Base | 0x1a;
- public static final long DiscoveryException = Base | 0x1b;
- public static final long ConflictingNetworkSettingException = Base | 0x1c;
- public static final long CloudAuthenticationException = Base | 0x1d;
- public static final long AsyncCommandQueued = Base | 0x1e;
- public static final long ResourceUnavailableException = Base | 0x1f;
- public static final long ConnectionException = Base | 0x20;
- public static final long PermissionDeniedException = Base | 0x21;
- public static final long sshException = Base | 0x22;
- public static final long HttpCallException = Base | 0x23;
- public static final long VirtualMachineMigrationException = Base | 0x24;
- public static final long DiscoveredWithErrorException = Base | 0x25;
- public static final long NoTransitionException = Base | 0x26;
- public static final long CloudExecutionException = Base | 0x27;
- public static final long CallFailedException = Base | 0x28;
- public static final long UnableDeleteHostException = Base | 0x29;
- public static final long AffinityConflictException = Base | 0x2a;
- public static final long JobCancellationException = Base | 0x2b;
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/StringUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/StringUtils.java b/utils/src/com/cloud/utils/StringUtils.java
deleted file mode 100644
index c598be8..0000000
--- a/utils/src/com/cloud/utils/StringUtils.java
+++ /dev/null
@@ -1,323 +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 com.cloud.utils;
-
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.owasp.esapi.StringUtilities;
-
-public class StringUtils {
- private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
-
- private static Charset preferredACSCharset;
- private static final String UTF8 = "UTF-8";
-
- static {
- if (isUtf8Supported()) {
- preferredACSCharset = Charset.forName(UTF8);
- } else {
- preferredACSCharset = Charset.defaultCharset();
- }
- }
-
- public static Charset getPreferredCharset() {
- return preferredACSCharset;
- }
-
- public static boolean isUtf8Supported() {
- return Charset.isSupported(UTF8);
- }
-
- protected static Charset getDefaultCharset() {
- return Charset.defaultCharset();
- }
-
- public static String join(final Iterable<? extends Object> iterable, final String delim) {
- final StringBuilder sb = new StringBuilder();
- if (iterable != null) {
- final Iterator<? extends Object> iter = iterable.iterator();
- if (iter.hasNext()) {
- final Object next = iter.next();
- sb.append(next.toString());
- }
- while (iter.hasNext()) {
- final Object next = iter.next();
- sb.append(delim + next.toString());
- }
- }
- return sb.toString();
- }
-
- public static String join(final String delimiter, final Object... components) {
- return org.apache.commons.lang.StringUtils.join(components, delimiter);
- }
-
- public static boolean isNotBlank(final String str) {
- if (str != null && str.trim().length() > 0) {
- return true;
- }
-
- return false;
- }
-
- public static String cleanupTags(String tags) {
- if (tags != null) {
- final String[] tokens = tags.split(",");
- final StringBuilder t = new StringBuilder();
- for (int i = 0; i < tokens.length; i++) {
- t.append(tokens[i].trim()).append(",");
- }
- t.delete(t.length() - 1, t.length());
- tags = t.toString();
- }
-
- return tags;
- }
-
- /**
- * @param tags
- * @return List of tags
- */
- public static List<String> csvTagsToList(final String tags) {
- final List<String> tagsList = new ArrayList<String>();
-
- if (tags != null) {
- final String[] tokens = tags.split(",");
- for (int i = 0; i < tokens.length; i++) {
- tagsList.add(tokens[i].trim());
- }
- }
-
- return tagsList;
- }
-
- /**
- * Converts a List of tags to a comma separated list
- * @param tags
- * @return String containing a comma separated list of tags
- */
-
- public static String listToCsvTags(final List<String> tagsList) {
- final StringBuilder tags = new StringBuilder();
- if (tagsList.size() > 0) {
- for (int i = 0; i < tagsList.size(); i++) {
- tags.append(tagsList.get(i));
- if (i != tagsList.size() - 1) {
- tags.append(',');
- }
- }
- }
-
- return tags.toString();
- }
-
- public static String getExceptionStackInfo(final Throwable e) {
- final StringBuffer sb = new StringBuffer();
-
- sb.append(e.toString()).append("\n");
- final StackTraceElement[] elemnents = e.getStackTrace();
- for (final StackTraceElement element : elemnents) {
- sb.append(element.getClassName()).append(".");
- sb.append(element.getMethodName()).append("(");
- sb.append(element.getFileName()).append(":");
- sb.append(element.getLineNumber()).append(")");
- sb.append("\n");
- }
-
- return sb.toString();
- }
-
- public static String unicodeEscape(final String s) {
- final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < s.length(); i++) {
- final char c = s.charAt(i);
- if (c >> 7 > 0) {
- sb.append("\\u");
- sb.append(hexChar[c >> 12 & 0xF]); // append the hex character for the left-most 4-bits
- sb.append(hexChar[c >> 8 & 0xF]); // hex for the second group of 4-bits from the left
- sb.append(hexChar[c >> 4 & 0xF]); // hex for the third group
- sb.append(hexChar[c & 0xF]); // hex for the last group, e.g., the right most 4-bits
- } else {
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
- public static String getMaskedPasswordForDisplay(final String password) {
- if (password == null || password.isEmpty()) {
- return "*";
- }
-
- final StringBuffer sb = new StringBuffer();
- sb.append(password.charAt(0));
- for (int i = 1; i < password.length(); i++) {
- sb.append("*");
- }
-
- return sb.toString();
- }
-
- // removes a password request param and it's value, also considering password is in query parameter value which has been url encoded
- private static final Pattern REGEX_PASSWORD_QUERYSTRING = Pattern.compile("(&|%26)?[^(&|%26)]*((p|P)assword|accesskey|secretkey)(=|%3D).*?(?=(%26|[&'\"]|$))");
-
- // removes a password/accesskey/ property from a response json object
- private static final Pattern REGEX_PASSWORD_JSON = Pattern.compile("\"((p|P)assword|accesskey|secretkey)\":\\s?\".*?\",?");
-
- private static final Pattern REGEX_PASSWORD_DETAILS = Pattern.compile("(&|%26)?details(\\[|%5B)\\d*(\\]|%5D)\\.key(=|%3D)((p|P)assword|accesskey|secretkey)(?=(%26|[&'\"]))");
-
- private static final Pattern REGEX_PASSWORD_DETAILS_INDEX = Pattern.compile("details(\\[|%5B)\\d*(\\]|%5D)");
-
- private static final Pattern REGEX_REDUNDANT_AND = Pattern.compile("(&|%26)(&|%26)+");
-
- // Responsible for stripping sensitive content from request and response strings
- public static String cleanString(final String stringToClean) {
- String cleanResult = "";
- if (stringToClean != null) {
- cleanResult = REGEX_PASSWORD_QUERYSTRING.matcher(stringToClean).replaceAll("");
- cleanResult = REGEX_PASSWORD_JSON.matcher(cleanResult).replaceAll("");
- final Matcher detailsMatcher = REGEX_PASSWORD_DETAILS.matcher(cleanResult);
- while (detailsMatcher.find()) {
- final Matcher detailsIndexMatcher = REGEX_PASSWORD_DETAILS_INDEX.matcher(detailsMatcher.group());
- if (detailsIndexMatcher.find()) {
- cleanResult = cleanDetails(cleanResult, detailsIndexMatcher.group());
- }
- }
- }
- return cleanResult;
- }
-
- public static String cleanDetails(final String stringToClean, final String detailsIndexSting) {
- String cleanResult = stringToClean;
- for (final String log : stringToClean.split("&|%26")) {
- if (log.contains(detailsIndexSting)) {
- cleanResult = cleanResult.replace(log, "");
- }
- }
- cleanResult = REGEX_REDUNDANT_AND.matcher(cleanResult).replaceAll("&");
- return cleanResult;
- }
-
- public static boolean areTagsEqual(final String tags1, final String tags2) {
- if (tags1 == null && tags2 == null) {
- return true;
- }
-
- if (tags1 != null && tags2 == null) {
- return false;
- }
-
- if (tags1 == null && tags2 != null) {
- return false;
- }
-
- final String delimiter = ",";
-
- final List<String> lstTags1 = new ArrayList<String>();
- final String[] aTags1 = tags1.split(delimiter);
-
- for (final String tag1 : aTags1) {
- lstTags1.add(tag1.toLowerCase());
- }
-
- final List<String> lstTags2 = new ArrayList<String>();
- final String[] aTags2 = tags2.split(delimiter);
-
- for (final String tag2 : aTags2) {
- lstTags2.add(tag2.toLowerCase());
- }
-
- return lstTags1.containsAll(lstTags2) && lstTags2.containsAll(lstTags1);
- }
-
- public static String stripControlCharacters(final String s) {
- return StringUtilities.stripControls(s);
- }
-
- public static int formatForOutput(final String text, final int start, final int columns, final char separator) {
- if (start >= text.length()) {
- return -1;
- }
-
- int end = start + columns;
- if (end > text.length()) {
- end = text.length();
- }
- final String searchable = text.substring(start, end);
- final int found = searchable.lastIndexOf(separator);
- return found > 0 ? found : end - start;
- }
-
- public static Map<String, String> stringToMap(final String s) {
- final Map<String, String> map = new HashMap<String, String>();
- final String[] elements = s.split(";");
- for (final String parts : elements) {
- final String[] keyValue = parts.split(":");
- map.put(keyValue[0], keyValue[1]);
- }
- return map;
- }
-
- public static String mapToString(final Map<String, String> map) {
- String s = "";
- for (final Map.Entry<String, String> entry : map.entrySet()) {
- s += entry.getKey() + ":" + entry.getValue() + ";";
- }
- if (s.length() > 0) {
- s = s.substring(0, s.length() - 1);
- }
- return s;
- }
-
- public static <T> List<T> applyPagination(final List<T> originalList, final Long startIndex, final Long pageSizeVal) {
- // Most likely pageSize will never exceed int value, and we need integer to partition the listToReturn
- final boolean applyPagination = startIndex != null && pageSizeVal != null
- && startIndex <= Integer.MAX_VALUE && startIndex >= Integer.MIN_VALUE && pageSizeVal <= Integer.MAX_VALUE
- && pageSizeVal >= Integer.MIN_VALUE;
- List<T> listWPagination = null;
- if (applyPagination) {
- listWPagination = new ArrayList<>();
- final int index = startIndex.intValue() == 0 ? 0 : startIndex.intValue() / pageSizeVal.intValue();
- final List<List<T>> partitions = StringUtils.partitionList(originalList, pageSizeVal.intValue());
- if (index < partitions.size()) {
- listWPagination = partitions.get(index);
- }
- }
- return listWPagination;
- }
-
- private static <T> List<List<T>> partitionList(final List<T> originalList, final int chunkSize) {
- final List<List<T>> listOfChunks = new ArrayList<List<T>>();
- for (int i = 0; i < originalList.size() / chunkSize; i++) {
- listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize + chunkSize));
- }
- if (originalList.size() % chunkSize != 0) {
- listOfChunks.add(originalList.subList(originalList.size() - originalList.size() % chunkSize, originalList.size()));
- }
- return listOfChunks;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/SwiftUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/SwiftUtil.java b/utils/src/com/cloud/utils/SwiftUtil.java
deleted file mode 100644
index 1136818..0000000
--- a/utils/src/com/cloud/utils/SwiftUtil.java
+++ /dev/null
@@ -1,239 +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 com.cloud.utils;
-
-import java.io.File;
-import java.util.Arrays;
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.script.OutputInterpreter;
-import com.cloud.utils.script.Script;
-
-public class SwiftUtil {
- private static Logger logger = Logger.getLogger(SwiftUtil.class);
- private static final long SWIFT_MAX_SIZE = 5L * 1024L * 1024L * 1024L;
-
- public interface SwiftClientCfg {
- String getAccount();
-
- String getUserName();
-
- String getKey();
-
- String getEndPoint();
- }
-
- private static String getSwiftCLIPath() {
- String swiftCLI = Script.findScript("scripts/storage/secondary", "swift");
- if (swiftCLI == null) {
- logger.debug("Can't find swift cli at scripts/storage/secondary/swift");
- throw new CloudRuntimeException("Can't find swift cli at scripts/storage/secondary/swift");
- }
- return swiftCLI;
- }
-
- public static boolean postMeta(SwiftClientCfg cfg, String container, String object, Map<String, String> metas) {
- String swiftCli = getSwiftCLIPath();
- StringBuilder cms = new StringBuilder();
- for (Map.Entry<String, String> entry : metas.entrySet()) {
- cms.append(" -m ");
- cms.append(entry.getKey());
- cms.append(":");
- cms.append(entry.getValue());
- cms.append(" ");
- }
- Script command = new Script("/bin/bash", logger);
- command.add("-c");
- command.add("/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() + " -K " + cfg.getKey() + " post " +
- container + " " + object + " " + cms.toString());
- OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
- String result = command.execute(parser);
- if (result != null) {
- throw new CloudRuntimeException("Failed to post meta" + result);
- }
- return true;
- }
-
- public static String putObject(SwiftClientCfg cfg, File srcFile, String container, String fileName) {
- String swiftCli = getSwiftCLIPath();
- if (fileName == null) {
- fileName = srcFile.getName();
- }
- String srcDirectory = srcFile.getParent();
- Script command = new Script("/bin/bash", logger);
- long size = srcFile.length();
- command.add("-c");
- if (size <= SWIFT_MAX_SIZE) {
- command.add("cd " + srcDirectory + ";/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() +
- " -K " + cfg.getKey() + " upload " + container + " " + fileName);
- } else {
- command.add("cd " + srcDirectory + ";/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() +
- " -K " + cfg.getKey() + " upload -S " + SWIFT_MAX_SIZE + " " + container + " " + fileName);
- }
- OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
- String result = command.execute(parser);
- if (result != null) {
- throw new CloudRuntimeException("Failed to upload file: " + result);
- }
-
- if (parser.getLines() != null) {
- String[] lines = parser.getLines().split("\\n");
- for (String line : lines) {
- if (line.contains("Errno") || line.contains("failed") || line.contains("not found")) {
- throw new CloudRuntimeException("Failed to upload file: " + Arrays.toString(lines));
- }
- }
- }
-
- return container + File.separator + srcFile.getName();
- }
-
- private static StringBuilder buildSwiftCmd(SwiftClientCfg swift) {
- String swiftCli = getSwiftCLIPath();
- StringBuilder sb = new StringBuilder();
- sb.append(" /usr/bin/python ");
- sb.append(swiftCli);
- sb.append(" -A ");
- sb.append(swift.getEndPoint());
- sb.append(" -U ");
- sb.append(swift.getAccount());
- sb.append(":");
- sb.append(swift.getUserName());
- sb.append(" -K ");
- sb.append(swift.getKey());
- sb.append(" ");
- return sb;
- }
-
- public static String[] list(SwiftClientCfg swift, String container, String rFilename) {
- getSwiftCLIPath();
- Script command = new Script("/bin/bash", logger);
- command.add("-c");
-
- StringBuilder swiftCmdBuilder = buildSwiftCmd(swift);
- swiftCmdBuilder.append(" list ");
- swiftCmdBuilder.append(container);
-
- if (rFilename != null) {
- swiftCmdBuilder.append(" -p ");
- swiftCmdBuilder.append(rFilename);
- }
-
- command.add(swiftCmdBuilder.toString());
- OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
- String result = command.execute(parser);
- if (result == null && parser.getLines() != null && !parser.getLines().equalsIgnoreCase("")) {
- String[] lines = parser.getLines().split("\\n");
- return lines;
- } else {
- if (result != null) {
- String errMsg = "swiftList failed , err=" + result;
- logger.debug("Failed to list " + errMsg);
- } else {
- String errMsg = "swiftList failed, no lines returns";
- logger.debug("Failed to list " + errMsg);
- }
- }
- return new String[0];
- }
-
- public static File getObject(SwiftClientCfg cfg, File destDirectory, String swiftPath) {
- int firstIndexOfSeparator = swiftPath.indexOf(File.separator);
- String container = swiftPath.substring(0, firstIndexOfSeparator);
- String srcPath = swiftPath.substring(firstIndexOfSeparator + 1);
- String destFilePath = null;
- if (destDirectory.isDirectory()) {
- destFilePath = destDirectory.getAbsolutePath() + File.separator + srcPath;
- } else {
- destFilePath = destDirectory.getAbsolutePath();
- }
- String swiftCli = getSwiftCLIPath();
- Script command = new Script("/bin/bash", logger);
- command.add("-c");
- command.add("/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() + " -K " + cfg.getKey() +
- " download " + container + " " + srcPath + " -o " + destFilePath);
- OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
- String result = command.execute(parser);
- if (result != null) {
- String errMsg = "swiftDownload failed err=" + result;
- logger.debug(errMsg);
- throw new CloudRuntimeException("failed to get object: " + swiftPath);
- }
- if (parser.getLines() != null) {
- String[] lines = parser.getLines().split("\\n");
- for (String line : lines) {
- if (line.contains("Errno") || line.contains("failed")) {
- String errMsg = "swiftDownload failed , err=" + Arrays.toString(lines);
- logger.debug(errMsg);
- throw new CloudRuntimeException("Failed to get object: " + swiftPath);
- }
- }
- }
- return new File(destFilePath);
- }
-
- public static String getContainerName(String type, Long id) {
- if (type.startsWith("T")) {
- return "T-" + id;
- } else if (type.startsWith("S")) {
- return "S-" + id;
- } else if (type.startsWith("V")) {
- return "V-" + id;
- }
- return null;
- }
-
- public static String[] splitSwiftPath(String path) {
- int index = path.indexOf(File.separator);
- if (index == -1) {
- return null;
- }
- String[] paths = new String[2];
- paths[0] = path.substring(0, index);
- paths[1] = path.substring(index + 1);
- return paths;
- }
-
- public static boolean deleteObject(SwiftClientCfg cfg, String path) {
- Script command = new Script("/bin/bash", logger);
- command.add("-c");
-
- String[] paths = splitSwiftPath(path);
- if (paths == null) {
- return false;
- }
- String container = paths[0];
- String objectName = paths[1];
-
- StringBuilder swiftCmdBuilder = buildSwiftCmd(cfg);
- swiftCmdBuilder.append(" delete ");
- swiftCmdBuilder.append(container);
- swiftCmdBuilder.append(" ");
- swiftCmdBuilder.append(objectName);
-
- command.add(swiftCmdBuilder.toString());
- OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
- command.execute(parser);
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/Ternary.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/Ternary.java b/utils/src/com/cloud/utils/Ternary.java
deleted file mode 100644
index fdc2fc9..0000000
--- a/utils/src/com/cloud/utils/Ternary.java
+++ /dev/null
@@ -1,85 +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 com.cloud.utils;
-
-public class Ternary<T, U, V> {
- private T t;
- private U u;
- private V v;
-
- public Ternary(T t, U u, V v) {
- this.t = t;
- this.u = u;
- this.v = v;
- }
-
- public T first() {
- return t;
- }
-
- public void first(T t) {
- this.t = t;
- }
-
- public U second() {
- return u;
- }
-
- public void second(U u) {
- this.u = u;
- }
-
- public V third() {
- return v;
- }
-
- public void third(V v) {
- this.v = v;
- }
-
- @Override
- // Note: This means any two pairs with null for both values will match each
- // other but what can I do? This is due to stupid type erasure.
- public
- int hashCode() {
- return (t != null ? t.hashCode() : 0) | (u != null ? u.hashCode() : 0) | (v != null ? v.hashCode() : 0);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof Ternary)) {
- return false;
- }
- Ternary<?, ?, ?> that = (Ternary<?, ?, ?>)obj;
- return (t != null ? t.equals(that.t) : that.t == null) && (u != null ? u.equals(that.u) : that.u == null) && (v != null ? v.equals(that.v) : that.v == null);
- }
-
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder("T[");
- b.append(t != null ? t.toString() : "null");
- b.append(":");
- b.append(u != null ? u.toString() : "null");
- b.append(":");
- b.append(v != null ? v.toString() : "null");
- b.append("]");
- return b.toString();
- }
-}
[37/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
deleted file mode 100644
index a0d7dc2..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
+++ /dev/null
@@ -1,68 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpTag;
-import com.cloud.network.nicira.VifAttachment;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.resource.NiciraNvpUtilities;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = UpdateLogicalSwitchPortCommand.class)
-public final class NiciraNvpUpdateLogicalSwitchPortCommandWrapper extends CommandWrapper<UpdateLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final UpdateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
-
- final String logicalSwitchUuid = command.getLogicalSwitchUuid();
- final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
- final String attachmentUuid = command.getAttachmentUuid();
-
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- // Tags set to scope cs_account and account name
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
-
- final VifAttachment vifAttachment = niciraNvpUtilities.createVifAttachment(attachmentUuid);
-
- niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment);
- return new UpdateLogicalSwitchPortAnswer(command, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, UpdateLogicalSwitchPortAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
deleted file mode 100644
index 92c198a..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
+++ /dev/null
@@ -1,89 +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 com.cloud.network.utils;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.Command;
-import com.cloud.resource.ServerResource;
-
-public class CommandRetryUtility {
-
- private static final Logger s_logger = Logger.getLogger(CommandRetryUtility.class);
-
- private static final int ZERO = 0;
- private static CommandRetryUtility instance;
-
- static {
- instance = new CommandRetryUtility();
- }
-
- private final ConcurrentHashMap<Command, Integer> commandsToRetry;
- private ServerResource serverResource;
-
- private CommandRetryUtility() {
- commandsToRetry = new ConcurrentHashMap<Command, Integer>();
- }
-
- public static CommandRetryUtility getInstance() {
- return instance;
- }
-
- public void setServerResource(final ServerResource serverResource) {
- this.serverResource = serverResource;
- }
-
- public boolean addRetry(final Command command, final int retries) {
- if (commandsToRetry.containsKey(command)) {
- // A retry already exists for this command, do not add it again.
- // Once all retries are executed, the command will be removed from the map.
- return false;
- }
- commandsToRetry.put(command, retries);
- return true;
- }
-
- public Answer retry(final Command command, final Class<? extends Answer> answerClass, final Exception error) {
- if (commandsToRetry.containsKey(command)) {
- Integer numRetries = commandsToRetry.get(command);
-
- if (numRetries > ZERO) {
- commandsToRetry.put(command, --numRetries);
-
- s_logger.warn("Retrying " + command.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
-
- return serverResource.executeRequest(command);
- } else {
- commandsToRetry.remove(command);
- }
- }
- try {
- final Constructor<? extends Answer> answerConstructor = answerClass.getConstructor(Command.class, Exception.class);
- return answerConstructor.newInstance(command, error);
- } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- return Answer.createUnsupportedCommandAnswer(command);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java
new file mode 100644
index 0000000..1765a81
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java
@@ -0,0 +1,35 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+/**
+ *
+ */
+public class ConfigurePortForwardingRulesOnLogicalRouterAnswer extends Answer {
+
+ public ConfigurePortForwardingRulesOnLogicalRouterAnswer(final Command command, final boolean success, final String details) {
+ super(command, success, details);
+ }
+
+ public ConfigurePortForwardingRulesOnLogicalRouterAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java
new file mode 100644
index 0000000..133714e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java
@@ -0,0 +1,63 @@
+//
+// 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 com.cloud.agent.api;
+
+import java.util.List;
+
+import com.cloud.agent.api.to.PortForwardingRuleTO;
+
+/**
+ *
+ */
+public class ConfigurePortForwardingRulesOnLogicalRouterCommand extends Command {
+
+ private String logicalRouterUuid;
+ private List<PortForwardingRuleTO> rules;
+
+ public ConfigurePortForwardingRulesOnLogicalRouterCommand(final String logicalRouterUuid, final List<PortForwardingRuleTO> rules) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ this.rules = rules;
+ }
+
+ public String getLogicalRouterUuid() {
+ return logicalRouterUuid;
+ }
+
+ public void setLogicalRouterUuid(final String logicalRouterUuid) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ }
+
+ public List<PortForwardingRuleTO> getRules() {
+ return rules;
+ }
+
+ public void setRules(final List<PortForwardingRuleTO> rules) {
+ this.rules = rules;
+ }
+
+ /* (non-Javadoc)
+ * @see com.cloud.agent.api.Command#executeInSequence()
+ */
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java
new file mode 100644
index 0000000..9da6caf
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.agent.api;
+
+public class ConfigurePublicIpsOnLogicalRouterAnswer extends Answer {
+
+ public ConfigurePublicIpsOnLogicalRouterAnswer(final Command command, final boolean success, final String details) {
+ super(command, success, details);
+ }
+
+ public ConfigurePublicIpsOnLogicalRouterAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java
new file mode 100644
index 0000000..ff81ae4
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java
@@ -0,0 +1,66 @@
+//
+// 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 com.cloud.agent.api;
+
+import java.util.List;
+
+public class ConfigurePublicIpsOnLogicalRouterCommand extends Command {
+
+ private String logicalRouterUuid;
+ private String l3GatewayServiceUuid;
+ private List<String> publicCidrs;
+
+ public ConfigurePublicIpsOnLogicalRouterCommand(final String logicalRouterUuid, final String l3GatewayServiceUuid, final List<String> publicCidrs) {
+ super();
+ this.logicalRouterUuid = logicalRouterUuid;
+ this.publicCidrs = publicCidrs;
+ this.l3GatewayServiceUuid = l3GatewayServiceUuid;
+ }
+
+ public String getLogicalRouterUuid() {
+ return logicalRouterUuid;
+ }
+
+ public void setLogicalRouterUuid(final String logicalRouterUuid) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ }
+
+ public String getL3GatewayServiceUuid() {
+ return l3GatewayServiceUuid;
+ }
+
+ public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) {
+ this.l3GatewayServiceUuid = l3GatewayServiceUuid;
+ }
+
+ public List<String> getPublicCidrs() {
+ return publicCidrs;
+ }
+
+ public void setPublicCidrs(final List<String> publicCidrs) {
+ this.publicCidrs = publicCidrs;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java
new file mode 100644
index 0000000..9074491
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+/**
+ *
+ */
+public class ConfigureStaticNatRulesOnLogicalRouterAnswer extends Answer {
+
+ /**
+ * @param command
+ * @param success
+ * @param details
+ */
+ public ConfigureStaticNatRulesOnLogicalRouterAnswer(final Command command, final boolean success, final String details) {
+ super(command, success, details);
+ }
+
+ /**
+ * @param command
+ * @param e
+ */
+ public ConfigureStaticNatRulesOnLogicalRouterAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java
new file mode 100644
index 0000000..b5434b3
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java
@@ -0,0 +1,65 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+import java.util.List;
+
+import com.cloud.agent.api.to.StaticNatRuleTO;
+
+/**
+ *
+ */
+public class ConfigureStaticNatRulesOnLogicalRouterCommand extends Command {
+
+ private String logicalRouterUuid;
+ private List<StaticNatRuleTO> rules;
+
+ public ConfigureStaticNatRulesOnLogicalRouterCommand(final String logicalRouterUuid, final List<StaticNatRuleTO> rules) {
+ super();
+ this.logicalRouterUuid = logicalRouterUuid;
+ this.rules = rules;
+
+ }
+
+ public String getLogicalRouterUuid() {
+ return logicalRouterUuid;
+ }
+
+ public void setLogicalRouterUuid(final String logicalRouterUuid) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ }
+
+ public List<StaticNatRuleTO> getRules() {
+ return rules;
+ }
+
+ public void setRules(final List<StaticNatRuleTO> rules) {
+ this.rules = rules;
+ }
+
+ /* (non-Javadoc)
+ * @see com.cloud.agent.api.Command#executeInSequence()
+ */
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java
new file mode 100644
index 0000000..0172891
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java
@@ -0,0 +1,42 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+/**
+ *
+ */
+public class CreateLogicalRouterAnswer extends Answer {
+
+ private String logicalRouterUuid;
+
+ public CreateLogicalRouterAnswer(final Command command, final boolean success, final String details, final String logicalRouterUuid) {
+ super(command, success, details);
+ this.logicalRouterUuid = logicalRouterUuid;
+ }
+
+ public CreateLogicalRouterAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+ public String getLogicalRouterUuid() {
+ return logicalRouterUuid;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java
new file mode 100644
index 0000000..ff12b8d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java
@@ -0,0 +1,116 @@
+//
+// 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 com.cloud.agent.api;
+
+/**
+ *
+ */
+public class CreateLogicalRouterCommand extends Command {
+ private String gatewayServiceUuid;
+ private String logicalSwitchUuid;
+ private long vlanId;
+ private String name;
+ private String ownerName;
+ private String publicIpCidr;
+ private String publicNextHop;
+ private String internalIpCidr;
+
+ public CreateLogicalRouterCommand(final String gatewayServiceUuid, final long vlanId, final String logicalSwitchUuid, final String name, final String publicIpCidr,
+ final String publicNextHop, final String internalIpCidr, final String ownerName) {
+ super();
+ this.gatewayServiceUuid = gatewayServiceUuid;
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ this.vlanId = vlanId;
+ this.name = name;
+ this.ownerName = ownerName;
+ this.publicIpCidr = publicIpCidr;
+ this.publicNextHop = publicNextHop;
+ this.internalIpCidr = internalIpCidr;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+ public String getGatewayServiceUuid() {
+ return gatewayServiceUuid;
+ }
+
+ public void setGatewayServiceUuid(final String gatewayServiceUuid) {
+ this.gatewayServiceUuid = gatewayServiceUuid;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+ public void setLogicalSwitchUuid(final String logicalSwitchUuid) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ }
+
+ public long getVlanId() {
+ return vlanId;
+ }
+
+ public void setVlanId(final long vlanId) {
+ this.vlanId = vlanId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getOwnerName() {
+ return ownerName;
+ }
+
+ public void setOwnerName(final String ownerName) {
+ this.ownerName = ownerName;
+ }
+
+ public String getPublicIpCidr() {
+ return publicIpCidr;
+ }
+
+ public void setPublicIpCidr(final String publicIpCidr) {
+ this.publicIpCidr = publicIpCidr;
+ }
+
+ public String getInternalIpCidr() {
+ return internalIpCidr;
+ }
+
+ public void setInternalIpCidr(final String internalIpCidr) {
+ this.internalIpCidr = internalIpCidr;
+ }
+
+ public String getPublicNextHop() {
+ return publicNextHop;
+ }
+
+ public void setPublicNextHop(final String publicNextHop) {
+ this.publicNextHop = publicNextHop;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java
new file mode 100644
index 0000000..ee9924e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.agent.api;
+
+public class CreateLogicalSwitchAnswer extends Answer {
+ private String logicalSwitchUuid;
+
+ public CreateLogicalSwitchAnswer(final Command command, final boolean success, final String details, final String logicalSwitchUuid) {
+ super(command, success, details);
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ }
+
+ public CreateLogicalSwitchAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java
new file mode 100644
index 0000000..5dc8616
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java
@@ -0,0 +1,57 @@
+//
+// 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 com.cloud.agent.api;
+
+public class CreateLogicalSwitchCommand extends Command {
+
+ private final String transportUuid;
+ private final String transportType;
+ private final String name;
+ private final String ownerName;
+
+ public CreateLogicalSwitchCommand(final String transportUuid, final String transportType, final String name, final String ownerName) {
+ this.transportUuid = transportUuid;
+ this.transportType = transportType;
+ this.name = name;
+ this.ownerName = ownerName;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+ public String getTransportUuid() {
+ return transportUuid;
+ }
+
+ public String getTransportType() {
+ return transportType;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getOwnerName() {
+ return ownerName;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java
new file mode 100644
index 0000000..8b09389
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.agent.api;
+
+public class CreateLogicalSwitchPortAnswer extends Answer {
+ private String logicalSwitchPortUuid;
+
+ public CreateLogicalSwitchPortAnswer(final Command command, final boolean success, final String details, final String localSwitchPortUuid) {
+ super(command, success, details);
+ logicalSwitchPortUuid = localSwitchPortUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwitchPortUuid;
+ }
+
+ public CreateLogicalSwitchPortAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java
new file mode 100644
index 0000000..6bc578f
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java
@@ -0,0 +1,56 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+public class CreateLogicalSwitchPortCommand extends Command {
+ private final String logicalSwitchUuid;
+ private final String attachmentUuid;
+ private final String ownerName;
+ private final String nicName;
+
+ public CreateLogicalSwitchPortCommand(final String logicalSwitchUuid, final String attachmentUuid, final String ownerName, final String nicName) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ this.attachmentUuid = attachmentUuid;
+ this.ownerName = ownerName;
+ this.nicName = nicName;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+ public String getAttachmentUuid() {
+ return attachmentUuid;
+ }
+
+ public String getOwnerName() {
+ return ownerName;
+ }
+
+ public String getNicName() {
+ return nicName;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java
new file mode 100644
index 0000000..f7f101d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+/**
+ *
+ */
+public class DeleteLogicalRouterAnswer extends Answer {
+
+ public DeleteLogicalRouterAnswer(final Command command, final boolean success, final String details) {
+ super(command, success, details);
+ }
+
+ public DeleteLogicalRouterAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java
new file mode 100644
index 0000000..8fd14e9
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+/**
+ *
+ */
+public class DeleteLogicalRouterCommand extends Command {
+
+ private final String logicalRouterUuid;
+
+ public DeleteLogicalRouterCommand(String logicalRouterUuid) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ }
+
+ /* (non-Javadoc)
+ * @see com.cloud.agent.api.Command#executeInSequence()
+ */
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+ public String getLogicalRouterUuid() {
+ return logicalRouterUuid;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java
new file mode 100644
index 0000000..e2c483f
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.agent.api;
+
+public class DeleteLogicalSwitchAnswer extends Answer {
+
+ public DeleteLogicalSwitchAnswer(final Command command, final boolean success, final String details) {
+ super(command, success, details);
+ }
+
+ public DeleteLogicalSwitchAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java
new file mode 100644
index 0000000..dbfefe2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.agent.api;
+
+public class DeleteLogicalSwitchCommand extends Command {
+
+ private final String logicalSwitchUuid;
+
+ public DeleteLogicalSwitchCommand(final String logicalSwitchUuid) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java
new file mode 100644
index 0000000..1cd87ea
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.agent.api;
+
+public class DeleteLogicalSwitchPortAnswer extends Answer {
+
+ public DeleteLogicalSwitchPortAnswer(final Command command, final boolean success, final String details) {
+ super(command, success, details);
+ }
+
+ public DeleteLogicalSwitchPortAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java
new file mode 100644
index 0000000..4a5e607
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+public class DeleteLogicalSwitchPortCommand extends Command {
+ private final String logicalSwitchUuid;
+ private final String logicalSwithPortUuid;
+
+ public DeleteLogicalSwitchPortCommand(final String logicalSwitchUuid, final String logicalSwitchPortUuid) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ logicalSwithPortUuid = logicalSwitchPortUuid;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwithPortUuid;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java
new file mode 100644
index 0000000..0524531
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.agent.api;
+
+public class FindLogicalSwitchPortAnswer extends Answer {
+ private String logicalSwitchPortUuid;
+
+ public FindLogicalSwitchPortAnswer(final Command command, final boolean success, final String details, final String localSwitchPortUuid) {
+ super(command, success, details);
+ logicalSwitchPortUuid = localSwitchPortUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwitchPortUuid;
+ }
+
+ public FindLogicalSwitchPortAnswer(final Command command, final Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java
new file mode 100644
index 0000000..ee00bd2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.agent.api;
+
+public class FindLogicalSwitchPortCommand extends Command {
+ private final String logicalSwitchUuid;
+ private final String logicalSwitchPortUuid;
+
+ public FindLogicalSwitchPortCommand(String logicalSwitchUuid, String logicalSwitchPortUuid) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ this.logicalSwitchPortUuid = logicalSwitchPortUuid;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwitchPortUuid;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java
new file mode 100644
index 0000000..9597d2f
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java
@@ -0,0 +1,30 @@
+//
+// 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 com.cloud.agent.api;
+
+import com.cloud.host.Host;
+
+public class StartupNiciraNvpCommand extends StartupCommand {
+
+ public StartupNiciraNvpCommand() {
+ super(Host.Type.L2Networking);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java
new file mode 100644
index 0000000..1471723
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.agent.api;
+
+public class UpdateLogicalSwitchPortAnswer extends Answer {
+ private String logicalSwitchPortUuid;
+
+ public UpdateLogicalSwitchPortAnswer(Command command, boolean success, String details, String localSwitchPortUuid) {
+ super(command, success, details);
+ logicalSwitchPortUuid = localSwitchPortUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwitchPortUuid;
+ }
+
+ public UpdateLogicalSwitchPortAnswer(Command command, Exception e) {
+ super(command, e);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java
new file mode 100644
index 0000000..91682a1
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java
@@ -0,0 +1,63 @@
+//
+// 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 com.cloud.agent.api;
+
+public class UpdateLogicalSwitchPortCommand extends Command {
+ private final String logicalSwitchUuid;
+ private final String logicalSwitchPortUuid;
+ private final String attachmentUuid;
+ private final String ownerName;
+ private final String nicName;
+
+ public UpdateLogicalSwitchPortCommand(final String logicalSwitchPortUuid, final String logicalSwitchUuid, final String attachmentUuid, final String ownerName,
+ final String nicName) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ this.logicalSwitchPortUuid = logicalSwitchPortUuid;
+ this.attachmentUuid = attachmentUuid;
+ this.ownerName = ownerName;
+ this.nicName = nicName;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwitchPortUuid;
+ }
+
+ public String getAttachmentUuid() {
+ return attachmentUuid;
+ }
+
+ public String getOwnerName() {
+ return ownerName;
+ }
+
+ public String getNicName() {
+ return nicName;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java
new file mode 100644
index 0000000..1a9be28
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java
@@ -0,0 +1,154 @@
+//
+// 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 com.cloud.api.commands;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
+import org.apache.cloudstack.context.CallContext;
+
+import com.cloud.api.response.NiciraNvpDeviceResponse;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.network.element.NiciraNvpElementService;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "addNiciraNvpDevice", responseObject = NiciraNvpDeviceResponse.class, description = "Adds a Nicira NVP device",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd {
+ private static final String s_name = "addniciranvpdeviceresponse";
+ @Inject
+ protected NiciraNvpElementService niciraNvpElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID,
+ type = CommandType.UUID,
+ entityType = PhysicalNetworkResponse.class,
+ required = true,
+ description = "the Physical Network ID")
+ private Long physicalNetworkId;
+
+ @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname of ip address of the Nicira NVP Controller.")
+ private String host;
+
+ @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to access the Nicira Controller API")
+ private String username;
+
+ @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to access the Nicira Controller API")
+ private String password;
+
+ @Parameter(name = ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID,
+ type = CommandType.STRING,
+ required = true,
+ description = "The Transportzone UUID configured on the Nicira Controller")
+ private String transportzoneuuid;
+
+ @Parameter(name = ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID,
+ type = CommandType.STRING,
+ required = false,
+ description = "The L3 Gateway Service UUID configured on the Nicira Controller")
+ private String l3gatewayserviceuuid;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getPhysicalNetworkId() {
+ return physicalNetworkId;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getTransportzoneUuid() {
+ return transportzoneuuid;
+ }
+
+ public String getL3GatewayServiceUuid() {
+ return l3gatewayserviceuuid;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+ ResourceAllocationException {
+ try {
+ NiciraNvpDeviceVO niciraNvpDeviceVO = niciraNvpElementService.addNiciraNvpDevice(this);
+ if (niciraNvpDeviceVO != null) {
+ NiciraNvpDeviceResponse response = niciraNvpElementService.createNiciraNvpDeviceResponse(niciraNvpDeviceVO);
+ response.setObjectName("niciranvpdevice");
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error.");
+ }
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return CallContext.current().getCallingAccount().getId();
+ }
+
+ @Override
+ public String getEventType() {
+ return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_ADD;
+ }
+
+ @Override
+ public String getEventDescription() {
+ return "Adding a Nicira Nvp Controller";
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java
new file mode 100644
index 0000000..d3fadea
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java
@@ -0,0 +1,112 @@
+//
+// 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 com.cloud.api.commands;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.cloudstack.context.CallContext;
+
+import com.cloud.api.response.NiciraNvpDeviceResponse;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.element.NiciraNvpElementService;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "deleteNiciraNvpDevice", responseObject = SuccessResponse.class, description = " delete a nicira nvp device",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd {
+ private static final String s_name = "deleteniciranvpdeviceresponse";
+ @Inject
+ protected NiciraNvpElementService niciraNvpElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID,
+ type = CommandType.UUID,
+ entityType = NiciraNvpDeviceResponse.class,
+ required = true,
+ description = "Nicira device ID")
+ private Long niciraNvpDeviceId;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getNiciraNvpDeviceId() {
+ return niciraNvpDeviceId;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+ ResourceAllocationException {
+ try {
+ boolean result = niciraNvpElementService.deleteNiciraNvpDevice(this);
+ if (result) {
+ SuccessResponse response = new SuccessResponse(getCommandName());
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Nicira device.");
+ }
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return CallContext.current().getCallingAccount().getId();
+ }
+
+ @Override
+ public String getEventType() {
+ return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_DELETE;
+ }
+
+ @Override
+ public String getEventDescription() {
+ return "Deleting Nicira Nvp Controller";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java
new file mode 100644
index 0000000..a3217cc
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java
@@ -0,0 +1,111 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.api.commands;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ResponseObject.ResponseView;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.NetworkResponse;
+
+import com.cloud.api.response.NiciraNvpDeviceResponse;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.Network;
+import com.cloud.network.element.NiciraNvpElementService;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "listNiciraNvpDeviceNetworks", responseObject = NetworkResponse.class, description = "lists network that are using a nicira nvp device",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd {
+
+ public static final Logger s_logger = Logger.getLogger(ListNiciraNvpDeviceNetworksCmd.class.getName());
+ private static final String s_name = "listniciranvpdevicenetworks";
+ @Inject
+ protected NiciraNvpElementService niciraNvpElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID,
+ type = CommandType.UUID,
+ entityType = NiciraNvpDeviceResponse.class,
+ required = true,
+ description = "nicira nvp device ID")
+ private Long niciraNvpDeviceId;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getNiciraNvpDeviceId() {
+ return niciraNvpDeviceId;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+ ResourceAllocationException {
+ try {
+ List<? extends Network> networks = niciraNvpElementService.listNiciraNvpDeviceNetworks(this);
+ ListResponse<NetworkResponse> response = new ListResponse<NetworkResponse>();
+ List<NetworkResponse> networkResponses = new ArrayList<NetworkResponse>();
+
+ if (networks != null && !networks.isEmpty()) {
+ for (Network network : networks) {
+ NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Full, network);
+ networkResponses.add(networkResponse);
+ }
+ }
+
+ response.setResponses(networkResponses);
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java
new file mode 100644
index 0000000..6cc8f5d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java
@@ -0,0 +1,108 @@
+//
+// 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 com.cloud.api.commands;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
+
+import com.cloud.api.response.NiciraNvpDeviceResponse;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.network.element.NiciraNvpElementService;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "listNiciraNvpDevices", responseObject = NiciraNvpDeviceResponse.class, description = "Lists Nicira NVP devices",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class ListNiciraNvpDevicesCmd extends BaseListCmd {
+ private static final String s_name = "listniciranvpdeviceresponse";
+
+ @Inject
+ protected NiciraNvpElementService niciraNvpElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "the Physical Network ID")
+ private Long physicalNetworkId;
+
+ @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID, type = CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, description = "nicira nvp device ID")
+ private Long niciraNvpDeviceId;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getNiciraNvpDeviceId() {
+ return niciraNvpDeviceId;
+ }
+
+ public Long getPhysicalNetworkId() {
+ return physicalNetworkId;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {
+ try {
+ List<NiciraNvpDeviceVO> niciraDevices = niciraNvpElementService.listNiciraNvpDevices(this);
+ ListResponse<NiciraNvpDeviceResponse> response = new ListResponse<NiciraNvpDeviceResponse>();
+ List<NiciraNvpDeviceResponse> niciraDevicesResponse = new ArrayList<NiciraNvpDeviceResponse>();
+
+ if (niciraDevices != null && !niciraDevices.isEmpty()) {
+ for (NiciraNvpDeviceVO niciraDeviceVO : niciraDevices) {
+ NiciraNvpDeviceResponse niciraDeviceResponse = niciraNvpElementService.createNiciraNvpDeviceResponse(niciraDeviceVO);
+ niciraDevicesResponse.add(niciraDeviceResponse);
+ }
+ }
+
+ response.setResponses(niciraDevicesResponse);
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java
new file mode 100644
index 0000000..46287aa
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java
@@ -0,0 +1,89 @@
+//
+// 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 com.cloud.api.response;
+
+import com.google.gson.annotations.SerializedName;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+import org.apache.cloudstack.api.EntityReference;
+
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.serializer.Param;
+
+@EntityReference(value = NiciraNvpDeviceVO.class)
+public class NiciraNvpDeviceResponse extends BaseResponse {
+ @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID)
+ @Param(description = "device id of the Nicire Nvp")
+ private String id;
+
+ @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID)
+ @Param(description = "the physical network to which this Nirica Nvp belongs to")
+ private String physicalNetworkId;
+
+ @SerializedName(ApiConstants.PROVIDER)
+ @Param(description = "name of the provider")
+ private String providerName;
+
+ @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_NAME)
+ @Param(description = "device name")
+ private String deviceName;
+
+ @SerializedName(ApiConstants.HOST_NAME)
+ @Param(description = "the controller Ip address")
+ private String hostName;
+
+ @SerializedName(ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID)
+ @Param(description = "the transport zone Uuid")
+ private String transportZoneUuid;
+
+ @SerializedName(ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID)
+ @Param(description = "this L3 gateway service Uuid")
+ private String l3GatewayServiceUuid;
+
+ public void setId(String nvpDeviceId) {
+ this.id = nvpDeviceId;
+ }
+
+ public void setPhysicalNetworkId(final String physicalNetworkId) {
+ this.physicalNetworkId = physicalNetworkId;
+ }
+
+ public void setProviderName(final String providerName) {
+ this.providerName = providerName;
+ }
+
+ public void setDeviceName(final String deviceName) {
+ this.deviceName = deviceName;
+ }
+
+ public void setHostName(final String hostName) {
+ this.hostName = hostName;
+ }
+
+ public void setTransportZoneUuid(final String transportZoneUuid) {
+ this.transportZoneUuid = transportZoneUuid;
+ }
+
+ public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) {
+ this.l3GatewayServiceUuid = l3GatewayServiceUuid;
+ }
+
+}
[34/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java
new file mode 100644
index 0000000..ea5df2c
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java
@@ -0,0 +1,40 @@
+//
+// 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 com.cloud.network.nicira;
+
+/**
+ *
+ */
+public class SingleDefaultRouteImplicitRoutingConfig extends RoutingConfig {
+ public RouterNextHop defaultRouteNextHop;
+ public final String type = "SingleDefaultRouteImplicitRoutingConfig";
+
+ public SingleDefaultRouteImplicitRoutingConfig(final RouterNextHop routerNextHop) {
+ defaultRouteNextHop = routerNextHop;
+ }
+
+ public RouterNextHop getDefaultRouteNextHop() {
+ return defaultRouteNextHop;
+ }
+
+ public void setDefaultRouteNextHop(final RouterNextHop defaultRouteNextHop) {
+ this.defaultRouteNextHop = defaultRouteNextHop;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java
new file mode 100644
index 0000000..b95cb9a
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java
@@ -0,0 +1,119 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class SourceNatRule extends NatRule {
+ private String toSourceIpAddressMax;
+ private String toSourceIpAddressMin;
+ private Integer toSourcePort;
+
+ public SourceNatRule() {
+ setType("SourceNatRule");
+ }
+
+ public String getToSourceIpAddressMax() {
+ return toSourceIpAddressMax;
+ }
+
+ public void setToSourceIpAddressMax(final String toSourceIpAddressMax) {
+ this.toSourceIpAddressMax = toSourceIpAddressMax;
+ }
+
+ public String getToSourceIpAddressMin() {
+ return toSourceIpAddressMin;
+ }
+
+ public void setToSourceIpAddressMin(final String toSourceIpAddressMin) {
+ this.toSourceIpAddressMin = toSourceIpAddressMin;
+ }
+
+ public Integer getToSourcePort() {
+ return toSourcePort;
+ }
+
+ public void setToSourcePort(final Integer toSourcePort) {
+ this.toSourcePort = toSourcePort;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result + ((toSourceIpAddressMax == null) ? 0 : toSourceIpAddressMax.hashCode());
+ result = prime * result + ((toSourceIpAddressMin == null) ? 0 : toSourceIpAddressMin.hashCode());
+ result = prime * result + ((toSourcePort == null) ? 0 : toSourcePort.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (!super.equals(obj))
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ SourceNatRule other = (SourceNatRule)obj;
+ if (toSourceIpAddressMax == null) {
+ if (other.toSourceIpAddressMax != null)
+ return false;
+ } else if (!toSourceIpAddressMax.equals(other.toSourceIpAddressMax))
+ return false;
+ if (toSourceIpAddressMin == null) {
+ if (other.toSourceIpAddressMin != null)
+ return false;
+ } else if (!toSourceIpAddressMin.equals(other.toSourceIpAddressMin))
+ return false;
+ if (toSourcePort == null) {
+ if (other.toSourcePort != null)
+ return false;
+ } else if (!toSourcePort.equals(other.toSourcePort))
+ return false;
+ return true;
+ }
+
+ @Override
+ public boolean equalsIgnoreUuid(final Object obj) {
+ if (this == obj)
+ return true;
+ if (!super.equalsIgnoreUuid(obj))
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ SourceNatRule other = (SourceNatRule)obj;
+ if (toSourceIpAddressMax == null) {
+ if (other.toSourceIpAddressMax != null)
+ return false;
+ } else if (!toSourceIpAddressMax.equals(other.toSourceIpAddressMax))
+ return false;
+ if (toSourceIpAddressMin == null) {
+ if (other.toSourceIpAddressMin != null)
+ return false;
+ } else if (!toSourceIpAddressMin.equals(other.toSourceIpAddressMin))
+ return false;
+ if (toSourcePort == null) {
+ if (other.toSourcePort != null)
+ return false;
+ } else if (!toSourcePort.equals(other.toSourcePort))
+ return false;
+ return true;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java
new file mode 100644
index 0000000..c643876
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java
@@ -0,0 +1,50 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class TransportZoneBinding {
+ private String zoneUuid;
+ private String transportType;
+
+ public TransportZoneBinding() {
+ }
+
+ public TransportZoneBinding(String zoneUuid, String transportType) {
+ this.zoneUuid = zoneUuid;
+ this.transportType = transportType;
+ }
+
+ public String getZoneUuid() {
+ return zoneUuid;
+ }
+
+ public void setZoneUuid(String zoneUuid) {
+ this.zoneUuid = zoneUuid;
+ }
+
+ public String getTransportType() {
+ return transportType;
+ }
+
+ public void setTransportType(String transportType) {
+ this.transportType = transportType;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java
new file mode 100644
index 0000000..fe7d93a
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java
@@ -0,0 +1,78 @@
+//
+// 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 com.cloud.network.nicira;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.commons.lang.builder.ReflectionToStringBuilder;
+import org.apache.commons.lang.builder.ToStringStyle;
+
+public class VifAttachment extends Attachment {
+ private final String type = "VifAttachment";
+ private String vifUuid;
+
+ public VifAttachment() {
+ }
+
+ public VifAttachment(final String vifUuid) {
+ this.vifUuid = vifUuid;
+ }
+
+ public String getVifUuid() {
+ return vifUuid;
+ }
+
+ public void setVifUuid(final String vifUuid) {
+ this.vifUuid = vifUuid;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+
+ @Override
+ public String toString() {
+ return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 31)
+ .append(this.getClass())
+ .append(vifUuid)
+ .toHashCode();
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (!(this.getClass().isInstance(obj))) {
+ return false;
+ }
+ final VifAttachment another = (VifAttachment) obj;
+ return new EqualsBuilder().append(vifUuid, another.vifUuid).isEquals();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java
new file mode 100644
index 0000000..9d261b2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java
@@ -0,0 +1,77 @@
+//
+// 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 com.cloud.network.resource;
+
+import java.util.Hashtable;
+import java.util.Set;
+
+import org.reflections.Reflections;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.RequestWrapper;
+import com.cloud.resource.ServerResource;
+
+public class NiciraNvpRequestWrapper extends RequestWrapper {
+
+ private static NiciraNvpRequestWrapper instance;
+
+ static {
+ instance = new NiciraNvpRequestWrapper();
+ }
+
+ Reflections baseWrappers = new Reflections("com.cloud.network.resource.wrapper");
+ @SuppressWarnings("rawtypes")
+ Set<Class<? extends CommandWrapper>> baseSet = baseWrappers.getSubTypesOf(CommandWrapper.class);
+
+ private NiciraNvpRequestWrapper() {
+ init();
+ }
+
+ @SuppressWarnings("rawtypes")
+ private void init() {
+ // NiciraNvpResource commands
+ final Hashtable<Class<? extends Command>, CommandWrapper> niciraCommands = processAnnotations(baseSet);
+
+ resources.put(NiciraNvpResource.class, niciraCommands);
+ }
+
+ public static NiciraNvpRequestWrapper getInstance() {
+ return instance;
+ }
+
+ @SuppressWarnings({"rawtypes" })
+ @Override
+ public Answer execute(final Command command, final ServerResource serverResource) {
+ final Class<? extends ServerResource> resourceClass = serverResource.getClass();
+
+ final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands = retrieveResource(command, resourceClass);
+
+ CommandWrapper<Command, Answer, ServerResource> commandWrapper = retrieveCommands(command.getClass(), resourceCommands);
+
+ while (commandWrapper == null) {
+ //Could not find the command in the given resource, will traverse the family tree.
+ commandWrapper = retryWhenAllFails(command, resourceClass, resourceCommands);
+ }
+
+ return commandWrapper.execute(command, serverResource);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
new file mode 100644
index 0000000..df40db4
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
@@ -0,0 +1,319 @@
+//
+// 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 com.cloud.network.resource;
+
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.IAgentControl;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.PingCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.StartupNiciraNvpCommand;
+import com.cloud.host.Host;
+import com.cloud.host.Host.Type;
+import com.cloud.network.nicira.ControlClusterStatus;
+import com.cloud.network.nicira.DestinationNatRule;
+import com.cloud.network.nicira.Match;
+import com.cloud.network.nicira.NatRule;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.SourceNatRule;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.ServerResource;
+
+public class NiciraNvpResource implements ServerResource {
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
+
+ public static final int NAME_MAX_LEN = 40;
+ public static final int NUM_RETRIES = 2;
+
+ private String name;
+ private String guid;
+ private String zoneId;
+
+ private NiciraNvpApi niciraNvpApi;
+ private NiciraNvpUtilities niciraNvpUtilities;
+ private CommandRetryUtility retryUtility;
+
+ protected NiciraNvpApi createNiciraNvpApi() {
+ return new NiciraNvpApi();
+ }
+
+ @Override
+ public boolean configure(final String ignoredName, final Map<String, Object> params) throws ConfigurationException {
+
+ name = (String)params.get("name");
+ if (name == null) {
+ throw new ConfigurationException("Unable to find name");
+ }
+
+ guid = (String)params.get("guid");
+ if (guid == null) {
+ throw new ConfigurationException("Unable to find the guid");
+ }
+
+ zoneId = (String)params.get("zoneId");
+ if (zoneId == null) {
+ throw new ConfigurationException("Unable to find zone");
+ }
+
+ final String ip = (String)params.get("ip");
+ if (ip == null) {
+ throw new ConfigurationException("Unable to find IP");
+ }
+
+ final String adminuser = (String)params.get("adminuser");
+ if (adminuser == null) {
+ throw new ConfigurationException("Unable to find admin username");
+ }
+
+ final String adminpass = (String)params.get("adminpass");
+ if (adminpass == null) {
+ throw new ConfigurationException("Unable to find admin password");
+ }
+
+ niciraNvpUtilities = NiciraNvpUtilities.getInstance();
+ retryUtility = CommandRetryUtility.getInstance();
+ retryUtility.setServerResource(this);
+
+ niciraNvpApi = createNiciraNvpApi();
+ niciraNvpApi.setControllerAddress(ip);
+ niciraNvpApi.setAdminCredentials(adminuser, adminpass);
+
+ return true;
+ }
+
+ public NiciraNvpApi getNiciraNvpApi() {
+ return niciraNvpApi;
+ }
+
+ public NiciraNvpUtilities getNiciraNvpUtilities() {
+ return niciraNvpUtilities;
+ }
+
+ public CommandRetryUtility getRetryUtility() {
+ return retryUtility;
+ }
+
+ @Override
+ public boolean start() {
+ return true;
+ }
+
+ @Override
+ public boolean stop() {
+ return true;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public Type getType() {
+ // Think up a better name for this Type?
+ return Host.Type.L2Networking;
+ }
+
+ @Override
+ public StartupCommand[] initialize() {
+ final StartupNiciraNvpCommand sc = new StartupNiciraNvpCommand();
+ sc.setGuid(guid);
+ sc.setName(name);
+ sc.setDataCenter(zoneId);
+ sc.setPod("");
+ sc.setPrivateIpAddress("");
+ sc.setStorageIpAddress("");
+ sc.setVersion(NiciraNvpResource.class.getPackage().getImplementationVersion());
+ return new StartupCommand[] {sc};
+ }
+
+ @Override
+ public PingCommand getCurrentStatus(final long id) {
+ try {
+ final ControlClusterStatus ccs = niciraNvpApi.getControlClusterStatus();
+ if (!"stable".equals(ccs.getClusterStatus())) {
+ s_logger.error("ControlCluster state is not stable: " + ccs.getClusterStatus());
+ return null;
+ }
+ } catch (final NiciraNvpApiException e) {
+ s_logger.error("getControlClusterStatus failed", e);
+ return null;
+ }
+ return new PingCommand(Host.Type.L2Networking, id);
+ }
+
+ @Override
+ public Answer executeRequest(final Command cmd) {
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ try {
+ return wrapper.execute(cmd, this);
+ } catch (final Exception e) {
+ s_logger.debug("Received unsupported command " + cmd.toString());
+ return Answer.createUnsupportedCommandAnswer(cmd);
+ }
+ }
+
+ @Override
+ public void disconnected() {
+ }
+
+ @Override
+ public IAgentControl getAgentControl() {
+ return null;
+ }
+
+ @Override
+ public void setAgentControl(final IAgentControl agentControl) {
+ }
+
+ public String natRuleToString(final NatRule rule) {
+
+ final StringBuilder natRuleStr = new StringBuilder();
+ natRuleStr.append("Rule ");
+ natRuleStr.append(rule.getUuid());
+ natRuleStr.append(" (");
+ natRuleStr.append(rule.getType());
+ natRuleStr.append(") :");
+ final Match m = rule.getMatch();
+ natRuleStr.append("match (");
+ natRuleStr.append(m.getProtocol());
+ natRuleStr.append(" ");
+ natRuleStr.append(m.getSourceIpAddresses());
+ natRuleStr.append(" [");
+ natRuleStr.append(m.getSourcePort());
+ natRuleStr.append(" ] -> ");
+ natRuleStr.append(m.getDestinationIpAddresses());
+ natRuleStr.append(" [");
+ natRuleStr.append(m.getDestinationPort());
+ natRuleStr.append(" ]) -->");
+ if ("SourceNatRule".equals(rule.getType())) {
+ natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMin());
+ natRuleStr.append("-");
+ natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMax());
+ natRuleStr.append(" [");
+ natRuleStr.append(((SourceNatRule)rule).getToSourcePort());
+ natRuleStr.append(" ])");
+ } else {
+ natRuleStr.append(((DestinationNatRule)rule).getToDestinationIpAddress());
+ natRuleStr.append(" [");
+ natRuleStr.append(((DestinationNatRule)rule).getToDestinationPort());
+ natRuleStr.append(" ])");
+ }
+ return natRuleStr.toString();
+ }
+
+ public String truncate(final String string, final int length) {
+ if (string.length() <= length) {
+ return string;
+ } else {
+ return string.substring(0, length);
+ }
+ }
+
+ public NatRule[] generateStaticNatRulePair(final String insideIp, final String outsideIp) {
+ final NatRule[] rulepair = new NatRule[2];
+ rulepair[0] = new DestinationNatRule();
+ rulepair[0].setType("DestinationNatRule");
+ rulepair[0].setOrder(100);
+ rulepair[1] = new SourceNatRule();
+ rulepair[1].setType("SourceNatRule");
+ rulepair[1].setOrder(100);
+
+ Match m = new Match();
+ m.setDestinationIpAddresses(outsideIp);
+ rulepair[0].setMatch(m);
+ ((DestinationNatRule)rulepair[0]).setToDestinationIpAddress(insideIp);
+
+ // create matching snat rule
+ m = new Match();
+ m.setSourceIpAddresses(insideIp);
+ rulepair[1].setMatch(m);
+ ((SourceNatRule)rulepair[1]).setToSourceIpAddressMin(outsideIp);
+ ((SourceNatRule)rulepair[1]).setToSourceIpAddressMax(outsideIp);
+
+ return rulepair;
+
+ }
+
+ public NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts,
+ final String protocol) {
+ // Start with a basic static nat rule, then add port and protocol details
+ final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp);
+
+ ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]);
+ rulepair[0].getMatch().setDestinationPort(outsidePorts[0]);
+ rulepair[0].setOrder(50);
+ rulepair[0].getMatch().setEthertype("IPv4");
+ if ("tcp".equals(protocol)) {
+ rulepair[0].getMatch().setProtocol(6);
+ } else if ("udp".equals(protocol)) {
+ rulepair[0].getMatch().setProtocol(17);
+ }
+
+ ((SourceNatRule)rulepair[1]).setToSourcePort(outsidePorts[0]);
+ rulepair[1].getMatch().setSourcePort(insidePorts[0]);
+ rulepair[1].setOrder(50);
+ rulepair[1].getMatch().setEthertype("IPv4");
+ if ("tcp".equals(protocol)) {
+ rulepair[1].getMatch().setProtocol(6);
+ } else if ("udp".equals(protocol)) {
+ rulepair[1].getMatch().setProtocol(17);
+ }
+
+ return rulepair;
+
+ }
+
+ @Override
+ public void setName(final String name) {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void setConfigParams(final Map<String, Object> params) {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public Map<String, Object> getConfigParams() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getRunLevel() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public void setRunLevel(final int level) {
+ // TODO Auto-generated method stub
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java
new file mode 100644
index 0000000..4edf5c3
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java
@@ -0,0 +1,65 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.resource;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.VifAttachment;
+
+public class NiciraNvpUtilities {
+
+ private static NiciraNvpUtilities instance;
+
+ static {
+ instance = new NiciraNvpUtilities();
+ }
+
+ private NiciraNvpUtilities() {
+ }
+
+ public static NiciraNvpUtilities getInstance() {
+ return instance;
+ }
+
+ public LogicalSwitch createLogicalSwitch() {
+ final LogicalSwitch logicalSwitch = new LogicalSwitch();
+ return logicalSwitch;
+ }
+
+ public LogicalSwitchPort createLogicalSwitchPort(final CreateLogicalSwitchPortCommand command) {
+ final String attachmentUuid = command.getAttachmentUuid();
+
+ // Tags set to scope cs_account and account name
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+
+ final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
+ return logicalSwitchPort;
+ }
+
+ public VifAttachment createVifAttachment(final String attachmentUuid) {
+ return new VifAttachment(attachmentUuid);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
new file mode 100644
index 0000000..89e7a6e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
@@ -0,0 +1,120 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.to.PortForwardingRuleTO;
+import com.cloud.network.nicira.NatRule;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class)
+public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends CommandWrapper<ConfigurePortForwardingRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigurePortForwardingRulesCommandWrapper.class);
+
+ @Override
+ public Answer execute(final ConfigurePortForwardingRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+ try {
+ final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
+ // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
+ // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
+ // Any other SourceNat rule should have a corresponding DestinationNat rule
+
+ for (final PortForwardingRuleTO rule : command.getRules()) {
+ if (rule.isAlreadyAdded() && !rule.revoked()) {
+ // Don't need to do anything
+ continue;
+ }
+
+ if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1]) {
+ return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, false, "Nicira NVP doesn't support port ranges for port forwarding");
+ }
+
+ final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
+
+ NatRule incoming = null;
+ NatRule outgoing = null;
+
+ for (final NatRule storedRule : existingRules.getResults()) {
+ if (storedRule.equalsIgnoreUuid(rulepair[1])) {
+ // The outgoing rule exists
+ outgoing = storedRule;
+ s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
+ if (incoming != null) {
+ break;
+ }
+ } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
+ // The incoming rule exists
+ incoming = storedRule;
+ s_logger.debug("Found matching incoming rule " + incoming.getUuid());
+ if (outgoing != null) {
+ break;
+ }
+ }
+ }
+ if (incoming != null && outgoing != null) {
+ if (rule.revoked()) {
+ s_logger.debug("Deleting incoming rule " + incoming.getUuid());
+ niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid());
+
+ s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
+ niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid());
+ }
+ } else {
+ if (rule.revoked()) {
+ s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
+ break;
+ }
+
+ rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]);
+ s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0]));
+
+ try {
+ rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]);
+ s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1]));
+ } catch (final NiciraNvpApiException ex) {
+ s_logger.warn("NiciraNvpApiException during create call, rolling back previous create");
+ niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid());
+ throw ex; // Rethrow the original exception
+ }
+
+ }
+ }
+ return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " PortForwarding rules applied");
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, ConfigurePortForwardingRulesOnLogicalRouterAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
new file mode 100644
index 0000000..e5d2dcd
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
@@ -0,0 +1,60 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
+import com.cloud.network.nicira.LogicalRouterPort;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class)
+public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrapper<ConfigurePublicIpsOnLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final ConfigurePublicIpsOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid());
+ if (ports.getResultCount() != 1) {
+ return new ConfigurePublicIpsOnLogicalRouterAnswer(command, false, "No logical router ports found, unable to set ip addresses");
+ }
+ final LogicalRouterPort lrp = ports.getResults().get(0);
+ lrp.setIpAddresses(command.getPublicCidrs());
+ niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp);
+
+ return new ConfigurePublicIpsOnLogicalRouterAnswer(command, true, "Configured " + command.getPublicCidrs().size() + " ip addresses on logical router uuid " +
+ command.getLogicalRouterUuid());
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, ConfigurePublicIpsOnLogicalRouterAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
new file mode 100644
index 0000000..1ce3ceb
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
@@ -0,0 +1,113 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.to.StaticNatRuleTO;
+import com.cloud.network.nicira.NatRule;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class)
+public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends CommandWrapper<ConfigureStaticNatRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigureStaticNatRulesCommandWrapper.class);
+
+ @Override
+ public Answer execute(final ConfigureStaticNatRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
+ // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
+ // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
+ // Any other SourceNat rule should have a corresponding DestinationNat rule
+
+ for (final StaticNatRuleTO rule : command.getRules()) {
+
+ final NatRule[] rulepair = niciraNvpResource.generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp());
+
+ NatRule incoming = null;
+ NatRule outgoing = null;
+
+ for (final NatRule storedRule : existingRules.getResults()) {
+ if (storedRule.equalsIgnoreUuid(rulepair[1])) {
+ // The outgoing rule exists
+ outgoing = storedRule;
+ s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
+ if (incoming != null) {
+ break;
+ }
+ } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
+ // The incoming rule exists
+ incoming = storedRule;
+ s_logger.debug("Found matching incoming rule " + incoming.getUuid());
+ if (outgoing != null) {
+ break;
+ }
+ }
+ }
+ if (incoming != null && outgoing != null) {
+ if (rule.revoked()) {
+ s_logger.debug("Deleting incoming rule " + incoming.getUuid());
+ niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid());
+
+ s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
+ niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid());
+ }
+ } else {
+ if (rule.revoked()) {
+ s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
+ break;
+ }
+
+ rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]);
+ s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0]));
+
+ try {
+ rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]);
+ s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1]));
+ } catch (final NiciraNvpApiException ex) {
+ s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule");
+ niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid());
+ throw ex; // Rethrow original exception
+ }
+
+ }
+ }
+ return new ConfigureStaticNatRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " StaticNat rules applied");
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, ConfigureStaticNatRulesOnLogicalRouterAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
new file mode 100644
index 0000000..1cddf4f
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
@@ -0,0 +1,152 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NAME_MAX_LEN;
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalRouterAnswer;
+import com.cloud.agent.api.CreateLogicalRouterCommand;
+import com.cloud.network.nicira.L3GatewayAttachment;
+import com.cloud.network.nicira.LogicalRouter;
+import com.cloud.network.nicira.LogicalRouterPort;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.Match;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.PatchAttachment;
+import com.cloud.network.nicira.RouterNextHop;
+import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
+import com.cloud.network.nicira.SourceNatRule;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = CreateLogicalRouterCommand.class)
+public final class NiciraNvpCreateLogicalRouterCommandWrapper extends CommandWrapper<CreateLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpCreateLogicalRouterCommandWrapper.class);
+
+ @Override
+ public Answer execute(final CreateLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+ final String routerName = command.getName();
+ final String gatewayServiceUuid = command.getGatewayServiceUuid();
+ final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+
+ final String publicNetworkNextHopIp = command.getPublicNextHop();
+ final String publicNetworkIpAddress = command.getPublicIpCidr();
+ final String internalNetworkAddress = command.getInternalIpCidr();
+
+ s_logger.debug("Creating a logical router with external ip " + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + "on gateway service " +
+ gatewayServiceUuid);
+
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ // Create the Router
+ LogicalRouter lrc = new LogicalRouter();
+ lrc.setDisplayName(niciraNvpResource.truncate(routerName, NAME_MAX_LEN));
+ lrc.setTags(tags);
+ lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp)));
+ lrc = niciraNvpApi.createLogicalRouter(lrc);
+
+ // store the switchport for rollback
+ LogicalSwitchPort lsp = null;
+
+ try {
+ // Create the outside port for the router
+ LogicalRouterPort lrpo = new LogicalRouterPort();
+ lrpo.setAdminStatusEnabled(true);
+ lrpo.setDisplayName(niciraNvpResource.truncate(routerName + "-outside-port", NAME_MAX_LEN));
+ lrpo.setTags(tags);
+ final List<String> outsideIpAddresses = new ArrayList<String>();
+ outsideIpAddresses.add(publicNetworkIpAddress);
+ lrpo.setIpAddresses(outsideIpAddresses);
+ lrpo = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpo);
+
+ // Attach the outside port to the gateway service on the correct VLAN
+ final L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid);
+ if (command.getVlanId() != 0) {
+ attachment.setVlanId(command.getVlanId());
+ }
+ niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment);
+
+ // Create the inside port for the router
+ LogicalRouterPort lrpi = new LogicalRouterPort();
+ lrpi.setAdminStatusEnabled(true);
+ lrpi.setDisplayName(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN));
+ lrpi.setTags(tags);
+ final List<String> insideIpAddresses = new ArrayList<String>();
+ insideIpAddresses.add(internalNetworkAddress);
+ lrpi.setIpAddresses(insideIpAddresses);
+ lrpi = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpi);
+
+ // Create the inside port on the lswitch
+ lsp = new LogicalSwitchPort(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN), tags, true);
+ lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp);
+
+ // Attach the inside router port to the lswitch port with a PatchAttachment
+ niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid()));
+
+ // Attach the inside lswitch port to the router with a PatchAttachment
+ niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid()));
+
+ // Setup the source nat rule
+ final SourceNatRule snr = new SourceNatRule();
+ snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]);
+ snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]);
+ final Match match = new Match();
+ match.setSourceIpAddresses(internalNetworkAddress);
+ snr.setMatch(match);
+ snr.setOrder(200);
+ niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr);
+ } catch (final NiciraNvpApiException e) {
+ // We need to destroy the router if we already created it
+ // this will also take care of any router ports and rules
+ try {
+ niciraNvpApi.deleteLogicalRouter(lrc.getUuid());
+ if (lsp != null) {
+ niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid());
+ }
+ } catch (final NiciraNvpApiException ex) {
+ }
+
+ throw e;
+ }
+
+ return new CreateLogicalRouterAnswer(command, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid());
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, CreateLogicalRouterAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
new file mode 100644
index 0000000..7d66ada
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
@@ -0,0 +1,73 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalSwitchAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.TransportZoneBinding;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.resource.NiciraNvpUtilities;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = CreateLogicalSwitchCommand.class)
+public final class NiciraNvpCreateLogicalSwitchCommandWrapper extends CommandWrapper<CreateLogicalSwitchCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final CreateLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
+
+ LogicalSwitch logicalSwitch = niciraNvpUtilities.createLogicalSwitch();
+ logicalSwitch.setDisplayName(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN));
+ logicalSwitch.setPortIsolationEnabled(false);
+
+ // Set transport binding
+ final List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
+ ltzb.add(new TransportZoneBinding(command.getTransportUuid(), command.getTransportType()));
+ logicalSwitch.setTransportZones(ltzb);
+
+ // Tags set to scope cs_account and account name
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+ logicalSwitch.setTags(tags);
+
+ try {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+ logicalSwitch = niciraNvpApi.createLogicalSwitch(logicalSwitch);
+ final String switchUuid = logicalSwitch.getUuid();
+ return new CreateLogicalSwitchAnswer(command, true, "Logicalswitch " + switchUuid + " created", switchUuid);
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, CreateLogicalSwitchAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..42a4067
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,70 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.VifAttachment;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.resource.NiciraNvpUtilities;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = CreateLogicalSwitchPortCommand.class)
+public final class NiciraNvpCreateLogicalSwitchPortCommandWrapper extends CommandWrapper<CreateLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpCreateLogicalSwitchPortCommandWrapper.class);
+
+ @Override
+ public Answer execute(final CreateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
+
+ final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+ final String attachmentUuid = command.getAttachmentUuid();
+
+ try {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ final LogicalSwitchPort logicalSwitchPort = niciraNvpUtilities.createLogicalSwitchPort(command);
+ final LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
+ try {
+ niciraNvpApi.updateLogicalSwitchPortAttachment(command.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
+ } catch (final NiciraNvpApiException ex) {
+ s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport");
+ niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), newPort.getUuid());
+ throw ex; // Rethrow the original exception
+ }
+ return new CreateLogicalSwitchPortAnswer(command, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, CreateLogicalSwitchPortAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
new file mode 100644
index 0000000..43665b2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
@@ -0,0 +1,50 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteLogicalRouterAnswer;
+import com.cloud.agent.api.DeleteLogicalRouterCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = DeleteLogicalRouterCommand.class)
+public final class NiciraNvpDeleteLogicalRouterCommandWrapper extends CommandWrapper<DeleteLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final DeleteLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ niciraNvpApi.deleteLogicalRouter(command.getLogicalRouterUuid());
+ return new DeleteLogicalRouterAnswer(command, true, "Logical Router deleted (uuid " + command.getLogicalRouterUuid() + ")");
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, DeleteLogicalRouterAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
new file mode 100644
index 0000000..f7b8ab9
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
@@ -0,0 +1,49 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = DeleteLogicalSwitchCommand.class)
+public final class NiciraNvpDeleteLogicalSwitchCommandWrapper extends CommandWrapper<DeleteLogicalSwitchCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final DeleteLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) {
+ try {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+ niciraNvpApi.deleteLogicalSwitch(command.getLogicalSwitchUuid());
+ return new DeleteLogicalSwitchAnswer(command, true, "Logicalswitch " + command.getLogicalSwitchUuid() + " deleted");
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, DeleteLogicalSwitchAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..b8c69f2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,50 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = DeleteLogicalSwitchPortCommand.class)
+public final class NiciraNvpDeleteLogicalSwitchPortCommandWrapper extends CommandWrapper<DeleteLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final DeleteLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid());
+ return new DeleteLogicalSwitchPortAnswer(command, true, "Logical switch port " + command.getLogicalSwitchPortUuid() + " deleted");
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, DeleteLogicalSwitchPortAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..40d58fc
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,59 @@
+//
+// 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
+import com.cloud.agent.api.FindLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class)
+public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandWrapper<FindLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final FindLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+ final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+ final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
+
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ final NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
+ if (ports.getResultCount() == 0) {
+ return new FindLogicalSwitchPortAnswer(command, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null);
+ } else {
+ return new FindLogicalSwitchPortAnswer(command, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
+ }
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, FindLogicalSwitchPortAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
new file mode 100644
index 0000000..3015378
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
@@ -0,0 +1,36 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.MaintainAnswer;
+import com.cloud.agent.api.MaintainCommand;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = MaintainCommand.class)
+public final class NiciraNvpMaintainCommandWrapper extends CommandWrapper<MaintainCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final MaintainCommand command, final NiciraNvpResource niciraNvpResource) {
+ return new MaintainAnswer(command);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
new file mode 100644
index 0000000..3d0d3f3
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
@@ -0,0 +1,36 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ReadyAnswer;
+import com.cloud.agent.api.ReadyCommand;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = ReadyCommand.class)
+public final class NiciraNvpReadyCommandWrapper extends CommandWrapper<ReadyCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final ReadyCommand command, final NiciraNvpResource niciraNvpResource) {
+ return new ReadyAnswer(command);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..a0d7dc2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,68 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.VifAttachment;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.resource.NiciraNvpUtilities;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles = UpdateLogicalSwitchPortCommand.class)
+public final class NiciraNvpUpdateLogicalSwitchPortCommandWrapper extends CommandWrapper<UpdateLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+ @Override
+ public Answer execute(final UpdateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+ final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
+
+ final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+ final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
+ final String attachmentUuid = command.getAttachmentUuid();
+
+ final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+ try {
+ // Tags set to scope cs_account and account name
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+
+ final VifAttachment vifAttachment = niciraNvpUtilities.createVifAttachment(attachmentUuid);
+
+ niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment);
+ return new UpdateLogicalSwitchPortAnswer(command, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
+ } catch (final NiciraNvpApiException e) {
+ final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+ retryUtility.addRetry(command, NUM_RETRIES);
+ return retryUtility.retry(command, UpdateLogicalSwitchPortAnswer.class, e);
+ }
+ }
+}
\ No newline at end of file
[16/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/ExceptionUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/ExceptionUtil.java b/utils/src/main/java/com/cloud/utils/exception/ExceptionUtil.java
new file mode 100644
index 0000000..351d2ab
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/ExceptionUtil.java
@@ -0,0 +1,54 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.exception;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+public class ExceptionUtil {
+ public static String toString(Throwable th) {
+ return toString(th, true);
+ }
+
+ public static String toString(Throwable th, boolean printStack) {
+ final StringWriter writer = new StringWriter();
+ writer.append("Exception: " + th.getClass().getName() + "\n");
+ writer.append("Message: ");
+ writer.append(th.getMessage()).append("\n");
+
+ if (printStack) {
+ writer.append("Stack: ");
+ th.printStackTrace(new PrintWriter(writer));
+ }
+ return writer.toString();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T extends Throwable> void rethrow(Throwable t, Class<T> clz) throws T {
+ if (clz.isAssignableFrom(t.getClass()))
+ throw (T)t;
+ }
+
+ public static <T extends Throwable> void rethrowRuntime(Throwable t) {
+ rethrow(t, RuntimeException.class);
+ rethrow(t, Error.class);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/ExecutionException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/ExecutionException.java b/utils/src/main/java/com/cloud/utils/exception/ExecutionException.java
new file mode 100644
index 0000000..7b3bc61
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/ExecutionException.java
@@ -0,0 +1,49 @@
+//
+// 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 com.cloud.utils.exception;
+
+import com.cloud.utils.SerialVersionUID;
+
+/**
+ * a public method.
+ *
+ */
+public class ExecutionException extends Exception {
+ private static final long serialVersionUID = SerialVersionUID.ExecutionException;
+
+ protected int csErrorCode;
+
+ public ExecutionException(String msg, Throwable cause) {
+ super(msg, cause);
+ setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
+ }
+
+ public ExecutionException(String msg) {
+ super(msg);
+ }
+
+ public void setCSErrorCode(int cserrcode) {
+ this.csErrorCode = cserrcode;
+ }
+
+ public int getCSErrorCode() {
+ return this.csErrorCode;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/HypervisorVersionChangedException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/HypervisorVersionChangedException.java b/utils/src/main/java/com/cloud/utils/exception/HypervisorVersionChangedException.java
new file mode 100644
index 0000000..55c273b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/HypervisorVersionChangedException.java
@@ -0,0 +1,35 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.exception;
+
+import com.cloud.utils.SerialVersionUID;
+
+public class HypervisorVersionChangedException extends CloudRuntimeException {
+
+ private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException;
+
+ public HypervisorVersionChangedException(String message) {
+ super(message);
+ }
+
+ protected HypervisorVersionChangedException() {
+ super();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/ChangeEvent.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/ChangeEvent.java b/utils/src/main/java/com/cloud/utils/fsm/ChangeEvent.java
new file mode 100644
index 0000000..15f4f6e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/ChangeEvent.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.utils.fsm;
+
+public class ChangeEvent {
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/FiniteState.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/FiniteState.java b/utils/src/main/java/com/cloud/utils/fsm/FiniteState.java
new file mode 100644
index 0000000..e6f2cd0
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/FiniteState.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.fsm;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ *
+ * @param <S> State
+ * @param <E> Event
+ */
+public interface FiniteState<S, E> {
+ /**
+ * @return the state machine being used.
+ */
+ StateMachine<S, E> getStateMachine();
+
+ /**
+ * get next state based on the event.
+ * @param event
+ * @return next State
+ */
+ S getNextState(E event);
+
+ /**
+ * Get the states that could have traveled to the current state
+ * via this event.
+ * @param event
+ * @return array of states
+ */
+ List<S> getFromStates(E event);
+
+ /**
+ * Get the possible events that can happen from the current state.
+ * @return array of events.
+ */
+ Set<E> getPossibleEvents();
+
+ String getDescription();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/FiniteState2.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/FiniteState2.java b/utils/src/main/java/com/cloud/utils/fsm/FiniteState2.java
new file mode 100644
index 0000000..14b9a5e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/FiniteState2.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.fsm;
+
+import java.util.Set;
+
+public interface FiniteState2<T, E> {
+
+ StateMachine2<T, ? extends ChangeEvent, ? extends StateObject<?>> getStateMachine();
+
+ T getNextState(ChangeEvent e) throws NoTransitionException;
+
+ T getFromStates(ChangeEvent e);
+
+ Set<ChangeEvent> getPossibleEvents();
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/FiniteStateObject.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/FiniteStateObject.java b/utils/src/main/java/com/cloud/utils/fsm/FiniteStateObject.java
new file mode 100644
index 0000000..a57e3b4
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/FiniteStateObject.java
@@ -0,0 +1,25 @@
+//
+// 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 com.cloud.utils.fsm;
+
+public interface FiniteStateObject<S, E> {
+
+ void setState(S state);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/NoTransitionException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/NoTransitionException.java b/utils/src/main/java/com/cloud/utils/fsm/NoTransitionException.java
new file mode 100644
index 0000000..241e456
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/NoTransitionException.java
@@ -0,0 +1,36 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.fsm;
+
+import com.cloud.utils.SerialVersionUID;
+
+/**
+ * Thrown by the state machine when there is no transition from one state
+ * to another.
+ *
+ */
+public class NoTransitionException extends Exception {
+
+ private static final long serialVersionUID = SerialVersionUID.NoTransitionException;
+
+ public NoTransitionException(String msg) {
+ super(msg);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/State.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/State.java b/utils/src/main/java/com/cloud/utils/fsm/State.java
new file mode 100644
index 0000000..0af0e61
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/State.java
@@ -0,0 +1,27 @@
+//
+// 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 com.cloud.utils.fsm;
+
+/**
+ * State represents one state for that object
+ */
+public interface State<T> {
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/StateDao.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/StateDao.java b/utils/src/main/java/com/cloud/utils/fsm/StateDao.java
new file mode 100644
index 0000000..43ce25c
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/StateDao.java
@@ -0,0 +1,25 @@
+//
+// 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 com.cloud.utils.fsm;
+
+public interface StateDao<S, E, V> {
+ boolean updateState(S currentState, E event, S nextState, V vo, Object data);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/StateListener.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/StateListener.java b/utils/src/main/java/com/cloud/utils/fsm/StateListener.java
new file mode 100644
index 0000000..96e8be9
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/StateListener.java
@@ -0,0 +1,43 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.fsm;
+
+public interface StateListener<S, E, V> {
+ /**
+ * Event is triggered before state machine transition finished.
+ * If you want to get the state of vm before state machine changed, you need to listen on this event
+ * @param oldState VM's old state
+ * @param event that triggered this VM state change
+ * @param newState VM's new state
+ * @param vo the VM instance
+ * @param opaque host id
+ * @return
+ */
+ public boolean preStateTransitionEvent(S oldState, E event, S newState, V vo, boolean status, Object opaque);
+
+ /**
+ * Event is triggered after state machine transition finished
+ * @param transition The Transition fo the Event
+ * @param vo the VM instance
+ * @param status the state transition is allowed or not
+ * @return
+ */
+ public boolean postStateTransitionEvent(StateMachine2.Transition<S, E> transition, V vo, boolean status, Object opaque);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/StateMachine.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/StateMachine.java b/utils/src/main/java/com/cloud/utils/fsm/StateMachine.java
new file mode 100644
index 0000000..d6d5b4d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/StateMachine.java
@@ -0,0 +1,147 @@
+//
+// 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 com.cloud.utils.fsm;
+
+import java.util.ArrayList;
+import java.util.Formatter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Specifically, it implements the Moore machine.
+ * so someone else can add/modify states easily without regression.
+ * business logic anyways.
+ *
+ * @param <S> state
+ * @param <E> event
+ */
+public class StateMachine<S, E> {
+ private final HashMap<S, StateEntry> _states = new HashMap<S, StateEntry>();
+ private final StateEntry _initialStateEntry;
+
+ public StateMachine() {
+ _initialStateEntry = new StateEntry(null);
+ }
+
+ public void addTransition(S currentState, E event, S toState) {
+ StateEntry entry = null;
+ if (currentState == null) {
+ entry = _initialStateEntry;
+ } else {
+ entry = _states.get(currentState);
+ if (entry == null) {
+ entry = new StateEntry(currentState);
+ _states.put(currentState, entry);
+ }
+ }
+
+ entry.addTransition(event, toState);
+
+ entry = _states.get(toState);
+ if (entry == null) {
+ entry = new StateEntry(toState);
+ _states.put(toState, entry);
+ }
+ entry.addFromTransition(event, currentState);
+ }
+
+ public Set<E> getPossibleEvents(S s) {
+ StateEntry entry = _states.get(s);
+ return entry.nextStates.keySet();
+ }
+
+ public S getNextState(S s, E e) {
+ StateEntry entry = null;
+ if (s == null) {
+ entry = _initialStateEntry;
+ } else {
+ entry = _states.get(s);
+ assert entry != null : "Cannot retrieve transitions for state " + s.toString();
+ }
+
+ return entry.nextStates.get(e);
+ }
+
+ public List<S> getFromStates(S s, E e) {
+ StateEntry entry = _states.get(s);
+ if (entry == null) {
+ return new ArrayList<S>();
+ }
+
+ return entry.prevStates.get(e);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder str = new StringBuilder(1024);
+ _initialStateEntry.buildString(str);
+ for (StateEntry entry : _states.values()) {
+ entry.buildString(str);
+ }
+ return str.toString();
+ }
+
+ private class StateEntry {
+ public S state;
+ public HashMap<E, S> nextStates;
+ public HashMap<E, List<S>> prevStates;
+
+ public StateEntry(S state) {
+ this.state = state;
+ nextStates = new HashMap<E, S>();
+ prevStates = new HashMap<E, List<S>>();
+ }
+
+ public void addTransition(E e, S s) {
+ assert !nextStates.containsKey(e) : "State " + getStateStr() + " already contains a transition to state " + nextStates.get(e).toString() + " via event " +
+ e.toString() + ". Please revisit the rule you're adding to state " + s.toString();
+ nextStates.put(e, s);
+ }
+
+ public void addFromTransition(E e, S s) {
+ List<S> l = prevStates.get(e);
+ if (l == null) {
+ l = new ArrayList<S>();
+ prevStates.put(e, l);
+ }
+
+ assert !l.contains(s) : "Already contains the from transition " + e.toString() + " from state " + s.toString() + " to " + getStateStr();
+ l.add(s);
+ }
+
+ protected String getStateStr() {
+ return state == null ? "Initial" : state.toString();
+ }
+
+ public void buildString(StringBuilder str) {
+ str.append("State: ").append(getStateStr()).append("\n");
+ for (Map.Entry<E, S> nextState : nextStates.entrySet()) {
+ str.append(" --> Event: ");
+ Formatter format = new Formatter();
+ str.append(format.format("%-30s", nextState.getKey().toString()));
+ str.append("----> State: ");
+ str.append(nextState.getValue().toString());
+ str.append("\n");
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/StateMachine2.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/StateMachine2.java b/utils/src/main/java/com/cloud/utils/fsm/StateMachine2.java
new file mode 100644
index 0000000..431d961
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/StateMachine2.java
@@ -0,0 +1,261 @@
+//
+// 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 com.cloud.utils.fsm;
+
+import java.util.ArrayList;
+import java.util.Formatter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Specifically, it implements the Moore machine.
+ * so someone else can add/modify states easily without regression.
+ * business logic anyways.
+ *
+ * @param <S> state
+ * @param <E> event
+ */
+public class StateMachine2<S, E, V extends StateObject<S>> {
+ private final HashMap<S, StateEntry> _states = new HashMap<S, StateEntry>();
+ private final StateEntry _initialStateEntry;
+
+ private List<StateListener<S, E, V>> _listeners = new ArrayList<StateListener<S, E, V>>();
+
+ public StateMachine2() {
+ _initialStateEntry = new StateEntry(null);
+
+ }
+
+ public void addTransition(S currentState, E event, S toState) {
+ addTransition(new Transition<S, E>(currentState, event, toState, null));
+ }
+
+
+ public void addTransition(Transition<S, E> transition) {
+ S currentState = transition.getCurrentState();
+ E event = transition.getEvent();
+ S toState = transition.getToState();
+ StateEntry entry = null;
+ if (currentState == null) {
+ entry = _initialStateEntry;
+ } else {
+ entry = _states.get(currentState);
+ if (entry == null) {
+ entry = new StateEntry(currentState);
+ _states.put(currentState, entry);
+ }
+ }
+
+ entry.addTransition(event, toState, transition);
+
+ entry = _states.get(toState);
+ if (entry == null) {
+ entry = new StateEntry(toState);
+ _states.put(toState, entry);
+ }
+ entry.addFromTransition(event, currentState);
+ }
+
+ public Set<E> getPossibleEvents(S s) {
+ StateEntry entry = _states.get(s);
+ return entry.nextStates.keySet();
+ }
+
+ public S getNextState(S s, E e) throws NoTransitionException {
+ return getTransition(s, e).getToState();
+ }
+
+ public Transition<S, E> getTransition(S s, E e) throws NoTransitionException {
+ StateEntry entry = null;
+ if (s == null) {
+ entry = _initialStateEntry;
+ } else {
+ entry = _states.get(s);
+ assert entry != null : "Cannot retrieve transitions for state " + s;
+ }
+
+ Transition<S, E> transition = entry.nextStates.get(e);
+ if (transition == null) {
+ throw new NoTransitionException("Unable to transition to a new state from " + s + " via " + e);
+ }
+ return transition;
+ }
+
+ public List<S> getFromStates(S s, E e) {
+ StateEntry entry = _states.get(s);
+ if (entry == null) {
+ return new ArrayList<S>();
+ }
+
+ return entry.prevStates.get(e);
+ }
+
+ public boolean transitTo(V vo, E e, Object opaque, StateDao<S, E, V> dao) throws NoTransitionException {
+ S currentState = vo.getState();
+ S nextState = getNextState(currentState, e);
+ Transition<S, E> transition = getTransition(currentState, e);
+
+ boolean transitionStatus = true;
+ if (nextState == null) {
+ transitionStatus = false;
+ }
+
+ for (StateListener<S, E, V> listener : _listeners) {
+ listener.preStateTransitionEvent(currentState, e, nextState, vo, transitionStatus, opaque);
+ }
+
+ transitionStatus = dao.updateState(currentState, e, nextState, vo, opaque);
+ if (!transitionStatus) {
+ return false;
+ }
+
+ for (StateListener<S, E, V> listener : _listeners) {
+ listener.postStateTransitionEvent(transition, vo, transitionStatus, opaque);
+ }
+
+ return true;
+ }
+
+ public boolean registerListener(StateListener<S, E, V> listener) {
+ synchronized (_listeners) {
+ return _listeners.add(listener);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder str = new StringBuilder(1024);
+ _initialStateEntry.buildString(str);
+ for (StateEntry entry : _states.values()) {
+ entry.buildString(str);
+ }
+ return str.toString();
+ }
+
+ public static class Transition<S, E> {
+
+ private S currentState;
+
+ private E event;
+
+ private S toState;
+
+ private List<Impact> impacts;
+
+ public static enum Impact {
+ USAGE
+ }
+
+ public Transition(S currentState, E event, S toState, List<Impact> impacts) {
+ this.currentState = currentState;
+ this.event = event;
+ this.toState = toState;
+ this.impacts = impacts;
+ }
+
+ public S getCurrentState() {
+ return currentState;
+ }
+
+ public E getEvent() {
+ return event;
+ }
+
+ public S getToState() {
+ return toState;
+ }
+
+ public boolean isImpacted(Impact impact) {
+ if (impacts == null || impacts.isEmpty()) {
+ return false;
+ }
+ return impacts.contains(impact);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Transition that = (Transition) o;
+
+ if (currentState != null ? !currentState.equals(that.currentState) : that.currentState != null) return false;
+ if (event != null ? !event.equals(that.event) : that.event != null) return false;
+ if (toState != null ? !toState.equals(that.toState) : that.toState != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = currentState != null ? currentState.hashCode() : 0;
+ result = 31 * result + (event != null ? event.hashCode() : 0);
+ result = 31 * result + (toState != null ? toState.hashCode() : 0);
+ return result;
+ }
+ }
+
+ private class StateEntry {
+ public S state;
+ public HashMap<E, Transition<S, E>> nextStates;
+ public HashMap<E, List<S>> prevStates;
+
+ public StateEntry(S state) {
+ this.state = state;
+ prevStates = new HashMap<E, List<S>>();
+ nextStates = new HashMap<E, Transition<S, E>>();
+ }
+
+ public void addTransition(E e, S s, Transition<S, E> transition) {
+ assert !nextStates.containsKey(e) : "State " + getStateStr() + " already contains a transition to state " + nextStates.get(e).toString() + " via event " +
+ e.toString() + ". Please revisit the rule you're adding to state " + s.toString();
+ nextStates.put(e, transition);
+ }
+
+ public void addFromTransition(E e, S s) {
+ List<S> l = prevStates.get(e);
+ if (l == null) {
+ l = new ArrayList<S>();
+ prevStates.put(e, l);
+ }
+
+ assert !l.contains(s) : "Already contains the from transition " + e.toString() + " from state " + s.toString() + " to " + getStateStr();
+ l.add(s);
+ }
+
+ protected String getStateStr() {
+ return state == null ? "Initial" : state.toString();
+ }
+
+ public void buildString(StringBuilder str) {
+ str.append("State: ").append(getStateStr()).append("\n");
+ for (Map.Entry<E, Transition<S, E>> nextState : nextStates.entrySet()) {
+ str.append(" --> Event: ");
+ Formatter format = new Formatter();
+ str.append(format.format("%-30s", nextState.getKey().toString()));
+ str.append("----> State: ");
+ str.append(nextState.getValue().toString());
+ str.append("\n");
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/fsm/StateObject.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/fsm/StateObject.java b/utils/src/main/java/com/cloud/utils/fsm/StateObject.java
new file mode 100644
index 0000000..85dd441
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/fsm/StateObject.java
@@ -0,0 +1,27 @@
+//
+// 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 com.cloud.utils.fsm;
+
+public interface StateObject<S> {
+ /**
+ * @return finite state.
+ */
+ S getState();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/mgmt/JmxUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/mgmt/JmxUtil.java b/utils/src/main/java/com/cloud/utils/mgmt/JmxUtil.java
new file mode 100644
index 0000000..49076f7
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/mgmt/JmxUtil.java
@@ -0,0 +1,90 @@
+//
+// 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 com.cloud.utils.mgmt;
+
+import java.lang.management.ManagementFactory;
+import java.util.ArrayList;
+
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+public class JmxUtil {
+ public static ObjectName registerMBean(ManagementBean mbean) throws MalformedObjectNameException, InstanceAlreadyExistsException, MBeanRegistrationException,
+ NotCompliantMBeanException {
+
+ return registerMBean(mbean.getName(), null, mbean);
+ }
+
+ public static ObjectName registerMBean(String objTypeName, String objInstanceName, Object mbean) throws MalformedObjectNameException, InstanceAlreadyExistsException,
+ MBeanRegistrationException, NotCompliantMBeanException {
+
+ String name = "com.cloud:type=" + objTypeName;
+ if (objInstanceName != null && !objInstanceName.isEmpty())
+ name += ", name=" + objInstanceName;
+ ObjectName objectName = new ObjectName(name);
+
+ ArrayList<MBeanServer> server = MBeanServerFactory.findMBeanServer(null);
+ if (server.size() > 0) {
+ MBeanServer mBeanServer = server.get(0);
+ if (!mBeanServer.isRegistered(objectName))
+ mBeanServer.registerMBean(mbean, objectName);
+ return objectName;
+ } else {
+ MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
+ if (!mBeanServer.isRegistered(objectName))
+ mBeanServer.registerMBean(mbean, objectName);
+ return objectName;
+ }
+ }
+
+ public static void unregisterMBean(String objTypeName, String objInstanceName) throws MalformedObjectNameException, MBeanRegistrationException,
+ InstanceNotFoundException {
+
+ ObjectName name = composeMBeanName(objTypeName, objInstanceName);
+ unregisterMBean(name);
+ }
+
+ public static void unregisterMBean(ObjectName name) throws MalformedObjectNameException, MBeanRegistrationException, InstanceNotFoundException {
+
+ ArrayList<MBeanServer> server = MBeanServerFactory.findMBeanServer(null);
+ if (server.size() > 0) {
+ MBeanServer mBeanServer = server.get(0);
+ mBeanServer.unregisterMBean(name);
+ } else {
+ MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
+ mBeanServer.unregisterMBean(name);
+ }
+ }
+
+ private static ObjectName composeMBeanName(String objTypeName, String objInstanceName) throws MalformedObjectNameException {
+
+ String name = "com.cloud:type=" + objTypeName;
+ if (objInstanceName != null && !objInstanceName.isEmpty())
+ name += ", name=" + objInstanceName;
+
+ return new ObjectName(name);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/mgmt/ManagementBean.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/mgmt/ManagementBean.java b/utils/src/main/java/com/cloud/utils/mgmt/ManagementBean.java
new file mode 100644
index 0000000..387052e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/mgmt/ManagementBean.java
@@ -0,0 +1,27 @@
+//
+// 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 com.cloud.utils.mgmt;
+
+/**
+ * we ever need common use methods here.
+ */
+public interface ManagementBean {
+ String getName();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/mgmt/PropertyMapDynamicBean.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/mgmt/PropertyMapDynamicBean.java b/utils/src/main/java/com/cloud/utils/mgmt/PropertyMapDynamicBean.java
new file mode 100644
index 0000000..d1689eb
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/mgmt/PropertyMapDynamicBean.java
@@ -0,0 +1,120 @@
+//
+// 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 com.cloud.utils.mgmt;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import javax.management.Attribute;
+import javax.management.AttributeList;
+import javax.management.AttributeNotFoundException;
+import javax.management.DynamicMBean;
+import javax.management.InvalidAttributeValueException;
+import javax.management.MBeanAttributeInfo;
+import javax.management.MBeanException;
+import javax.management.MBeanInfo;
+import javax.management.ReflectionException;
+
+public class PropertyMapDynamicBean implements DynamicMBean {
+
+ private Map<String, Object> _propMap = new HashMap<String, Object>();
+
+ public PropertyMapDynamicBean() {
+ }
+
+ public PropertyMapDynamicBean(Map<String, Object> propMap) {
+ _propMap = propMap;
+ }
+
+ @Override
+ public synchronized Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException {
+ if (_propMap != null) {
+ return _propMap.get(name);
+ }
+
+ throw new AttributeNotFoundException("No such property " + name);
+ }
+
+ @Override
+ public synchronized AttributeList getAttributes(String[] names) {
+ AttributeList list = new AttributeList();
+ for (String name : names) {
+ Object value = _propMap.get(name);
+ if (value != null)
+ list.add(new Attribute(name, value));
+ }
+ return list;
+ }
+
+ @Override
+ public synchronized MBeanInfo getMBeanInfo() {
+ SortedSet<String> names = new TreeSet<String>();
+
+ for (String name : _propMap.keySet())
+ names.add(name);
+
+ MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[names.size()];
+ Iterator<String> it = names.iterator();
+ for (int i = 0; i < attrs.length; i++) {
+ String name = it.next();
+ attrs[i] = new MBeanAttributeInfo(name, "java.lang.String", name, true, // isReadable
+ true, // isWritable
+ false); // isIs
+ }
+
+ return new MBeanInfo(this.getClass().getName(), "Dynamic MBean", attrs, null, null, null);
+ }
+
+ @Override
+ public synchronized Object invoke(String name, Object[] args, String[] sig) throws MBeanException, ReflectionException {
+ throw new ReflectionException(new NoSuchMethodException(name));
+ }
+
+ @Override
+ public synchronized void setAttribute(Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
+ String name = attr.getName();
+ if (name != null)
+ _propMap.put(name, attr.getValue());
+ }
+
+ @Override
+ public synchronized AttributeList setAttributes(AttributeList list) {
+ Attribute[] attrs = list.toArray(new Attribute[0]);
+ AttributeList retList = new AttributeList();
+ for (Attribute attr : attrs) {
+ String name = attr.getName();
+ Object value = attr.getValue();
+ _propMap.put(name, value);
+ retList.add(new Attribute(name, value));
+ }
+ return retList;
+ }
+
+ public synchronized void addProp(String name, Object value) {
+ _propMap.put(name, value);
+ }
+
+ public synchronized Object getProp(String name) {
+ return _propMap.get(name);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/net/Ip.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/net/Ip.java b/utils/src/main/java/com/cloud/utils/net/Ip.java
new file mode 100644
index 0000000..09312bc
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/net/Ip.java
@@ -0,0 +1,98 @@
+//
+// 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 com.cloud.utils.net;
+
+import java.io.Serializable;
+
+import com.cloud.utils.NumbersUtil;
+import com.cloud.utils.SerialVersionUID;
+
+/**
+ * Simple Ip implementation class that works with both ip4 and ip6.
+ *
+ */
+public class Ip implements Serializable, Comparable<Ip> {
+
+ private static final long serialVersionUID = SerialVersionUID.Ip;
+
+ long ip;
+
+ public Ip(long ip) {
+ this.ip = ip;
+ }
+
+ public Ip(String ip) {
+ this.ip = NetUtils.ip2Long(ip);
+ }
+
+ protected Ip() {
+ }
+
+ public String addr() {
+ return toString();
+ }
+
+ public long longValue() {
+ return ip;
+ }
+
+ @Override
+ public String toString() {
+ return NetUtils.long2Ip(ip);
+ }
+
+ public boolean isIp4() {
+ return ip <= 2L * Integer.MAX_VALUE + 1;
+ }
+
+ public boolean isIp6() {
+ return ip > Integer.MAX_VALUE;
+ }
+
+ @Override
+ public int hashCode() {
+ return NumbersUtil.hash(ip);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof Ip) {
+ return ip == ((Ip)obj).ip;
+ }
+ return false;
+ }
+
+ public boolean isSameAddressAs(Object obj) {
+ if (this.equals(obj)) {
+ return true;
+ } else if (obj instanceof String) {
+ return ip == NetUtils.ip2Long((String)obj);
+ } else if (obj instanceof Long) {
+ return ip == (Long)obj;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public int compareTo(Ip that) {
+ return (int)(this.ip - that.ip);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/net/Ip4Address.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/net/Ip4Address.java b/utils/src/main/java/com/cloud/utils/net/Ip4Address.java
new file mode 100644
index 0000000..0bd814d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/net/Ip4Address.java
@@ -0,0 +1,80 @@
+//
+// 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 com.cloud.utils.net;
+
+public class Ip4Address {
+ String _addr;
+ String _mac;
+ static final String s_empty_mac = "00:00:00:00:00:00";
+
+ public Ip4Address(String addr, String mac) {
+ _addr = addr;
+ _mac = mac;
+ }
+
+ public Ip4Address(long addr, long mac) {
+ _addr = NetUtils.long2Ip(addr);
+ _mac = NetUtils.long2Mac(mac);
+ }
+
+ public Ip4Address(String addr) {
+ this(addr, s_empty_mac);
+ }
+
+ public Ip4Address(long addr) {
+ this(NetUtils.long2Ip(addr), s_empty_mac);
+ }
+
+ public String ip4() {
+ return _addr;
+ }
+
+ public String mac() {
+ return _mac;
+ }
+
+ public long toLong() {
+ return NetUtils.ip2Long(_addr);
+ }
+
+ @Override
+ public boolean equals(Object that) {
+
+ if (that instanceof Ip4Address) {
+ Ip4Address ip4 = (Ip4Address)that;
+ return _addr.equals(ip4._addr) && (_mac == ip4._mac || _mac.equals(ip4._mac));
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isSameAddressAs(Object other) {
+ if (other instanceof String) { // Assume that is an ip4 address in String form
+ return _addr.equals(other);
+ } else {
+ return equals(other);
+ }
+ }
+
+ @Override
+ public int hashCode(){
+ return _mac.hashCode()*_addr.hashCode();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/net/MacAddress.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/net/MacAddress.java b/utils/src/main/java/com/cloud/utils/net/MacAddress.java
new file mode 100644
index 0000000..b9118cf
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/net/MacAddress.java
@@ -0,0 +1,367 @@
+//
+// 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 com.cloud.utils.net;
+
+import static com.cloud.utils.AutoCloseableUtil.closeAutoCloseable;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Formatter;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.NumbersUtil;
+
+/**
+ * copied from the public domain utility from John Burkard.
+ * @author <a href="mailto:jb@eaio.com">Johann Burkard</a>
+ * @version 2.1.3
+ **/
+public class MacAddress {
+ private static final Logger s_logger = Logger.getLogger(MacAddress.class);
+ private long _addr = 0;
+
+ protected MacAddress() {
+ }
+
+ public MacAddress(long addr) {
+ _addr = addr;
+ }
+
+ public long toLong() {
+ return _addr;
+ }
+
+ public byte[] toByteArray() {
+ byte[] bytes = new byte[6];
+ bytes[0] = (byte)((_addr >> 40) & 0xff);
+ bytes[1] = (byte)((_addr >> 32) & 0xff);
+ bytes[2] = (byte)((_addr >> 24) & 0xff);
+ bytes[3] = (byte)((_addr >> 16) & 0xff);
+ bytes[4] = (byte)((_addr >> 8) & 0xff);
+ bytes[5] = (byte)((_addr >> 0) & 0xff);
+ return bytes;
+ }
+
+ public String toString(String separator) {
+ StringBuilder buff = new StringBuilder();
+ Formatter formatter = new Formatter(buff);
+ formatter.format("%02x%s%02x%s%02x%s%02x%s%02x%s%02x", _addr >> 40 & 0xff, separator, _addr >> 32 & 0xff, separator, _addr >> 24 & 0xff, separator,
+ _addr >> 16 & 0xff, separator, _addr >> 8 & 0xff, separator, _addr & 0xff);
+ return buff.toString();
+
+ /*
+
+ String str = Long.toHexString(_addr);
+
+ for (int i = str.length() - 1; i >= 0; i--) {
+ buff.append(str.charAt(i));
+ if (separator != null && (str.length() - i) % 2 == 0) {
+ buff.append(separator);
+ }
+ }
+ return buff.reverse().toString();
+ */
+ }
+
+ @Override
+ public String toString() {
+ return toString(":");
+ }
+
+ private static MacAddress s_address;
+ static {
+ String macAddress = null;
+
+ Process p = null;
+ BufferedReader in = null;
+
+ try {
+ String osname = System.getProperty("os.name");
+
+ if (osname.startsWith("Windows")) {
+ p = Runtime.getRuntime().exec(new String[] {"ipconfig", "/all"}, null);
+ } else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) {
+ // Solaris code must appear before the generic code
+ String hostName = MacAddress.getFirstLineOfCommand(new String[] {"uname", "-n"});
+ if (hostName != null) {
+ p = Runtime.getRuntime().exec(new String[] {"/usr/sbin/arp", hostName}, null);
+ }
+ } else if (new File("/usr/sbin/lanscan").exists()) {
+ p = Runtime.getRuntime().exec(new String[] {"/usr/sbin/lanscan"}, null);
+ } else if (new File("/sbin/ifconfig").exists()) {
+ p = Runtime.getRuntime().exec(new String[] {"/sbin/ifconfig", "-a"}, null);
+ }
+
+ if (p != null) {
+ in = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
+ String l = null;
+ while ((l = in.readLine()) != null) {
+ macAddress = MacAddress.parse(l);
+ if (macAddress != null) {
+ short parsedShortMacAddress = MacAddress.parseShort(macAddress);
+ if (parsedShortMacAddress != 0xff && parsedShortMacAddress != 0x00)
+ break;
+ }
+ macAddress = null;
+ }
+ }
+
+ } catch (SecurityException ex) {
+ s_logger.info("[ignored] security exception in static initializer of MacAddress", ex);
+ } catch (IOException ex) {
+ s_logger.info("[ignored] io exception in static initializer of MacAddress");
+ } finally {
+ if (p != null) {
+ closeAutoCloseable(in, "closing init process input stream");
+ closeAutoCloseable(p.getErrorStream(), "closing init process error output stream");
+ closeAutoCloseable(p.getOutputStream(), "closing init process std output stream");
+ p.destroy();
+ }
+ }
+
+ long clockSeqAndNode = 0;
+
+ if (macAddress != null) {
+ if (macAddress.indexOf(':') != -1) {
+ clockSeqAndNode |= MacAddress.parseLong(macAddress);
+ } else if (macAddress.startsWith("0x")) {
+ clockSeqAndNode |= MacAddress.parseLong(macAddress.substring(2));
+ }
+ } else {
+ try {
+ byte[] local = InetAddress.getLocalHost().getAddress();
+ clockSeqAndNode |= (local[0] << 24) & 0xFF000000L;
+ clockSeqAndNode |= (local[1] << 16) & 0xFF0000;
+ clockSeqAndNode |= (local[2] << 8) & 0xFF00;
+ clockSeqAndNode |= local[3] & 0xFF;
+ } catch (UnknownHostException ex) {
+ clockSeqAndNode |= (long)(Math.random() * 0x7FFFFFFF);
+ }
+ }
+
+ s_address = new MacAddress(clockSeqAndNode);
+ }
+
+ public static MacAddress getMacAddress() {
+ return s_address;
+ }
+
+ private static String getFirstLineOfCommand(String[] commands) throws IOException {
+
+ Process p = null;
+ BufferedReader reader = null;
+
+ try {
+ p = Runtime.getRuntime().exec(commands);
+ reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
+
+ return reader.readLine();
+ } finally {
+ if (p != null) {
+ closeAutoCloseable(reader, "closing process input stream");
+ closeAutoCloseable(p.getErrorStream(), "closing process error output stream");
+ closeAutoCloseable(p.getOutputStream(), "closing process std output stream");
+ p.destroy();
+ }
+ }
+
+ }
+
+ /**
+ * The MAC address parser attempts to find the following patterns:
+ * <ul>
+ * <li>.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}</li>
+ * <li>.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}</li>
+ * </ul>
+ *
+ * This is copied from the author below. The author encouraged copying
+ * it.
+ *
+ */
+ static String parse(String in) {
+
+ // lanscan
+
+ int hexStart = in.indexOf("0x");
+ if (hexStart != -1) {
+ int hexEnd = in.indexOf(' ', hexStart);
+ if (hexEnd != -1) {
+ return in.substring(hexStart, hexEnd);
+ }
+ }
+
+ int octets = 0;
+ int lastIndex, old, end;
+
+ if (in.indexOf('-') > -1) {
+ in = in.replace('-', ':');
+ }
+
+ lastIndex = in.lastIndexOf(':');
+
+ if (lastIndex > in.length() - 2)
+ return null;
+
+ end = Math.min(in.length(), lastIndex + 3);
+
+ ++octets;
+ old = lastIndex;
+ while (octets != 5 && lastIndex != -1 && lastIndex > 1) {
+ lastIndex = in.lastIndexOf(':', --lastIndex);
+ if (old - lastIndex == 3 || old - lastIndex == 2) {
+ ++octets;
+ old = lastIndex;
+ }
+ }
+
+ if (octets == 5 && lastIndex > 1) {
+ return in.substring(lastIndex - 2, end).trim();
+ }
+ return null;
+ }
+
+ public static void main(String[] args) {
+ MacAddress addr = MacAddress.getMacAddress();
+ System.out.println("addr in integer is " + addr.toLong());
+ System.out.println("addr in bytes is " + NumbersUtil.bytesToString(addr.toByteArray(), 0, addr.toByteArray().length));
+ System.out.println("addr in char is " + addr.toString(":"));
+ }
+
+ /**
+ * Parses a <code>long</code> from a hex encoded number. This method will skip
+ * all characters that are not 0-9 and a-f (the String is lower cased first).
+ * Returns 0 if the String does not contain any interesting characters.
+ *
+ * @param s the String to extract a <code>long</code> from, may not be <code>null</code>
+ * @return a <code>long</code>
+ * @throws NullPointerException if the String is <code>null</code>
+ */
+ public static long parseLong(String s) throws NullPointerException {
+ s = s.toLowerCase();
+ long out = 0;
+ byte shifts = 0;
+ char c;
+ for (int i = 0; i < s.length() && shifts < 16; i++) {
+ c = s.charAt(i);
+ if ((c > 47) && (c < 58)) {
+ out <<= 4;
+ ++shifts;
+ out |= c - 48;
+ } else if ((c > 96) && (c < 103)) {
+ ++shifts;
+ out <<= 4;
+ out |= c - 87;
+ }
+ }
+ return out;
+ }
+
+ /**
+ * Parses an <code>int</code> from a hex encoded number. This method will skip
+ * all characters that are not 0-9 and a-f (the String is lower cased first).
+ * Returns 0 if the String does not contain any interesting characters.
+ *
+ * @param s the String to extract an <code>int</code> from, may not be <code>null</code>
+ * @return an <code>int</code>
+ * @throws NullPointerException if the String is <code>null</code>
+ */
+ public static int parseInt(String s) throws NullPointerException {
+ s = s.toLowerCase();
+ int out = 0;
+ byte shifts = 0;
+ char c;
+ for (int i = 0; i < s.length() && shifts < 8; i++) {
+ c = s.charAt(i);
+ if ((c > 47) && (c < 58)) {
+ out <<= 4;
+ ++shifts;
+ out |= c - 48;
+ } else if ((c > 96) && (c < 103)) {
+ ++shifts;
+ out <<= 4;
+ out |= c - 87;
+ }
+ }
+ return out;
+ }
+
+ /**
+ * Parses a <code>short</code> from a hex encoded number. This method will skip
+ * all characters that are not 0-9 and a-f (the String is lower cased first).
+ * Returns 0 if the String does not contain any interesting characters.
+ *
+ * @param s the String to extract a <code>short</code> from, may not be <code>null</code>
+ * @return a <code>short</code>
+ * @throws NullPointerException if the String is <code>null</code>
+ */
+ public static short parseShort(String s) throws NullPointerException {
+ s = s.toLowerCase();
+ short out = 0;
+ byte shifts = 0;
+ char c;
+ for (int i = 0; i < s.length() && shifts < 4; i++) {
+ c = s.charAt(i);
+ if ((c > 47) && (c < 58)) {
+ out <<= 4;
+ ++shifts;
+ out |= c - 48;
+ } else if ((c > 96) && (c < 103)) {
+ ++shifts;
+ out <<= 4;
+ out |= c - 87;
+ }
+ }
+ return out;
+ }
+
+ /**
+ * Parses a <code>byte</code> from a hex encoded number. This method will skip
+ * all characters that are not 0-9 and a-f (the String is lower cased first).
+ * Returns 0 if the String does not contain any interesting characters.
+ *
+ * @param s the String to extract a <code>byte</code> from, may not be <code>null</code>
+ * @return a <code>byte</code>
+ * @throws NullPointerException if the String is <code>null</code>
+ */
+ public static byte parseByte(String s) throws NullPointerException {
+ s = s.toLowerCase();
+ byte out = 0;
+ byte shifts = 0;
+ char c;
+ for (int i = 0; i < s.length() && shifts < 2; i++) {
+ c = s.charAt(i);
+ if ((c > 47) && (c < 58)) {
+ out <<= 4;
+ ++shifts;
+ out |= c - 48;
+ } else if ((c > 96) && (c < 103)) {
+ ++shifts;
+ out <<= 4;
+ out |= c - 87;
+ }
+ }
+ return out;
+ }
+}
[19/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/StringUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/StringUtils.java b/utils/src/main/java/com/cloud/utils/StringUtils.java
new file mode 100644
index 0000000..c598be8
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/StringUtils.java
@@ -0,0 +1,323 @@
+//
+// 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 com.cloud.utils;
+
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.owasp.esapi.StringUtilities;
+
+public class StringUtils {
+ private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+ private static Charset preferredACSCharset;
+ private static final String UTF8 = "UTF-8";
+
+ static {
+ if (isUtf8Supported()) {
+ preferredACSCharset = Charset.forName(UTF8);
+ } else {
+ preferredACSCharset = Charset.defaultCharset();
+ }
+ }
+
+ public static Charset getPreferredCharset() {
+ return preferredACSCharset;
+ }
+
+ public static boolean isUtf8Supported() {
+ return Charset.isSupported(UTF8);
+ }
+
+ protected static Charset getDefaultCharset() {
+ return Charset.defaultCharset();
+ }
+
+ public static String join(final Iterable<? extends Object> iterable, final String delim) {
+ final StringBuilder sb = new StringBuilder();
+ if (iterable != null) {
+ final Iterator<? extends Object> iter = iterable.iterator();
+ if (iter.hasNext()) {
+ final Object next = iter.next();
+ sb.append(next.toString());
+ }
+ while (iter.hasNext()) {
+ final Object next = iter.next();
+ sb.append(delim + next.toString());
+ }
+ }
+ return sb.toString();
+ }
+
+ public static String join(final String delimiter, final Object... components) {
+ return org.apache.commons.lang.StringUtils.join(components, delimiter);
+ }
+
+ public static boolean isNotBlank(final String str) {
+ if (str != null && str.trim().length() > 0) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public static String cleanupTags(String tags) {
+ if (tags != null) {
+ final String[] tokens = tags.split(",");
+ final StringBuilder t = new StringBuilder();
+ for (int i = 0; i < tokens.length; i++) {
+ t.append(tokens[i].trim()).append(",");
+ }
+ t.delete(t.length() - 1, t.length());
+ tags = t.toString();
+ }
+
+ return tags;
+ }
+
+ /**
+ * @param tags
+ * @return List of tags
+ */
+ public static List<String> csvTagsToList(final String tags) {
+ final List<String> tagsList = new ArrayList<String>();
+
+ if (tags != null) {
+ final String[] tokens = tags.split(",");
+ for (int i = 0; i < tokens.length; i++) {
+ tagsList.add(tokens[i].trim());
+ }
+ }
+
+ return tagsList;
+ }
+
+ /**
+ * Converts a List of tags to a comma separated list
+ * @param tags
+ * @return String containing a comma separated list of tags
+ */
+
+ public static String listToCsvTags(final List<String> tagsList) {
+ final StringBuilder tags = new StringBuilder();
+ if (tagsList.size() > 0) {
+ for (int i = 0; i < tagsList.size(); i++) {
+ tags.append(tagsList.get(i));
+ if (i != tagsList.size() - 1) {
+ tags.append(',');
+ }
+ }
+ }
+
+ return tags.toString();
+ }
+
+ public static String getExceptionStackInfo(final Throwable e) {
+ final StringBuffer sb = new StringBuffer();
+
+ sb.append(e.toString()).append("\n");
+ final StackTraceElement[] elemnents = e.getStackTrace();
+ for (final StackTraceElement element : elemnents) {
+ sb.append(element.getClassName()).append(".");
+ sb.append(element.getMethodName()).append("(");
+ sb.append(element.getFileName()).append(":");
+ sb.append(element.getLineNumber()).append(")");
+ sb.append("\n");
+ }
+
+ return sb.toString();
+ }
+
+ public static String unicodeEscape(final String s) {
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < s.length(); i++) {
+ final char c = s.charAt(i);
+ if (c >> 7 > 0) {
+ sb.append("\\u");
+ sb.append(hexChar[c >> 12 & 0xF]); // append the hex character for the left-most 4-bits
+ sb.append(hexChar[c >> 8 & 0xF]); // hex for the second group of 4-bits from the left
+ sb.append(hexChar[c >> 4 & 0xF]); // hex for the third group
+ sb.append(hexChar[c & 0xF]); // hex for the last group, e.g., the right most 4-bits
+ } else {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
+ public static String getMaskedPasswordForDisplay(final String password) {
+ if (password == null || password.isEmpty()) {
+ return "*";
+ }
+
+ final StringBuffer sb = new StringBuffer();
+ sb.append(password.charAt(0));
+ for (int i = 1; i < password.length(); i++) {
+ sb.append("*");
+ }
+
+ return sb.toString();
+ }
+
+ // removes a password request param and it's value, also considering password is in query parameter value which has been url encoded
+ private static final Pattern REGEX_PASSWORD_QUERYSTRING = Pattern.compile("(&|%26)?[^(&|%26)]*((p|P)assword|accesskey|secretkey)(=|%3D).*?(?=(%26|[&'\"]|$))");
+
+ // removes a password/accesskey/ property from a response json object
+ private static final Pattern REGEX_PASSWORD_JSON = Pattern.compile("\"((p|P)assword|accesskey|secretkey)\":\\s?\".*?\",?");
+
+ private static final Pattern REGEX_PASSWORD_DETAILS = Pattern.compile("(&|%26)?details(\\[|%5B)\\d*(\\]|%5D)\\.key(=|%3D)((p|P)assword|accesskey|secretkey)(?=(%26|[&'\"]))");
+
+ private static final Pattern REGEX_PASSWORD_DETAILS_INDEX = Pattern.compile("details(\\[|%5B)\\d*(\\]|%5D)");
+
+ private static final Pattern REGEX_REDUNDANT_AND = Pattern.compile("(&|%26)(&|%26)+");
+
+ // Responsible for stripping sensitive content from request and response strings
+ public static String cleanString(final String stringToClean) {
+ String cleanResult = "";
+ if (stringToClean != null) {
+ cleanResult = REGEX_PASSWORD_QUERYSTRING.matcher(stringToClean).replaceAll("");
+ cleanResult = REGEX_PASSWORD_JSON.matcher(cleanResult).replaceAll("");
+ final Matcher detailsMatcher = REGEX_PASSWORD_DETAILS.matcher(cleanResult);
+ while (detailsMatcher.find()) {
+ final Matcher detailsIndexMatcher = REGEX_PASSWORD_DETAILS_INDEX.matcher(detailsMatcher.group());
+ if (detailsIndexMatcher.find()) {
+ cleanResult = cleanDetails(cleanResult, detailsIndexMatcher.group());
+ }
+ }
+ }
+ return cleanResult;
+ }
+
+ public static String cleanDetails(final String stringToClean, final String detailsIndexSting) {
+ String cleanResult = stringToClean;
+ for (final String log : stringToClean.split("&|%26")) {
+ if (log.contains(detailsIndexSting)) {
+ cleanResult = cleanResult.replace(log, "");
+ }
+ }
+ cleanResult = REGEX_REDUNDANT_AND.matcher(cleanResult).replaceAll("&");
+ return cleanResult;
+ }
+
+ public static boolean areTagsEqual(final String tags1, final String tags2) {
+ if (tags1 == null && tags2 == null) {
+ return true;
+ }
+
+ if (tags1 != null && tags2 == null) {
+ return false;
+ }
+
+ if (tags1 == null && tags2 != null) {
+ return false;
+ }
+
+ final String delimiter = ",";
+
+ final List<String> lstTags1 = new ArrayList<String>();
+ final String[] aTags1 = tags1.split(delimiter);
+
+ for (final String tag1 : aTags1) {
+ lstTags1.add(tag1.toLowerCase());
+ }
+
+ final List<String> lstTags2 = new ArrayList<String>();
+ final String[] aTags2 = tags2.split(delimiter);
+
+ for (final String tag2 : aTags2) {
+ lstTags2.add(tag2.toLowerCase());
+ }
+
+ return lstTags1.containsAll(lstTags2) && lstTags2.containsAll(lstTags1);
+ }
+
+ public static String stripControlCharacters(final String s) {
+ return StringUtilities.stripControls(s);
+ }
+
+ public static int formatForOutput(final String text, final int start, final int columns, final char separator) {
+ if (start >= text.length()) {
+ return -1;
+ }
+
+ int end = start + columns;
+ if (end > text.length()) {
+ end = text.length();
+ }
+ final String searchable = text.substring(start, end);
+ final int found = searchable.lastIndexOf(separator);
+ return found > 0 ? found : end - start;
+ }
+
+ public static Map<String, String> stringToMap(final String s) {
+ final Map<String, String> map = new HashMap<String, String>();
+ final String[] elements = s.split(";");
+ for (final String parts : elements) {
+ final String[] keyValue = parts.split(":");
+ map.put(keyValue[0], keyValue[1]);
+ }
+ return map;
+ }
+
+ public static String mapToString(final Map<String, String> map) {
+ String s = "";
+ for (final Map.Entry<String, String> entry : map.entrySet()) {
+ s += entry.getKey() + ":" + entry.getValue() + ";";
+ }
+ if (s.length() > 0) {
+ s = s.substring(0, s.length() - 1);
+ }
+ return s;
+ }
+
+ public static <T> List<T> applyPagination(final List<T> originalList, final Long startIndex, final Long pageSizeVal) {
+ // Most likely pageSize will never exceed int value, and we need integer to partition the listToReturn
+ final boolean applyPagination = startIndex != null && pageSizeVal != null
+ && startIndex <= Integer.MAX_VALUE && startIndex >= Integer.MIN_VALUE && pageSizeVal <= Integer.MAX_VALUE
+ && pageSizeVal >= Integer.MIN_VALUE;
+ List<T> listWPagination = null;
+ if (applyPagination) {
+ listWPagination = new ArrayList<>();
+ final int index = startIndex.intValue() == 0 ? 0 : startIndex.intValue() / pageSizeVal.intValue();
+ final List<List<T>> partitions = StringUtils.partitionList(originalList, pageSizeVal.intValue());
+ if (index < partitions.size()) {
+ listWPagination = partitions.get(index);
+ }
+ }
+ return listWPagination;
+ }
+
+ private static <T> List<List<T>> partitionList(final List<T> originalList, final int chunkSize) {
+ final List<List<T>> listOfChunks = new ArrayList<List<T>>();
+ for (int i = 0; i < originalList.size() / chunkSize; i++) {
+ listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize + chunkSize));
+ }
+ if (originalList.size() % chunkSize != 0) {
+ listOfChunks.add(originalList.subList(originalList.size() - originalList.size() % chunkSize, originalList.size()));
+ }
+ return listOfChunks;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/SwiftUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/SwiftUtil.java b/utils/src/main/java/com/cloud/utils/SwiftUtil.java
new file mode 100644
index 0000000..1136818
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/SwiftUtil.java
@@ -0,0 +1,239 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.OutputInterpreter;
+import com.cloud.utils.script.Script;
+
+public class SwiftUtil {
+ private static Logger logger = Logger.getLogger(SwiftUtil.class);
+ private static final long SWIFT_MAX_SIZE = 5L * 1024L * 1024L * 1024L;
+
+ public interface SwiftClientCfg {
+ String getAccount();
+
+ String getUserName();
+
+ String getKey();
+
+ String getEndPoint();
+ }
+
+ private static String getSwiftCLIPath() {
+ String swiftCLI = Script.findScript("scripts/storage/secondary", "swift");
+ if (swiftCLI == null) {
+ logger.debug("Can't find swift cli at scripts/storage/secondary/swift");
+ throw new CloudRuntimeException("Can't find swift cli at scripts/storage/secondary/swift");
+ }
+ return swiftCLI;
+ }
+
+ public static boolean postMeta(SwiftClientCfg cfg, String container, String object, Map<String, String> metas) {
+ String swiftCli = getSwiftCLIPath();
+ StringBuilder cms = new StringBuilder();
+ for (Map.Entry<String, String> entry : metas.entrySet()) {
+ cms.append(" -m ");
+ cms.append(entry.getKey());
+ cms.append(":");
+ cms.append(entry.getValue());
+ cms.append(" ");
+ }
+ Script command = new Script("/bin/bash", logger);
+ command.add("-c");
+ command.add("/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() + " -K " + cfg.getKey() + " post " +
+ container + " " + object + " " + cms.toString());
+ OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
+ String result = command.execute(parser);
+ if (result != null) {
+ throw new CloudRuntimeException("Failed to post meta" + result);
+ }
+ return true;
+ }
+
+ public static String putObject(SwiftClientCfg cfg, File srcFile, String container, String fileName) {
+ String swiftCli = getSwiftCLIPath();
+ if (fileName == null) {
+ fileName = srcFile.getName();
+ }
+ String srcDirectory = srcFile.getParent();
+ Script command = new Script("/bin/bash", logger);
+ long size = srcFile.length();
+ command.add("-c");
+ if (size <= SWIFT_MAX_SIZE) {
+ command.add("cd " + srcDirectory + ";/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() +
+ " -K " + cfg.getKey() + " upload " + container + " " + fileName);
+ } else {
+ command.add("cd " + srcDirectory + ";/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() +
+ " -K " + cfg.getKey() + " upload -S " + SWIFT_MAX_SIZE + " " + container + " " + fileName);
+ }
+ OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
+ String result = command.execute(parser);
+ if (result != null) {
+ throw new CloudRuntimeException("Failed to upload file: " + result);
+ }
+
+ if (parser.getLines() != null) {
+ String[] lines = parser.getLines().split("\\n");
+ for (String line : lines) {
+ if (line.contains("Errno") || line.contains("failed") || line.contains("not found")) {
+ throw new CloudRuntimeException("Failed to upload file: " + Arrays.toString(lines));
+ }
+ }
+ }
+
+ return container + File.separator + srcFile.getName();
+ }
+
+ private static StringBuilder buildSwiftCmd(SwiftClientCfg swift) {
+ String swiftCli = getSwiftCLIPath();
+ StringBuilder sb = new StringBuilder();
+ sb.append(" /usr/bin/python ");
+ sb.append(swiftCli);
+ sb.append(" -A ");
+ sb.append(swift.getEndPoint());
+ sb.append(" -U ");
+ sb.append(swift.getAccount());
+ sb.append(":");
+ sb.append(swift.getUserName());
+ sb.append(" -K ");
+ sb.append(swift.getKey());
+ sb.append(" ");
+ return sb;
+ }
+
+ public static String[] list(SwiftClientCfg swift, String container, String rFilename) {
+ getSwiftCLIPath();
+ Script command = new Script("/bin/bash", logger);
+ command.add("-c");
+
+ StringBuilder swiftCmdBuilder = buildSwiftCmd(swift);
+ swiftCmdBuilder.append(" list ");
+ swiftCmdBuilder.append(container);
+
+ if (rFilename != null) {
+ swiftCmdBuilder.append(" -p ");
+ swiftCmdBuilder.append(rFilename);
+ }
+
+ command.add(swiftCmdBuilder.toString());
+ OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
+ String result = command.execute(parser);
+ if (result == null && parser.getLines() != null && !parser.getLines().equalsIgnoreCase("")) {
+ String[] lines = parser.getLines().split("\\n");
+ return lines;
+ } else {
+ if (result != null) {
+ String errMsg = "swiftList failed , err=" + result;
+ logger.debug("Failed to list " + errMsg);
+ } else {
+ String errMsg = "swiftList failed, no lines returns";
+ logger.debug("Failed to list " + errMsg);
+ }
+ }
+ return new String[0];
+ }
+
+ public static File getObject(SwiftClientCfg cfg, File destDirectory, String swiftPath) {
+ int firstIndexOfSeparator = swiftPath.indexOf(File.separator);
+ String container = swiftPath.substring(0, firstIndexOfSeparator);
+ String srcPath = swiftPath.substring(firstIndexOfSeparator + 1);
+ String destFilePath = null;
+ if (destDirectory.isDirectory()) {
+ destFilePath = destDirectory.getAbsolutePath() + File.separator + srcPath;
+ } else {
+ destFilePath = destDirectory.getAbsolutePath();
+ }
+ String swiftCli = getSwiftCLIPath();
+ Script command = new Script("/bin/bash", logger);
+ command.add("-c");
+ command.add("/usr/bin/python " + swiftCli + " -A " + cfg.getEndPoint() + " -U " + cfg.getAccount() + ":" + cfg.getUserName() + " -K " + cfg.getKey() +
+ " download " + container + " " + srcPath + " -o " + destFilePath);
+ OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
+ String result = command.execute(parser);
+ if (result != null) {
+ String errMsg = "swiftDownload failed err=" + result;
+ logger.debug(errMsg);
+ throw new CloudRuntimeException("failed to get object: " + swiftPath);
+ }
+ if (parser.getLines() != null) {
+ String[] lines = parser.getLines().split("\\n");
+ for (String line : lines) {
+ if (line.contains("Errno") || line.contains("failed")) {
+ String errMsg = "swiftDownload failed , err=" + Arrays.toString(lines);
+ logger.debug(errMsg);
+ throw new CloudRuntimeException("Failed to get object: " + swiftPath);
+ }
+ }
+ }
+ return new File(destFilePath);
+ }
+
+ public static String getContainerName(String type, Long id) {
+ if (type.startsWith("T")) {
+ return "T-" + id;
+ } else if (type.startsWith("S")) {
+ return "S-" + id;
+ } else if (type.startsWith("V")) {
+ return "V-" + id;
+ }
+ return null;
+ }
+
+ public static String[] splitSwiftPath(String path) {
+ int index = path.indexOf(File.separator);
+ if (index == -1) {
+ return null;
+ }
+ String[] paths = new String[2];
+ paths[0] = path.substring(0, index);
+ paths[1] = path.substring(index + 1);
+ return paths;
+ }
+
+ public static boolean deleteObject(SwiftClientCfg cfg, String path) {
+ Script command = new Script("/bin/bash", logger);
+ command.add("-c");
+
+ String[] paths = splitSwiftPath(path);
+ if (paths == null) {
+ return false;
+ }
+ String container = paths[0];
+ String objectName = paths[1];
+
+ StringBuilder swiftCmdBuilder = buildSwiftCmd(cfg);
+ swiftCmdBuilder.append(" delete ");
+ swiftCmdBuilder.append(container);
+ swiftCmdBuilder.append(" ");
+ swiftCmdBuilder.append(objectName);
+
+ command.add(swiftCmdBuilder.toString());
+ OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
+ command.execute(parser);
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/Ternary.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/Ternary.java b/utils/src/main/java/com/cloud/utils/Ternary.java
new file mode 100644
index 0000000..fdc2fc9
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/Ternary.java
@@ -0,0 +1,85 @@
+//
+// 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 com.cloud.utils;
+
+public class Ternary<T, U, V> {
+ private T t;
+ private U u;
+ private V v;
+
+ public Ternary(T t, U u, V v) {
+ this.t = t;
+ this.u = u;
+ this.v = v;
+ }
+
+ public T first() {
+ return t;
+ }
+
+ public void first(T t) {
+ this.t = t;
+ }
+
+ public U second() {
+ return u;
+ }
+
+ public void second(U u) {
+ this.u = u;
+ }
+
+ public V third() {
+ return v;
+ }
+
+ public void third(V v) {
+ this.v = v;
+ }
+
+ @Override
+ // Note: This means any two pairs with null for both values will match each
+ // other but what can I do? This is due to stupid type erasure.
+ public
+ int hashCode() {
+ return (t != null ? t.hashCode() : 0) | (u != null ? u.hashCode() : 0) | (v != null ? v.hashCode() : 0);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Ternary)) {
+ return false;
+ }
+ Ternary<?, ?, ?> that = (Ternary<?, ?, ?>)obj;
+ return (t != null ? t.equals(that.t) : that.t == null) && (u != null ? u.equals(that.u) : that.u == null) && (v != null ? v.equals(that.v) : that.v == null);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder("T[");
+ b.append(t != null ? t.toString() : "null");
+ b.append(":");
+ b.append(u != null ? u.toString() : "null");
+ b.append(":");
+ b.append(v != null ? v.toString() : "null");
+ b.append("]");
+ return b.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/UriUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/UriUtils.java b/utils/src/main/java/com/cloud/utils/UriUtils.java
new file mode 100644
index 0000000..631c629
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/UriUtils.java
@@ -0,0 +1,394 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.StringTokenizer;
+
+import javax.net.ssl.HttpsURLConnection;
+
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.commons.httpclient.auth.AuthScope;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.HeadMethod;
+import org.apache.commons.httpclient.util.URIUtil;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.client.utils.URLEncodedUtils;
+
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.crypt.DBEncryptionUtil;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class UriUtils {
+
+ public static final Logger s_logger = Logger.getLogger(UriUtils.class.getName());
+
+ public static String formNfsUri(String host, String path) {
+ try {
+ URI uri = new URI("nfs", host, path, null);
+ return uri.toString();
+ } catch (URISyntaxException e) {
+ throw new CloudRuntimeException("Unable to form nfs URI: " + host + " - " + path);
+ }
+ }
+
+ public static String formIscsiUri(String host, String iqn, Integer lun) {
+ try {
+ String path = iqn;
+ if (lun != null) {
+ path += "/" + lun.toString();
+ }
+ URI uri = new URI("iscsi", host, path, null);
+ return uri.toString();
+ } catch (URISyntaxException e) {
+ throw new CloudRuntimeException("Unable to form iscsi URI: " + host + " - " + iqn + " - " + lun);
+ }
+ }
+
+ public static String formFileUri(String path) {
+ File file = new File(path);
+
+ return file.toURI().toString();
+ }
+
+ // a simple URI component helper (Note: it does not deal with URI paramemeter area)
+ public static String encodeURIComponent(String url) {
+ int schemeTail = url.indexOf("://");
+
+ int pathStart = 0;
+ if (schemeTail > 0)
+ pathStart = url.indexOf('/', schemeTail + 3);
+ else
+ pathStart = url.indexOf('/');
+
+ if (pathStart > 0) {
+ String[] tokens = url.substring(pathStart + 1).split("/");
+ StringBuilder sb = new StringBuilder(url.substring(0, pathStart));
+ for (String token : tokens) {
+ sb.append("/").append(URLEncoder.encode(token));
+ }
+
+ return sb.toString();
+ }
+
+ // no need to do URL component encoding
+ return url;
+ }
+
+ public static String getCifsUriParametersProblems(URI uri) {
+ if (!UriUtils.hostAndPathPresent(uri)) {
+ String errMsg = "cifs URI missing host and/or path. Make sure it's of the format cifs://hostname/path";
+ s_logger.warn(errMsg);
+ return errMsg;
+ }
+ return null;
+ }
+
+ public static boolean hostAndPathPresent(URI uri) {
+ return !(uri.getHost() == null || uri.getHost().trim().isEmpty() || uri.getPath() == null || uri.getPath().trim().isEmpty());
+ }
+
+ public static boolean cifsCredentialsPresent(URI uri) {
+ List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
+ boolean foundUser = false;
+ boolean foundPswd = false;
+ for (NameValuePair nvp : args) {
+ String name = nvp.getName();
+ if (name.equals("user")) {
+ foundUser = true;
+ s_logger.debug("foundUser is" + foundUser);
+ } else if (name.equals("password")) {
+ foundPswd = true;
+ s_logger.debug("foundPswd is" + foundPswd);
+ }
+ }
+ return (foundUser && foundPswd);
+ }
+
+ public static String getUpdateUri(String url, boolean encrypt) {
+ String updatedPath = null;
+ try {
+ String query = URIUtil.getQuery(url);
+ URIBuilder builder = new URIBuilder(url);
+ builder.removeQuery();
+
+ StringBuilder updatedQuery = new StringBuilder();
+ List<NameValuePair> queryParams = getUserDetails(query);
+ ListIterator<NameValuePair> iterator = queryParams.listIterator();
+ while (iterator.hasNext()) {
+ NameValuePair param = iterator.next();
+ String value = null;
+ if ("password".equalsIgnoreCase(param.getName()) &&
+ param.getValue() != null) {
+ value = encrypt ? DBEncryptionUtil.encrypt(param.getValue()) : DBEncryptionUtil.decrypt(param.getValue());
+ } else {
+ value = param.getValue();
+ }
+
+ if (updatedQuery.length() == 0) {
+ updatedQuery.append(param.getName()).append('=')
+ .append(value);
+ } else {
+ updatedQuery.append('&').append(param.getName())
+ .append('=').append(value);
+ }
+ }
+
+ String schemeAndHost = "";
+ URI newUri = builder.build();
+ if (newUri.getScheme() != null) {
+ schemeAndHost = newUri.getScheme() + "://" + newUri.getHost();
+ }
+
+ updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery;
+ } catch (URISyntaxException e) {
+ throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage());
+ }
+
+ return updatedPath;
+ }
+
+ private static List<NameValuePair> getUserDetails(String query) {
+ List<NameValuePair> details = new ArrayList<NameValuePair>();
+ if (query != null && !query.isEmpty()) {
+ StringTokenizer allParams = new StringTokenizer(query, "&");
+ while (allParams.hasMoreTokens()) {
+ String param = allParams.nextToken();
+ details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")),
+ param.substring(param.indexOf("=") + 1)));
+ }
+ }
+
+ return details;
+ }
+
+ // Get the size of a file from URL response header.
+ public static Long getRemoteSize(String url) {
+ Long remoteSize = (long)0;
+ HttpURLConnection httpConn = null;
+ HttpsURLConnection httpsConn = null;
+ try {
+ URI uri = new URI(url);
+ if (uri.getScheme().equalsIgnoreCase("http")) {
+ httpConn = (HttpURLConnection)uri.toURL().openConnection();
+ if (httpConn != null) {
+ httpConn.setConnectTimeout(2000);
+ httpConn.setReadTimeout(5000);
+ String contentLength = httpConn.getHeaderField("content-length");
+ if (contentLength != null) {
+ remoteSize = Long.parseLong(contentLength);
+ }
+ httpConn.disconnect();
+ }
+ } else if (uri.getScheme().equalsIgnoreCase("https")) {
+ httpsConn = (HttpsURLConnection)uri.toURL().openConnection();
+ if (httpsConn != null) {
+ String contentLength = httpsConn.getHeaderField("content-length");
+ if (contentLength != null) {
+ remoteSize = Long.parseLong(contentLength);
+ }
+ httpsConn.disconnect();
+ }
+ }
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Invalid URL " + url);
+ } catch (IOException e) {
+ throw new IllegalArgumentException("Unable to establish connection with URL " + url);
+ }
+ return remoteSize;
+ }
+
+ public static Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
+ return validateUrl(null, url);
+ }
+
+ public static Pair<String, Integer> validateUrl(String format, String url) throws IllegalArgumentException {
+ try {
+ URI uri = new URI(url);
+ if ((uri.getScheme() == null) ||
+ (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) {
+ throw new IllegalArgumentException("Unsupported scheme for url: " + url);
+ }
+ int port = uri.getPort();
+ if (!(port == 80 || port == 8080 || port == 443 || port == -1)) {
+ throw new IllegalArgumentException("Only ports 80, 8080 and 443 are allowed");
+ }
+
+ if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
+ port = 443;
+ } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
+ port = 80;
+ }
+
+ String host = uri.getHost();
+ try {
+ InetAddress hostAddr = InetAddress.getByName(host);
+ if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) {
+ throw new IllegalArgumentException("Illegal host specified in url");
+ }
+ if (hostAddr instanceof Inet6Address) {
+ throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
+ }
+ } catch (UnknownHostException uhe) {
+ throw new IllegalArgumentException("Unable to resolve " + host);
+ }
+
+ // verify format
+ if (format != null) {
+ String uripath = uri.getPath();
+ checkFormat(format, uripath);
+ }
+ return new Pair<String, Integer>(host, port);
+ } catch (URISyntaxException use) {
+ throw new IllegalArgumentException("Invalid URL: " + url);
+ }
+ }
+
+ // use http HEAD method to validate url
+ public static void checkUrlExistence(String url) {
+ if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) {
+ HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
+ HeadMethod httphead = new HeadMethod(url);
+ try {
+ if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) {
+ throw new IllegalArgumentException("Invalid URL: " + url);
+ }
+ } catch (HttpException hte) {
+ throw new IllegalArgumentException("Cannot reach URL: " + url);
+ } catch (IOException ioe) {
+ throw new IllegalArgumentException("Cannot reach URL: " + url);
+ }
+ }
+ }
+
+ // verify if a URI path is compliance with the file format given
+ private static void checkFormat(String format, String uripath) {
+ if ((!uripath.toLowerCase().endsWith("vhd")) && (!uripath.toLowerCase().endsWith("vhd.zip")) && (!uripath.toLowerCase().endsWith("vhd.bz2")) &&
+ (!uripath.toLowerCase().endsWith("vhdx")) && (!uripath.toLowerCase().endsWith("vhdx.gz")) &&
+ (!uripath.toLowerCase().endsWith("vhdx.bz2")) && (!uripath.toLowerCase().endsWith("vhdx.zip")) &&
+ (!uripath.toLowerCase().endsWith("vhd.gz")) && (!uripath.toLowerCase().endsWith("qcow2")) && (!uripath.toLowerCase().endsWith("qcow2.zip")) &&
+ (!uripath.toLowerCase().endsWith("qcow2.bz2")) && (!uripath.toLowerCase().endsWith("qcow2.gz")) && (!uripath.toLowerCase().endsWith("ova")) &&
+ (!uripath.toLowerCase().endsWith("ova.zip")) && (!uripath.toLowerCase().endsWith("ova.bz2")) && (!uripath.toLowerCase().endsWith("ova.gz")) &&
+ (!uripath.toLowerCase().endsWith("tar")) && (!uripath.toLowerCase().endsWith("tar.zip")) && (!uripath.toLowerCase().endsWith("tar.bz2")) &&
+ (!uripath.toLowerCase().endsWith("tar.gz")) && (!uripath.toLowerCase().endsWith("vmdk")) && (!uripath.toLowerCase().endsWith("vmdk.gz")) &&
+ (!uripath.toLowerCase().endsWith("vmdk.zip")) && (!uripath.toLowerCase().endsWith("vmdk.bz2")) && (!uripath.toLowerCase().endsWith("img")) &&
+ (!uripath.toLowerCase().endsWith("img.gz")) && (!uripath.toLowerCase().endsWith("img.zip")) && (!uripath.toLowerCase().endsWith("img.bz2")) &&
+ (!uripath.toLowerCase().endsWith("raw")) && (!uripath.toLowerCase().endsWith("raw.gz")) && (!uripath.toLowerCase().endsWith("raw.bz2")) &&
+ (!uripath.toLowerCase().endsWith("raw.zip")) && (!uripath.toLowerCase().endsWith("iso")) && (!uripath.toLowerCase().endsWith("iso.zip"))
+ && (!uripath.toLowerCase().endsWith("iso.bz2")) && (!uripath.toLowerCase().endsWith("iso.gz"))) {
+ throw new IllegalArgumentException("Please specify a valid " + format.toLowerCase());
+ }
+
+ if ((format.equalsIgnoreCase("vhd")
+ && (!uripath.toLowerCase().endsWith("vhd")
+ && !uripath.toLowerCase().endsWith("vhd.zip")
+ && !uripath.toLowerCase().endsWith("vhd.bz2")
+ && !uripath.toLowerCase().endsWith("vhd.gz")))
+ || (format.equalsIgnoreCase("vhdx")
+ && (!uripath.toLowerCase().endsWith("vhdx")
+ && !uripath.toLowerCase().endsWith("vhdx.zip")
+ && !uripath.toLowerCase().endsWith("vhdx.bz2")
+ && !uripath.toLowerCase().endsWith("vhdx.gz")))
+ || (format.equalsIgnoreCase("qcow2")
+ && (!uripath.toLowerCase().endsWith("qcow2")
+ && !uripath.toLowerCase().endsWith("qcow2.zip")
+ && !uripath.toLowerCase().endsWith("qcow2.bz2")
+ && !uripath.toLowerCase().endsWith("qcow2.gz")))
+ || (format.equalsIgnoreCase("ova")
+ && (!uripath.toLowerCase().endsWith("ova")
+ && !uripath.toLowerCase().endsWith("ova.zip")
+ && !uripath.toLowerCase().endsWith("ova.bz2")
+ && !uripath.toLowerCase().endsWith("ova.gz")))
+ || (format.equalsIgnoreCase("tar")
+ && (!uripath.toLowerCase().endsWith("tar")
+ && !uripath.toLowerCase().endsWith("tar.zip")
+ && !uripath.toLowerCase().endsWith("tar.bz2")
+ && !uripath.toLowerCase().endsWith("tar.gz")))
+ || (format.equalsIgnoreCase("raw")
+ && (!uripath.toLowerCase().endsWith("img")
+ && !uripath.toLowerCase().endsWith("img.zip")
+ && !uripath.toLowerCase().endsWith("img.bz2")
+ && !uripath.toLowerCase().endsWith("img.gz")
+ && !uripath.toLowerCase().endsWith("raw")
+ && !uripath.toLowerCase().endsWith("raw.bz2")
+ && !uripath.toLowerCase().endsWith("raw.zip")
+ && !uripath.toLowerCase().endsWith("raw.gz")))
+ || (format.equalsIgnoreCase("vmdk")
+ && (!uripath.toLowerCase().endsWith("vmdk")
+ && !uripath.toLowerCase().endsWith("vmdk.zip")
+ && !uripath.toLowerCase().endsWith("vmdk.bz2")
+ && !uripath.toLowerCase().endsWith("vmdk.gz")))
+ || (format.equalsIgnoreCase("iso")
+ && (!uripath.toLowerCase().endsWith("iso")
+ && !uripath.toLowerCase().endsWith("iso.zip")
+ && !uripath.toLowerCase().endsWith("iso.bz2")
+ && !uripath.toLowerCase().endsWith("iso.gz")))) {
+ throw new IllegalArgumentException("Please specify a valid URL. URL:" + uripath + " is an invalid for the format " + format.toLowerCase());
+ }
+
+ }
+
+ public static InputStream getInputStreamFromUrl(String url, String user, String password) {
+
+ try {
+ Pair<String, Integer> hostAndPort = validateUrl(url);
+ HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
+ if ((user != null) && (password != null)) {
+ httpclient.getParams().setAuthenticationPreemptive(true);
+ Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
+ httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
+ s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
+ }
+ // Execute the method.
+ GetMethod method = new GetMethod(url);
+ int statusCode = httpclient.executeMethod(method);
+
+ if (statusCode != HttpStatus.SC_OK) {
+ s_logger.error("Failed to read from URL: " + url);
+ return null;
+ }
+
+ return method.getResponseBodyAsStream();
+ } catch (Exception ex) {
+ s_logger.error("Failed to read from URL: " + url);
+ return null;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/UsernamePasswordValidator.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/UsernamePasswordValidator.java b/utils/src/main/java/com/cloud/utils/UsernamePasswordValidator.java
new file mode 100644
index 0000000..f11186c
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/UsernamePasswordValidator.java
@@ -0,0 +1,49 @@
+//
+// 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 com.cloud.utils;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class UsernamePasswordValidator {
+ private Pattern usernamePattern;
+ private Pattern passwordPattern;
+ private Matcher matcher;
+
+ private static final String USERNAME_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$";
+ private static final String PASSWORD_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$";
+
+ public UsernamePasswordValidator() {
+ usernamePattern = Pattern.compile(USERNAME_PATTERN);
+ passwordPattern = Pattern.compile(PASSWORD_PATTERN);
+
+ }
+
+ public boolean validateUsername(final String username) {
+ matcher = usernamePattern.matcher(username);
+ return matcher.matches();
+ }
+
+ public boolean validatePassword(final String password) {
+ matcher = passwordPattern.matcher(password);
+ return matcher.matches();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/UuidUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/UuidUtils.java b/utils/src/main/java/com/cloud/utils/UuidUtils.java
new file mode 100644
index 0000000..9c4a756
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/UuidUtils.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import org.apache.xerces.impl.xpath.regex.RegularExpression;
+
+public class UuidUtils {
+
+ public final static String first(String uuid) {
+ return uuid.substring(0, uuid.indexOf('-'));
+ }
+
+ public static boolean validateUUID(String uuid) {
+ RegularExpression regex = new RegularExpression("[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}");
+ return regex.matches(uuid);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/backoff/BackoffAlgorithm.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/backoff/BackoffAlgorithm.java b/utils/src/main/java/com/cloud/utils/backoff/BackoffAlgorithm.java
new file mode 100644
index 0000000..b8f3f00
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/backoff/BackoffAlgorithm.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.utils.backoff;
+
+import com.cloud.utils.component.Adapter;
+
+/**
+ * BackoffAlgorithm implements multiple BackoffAlgorithm.
+ */
+public interface BackoffAlgorithm extends Adapter {
+
+ /**
+ */
+ void waitBeforeRetry();
+
+ /**
+ * no longer need to backoff. reset to beginning.
+ */
+ void reset();
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java b/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java
new file mode 100644
index 0000000..14eae16
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java
@@ -0,0 +1,102 @@
+//
+// 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 com.cloud.utils.backoff.impl;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.ejb.Local;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.cloud.utils.NumbersUtil;
+import com.cloud.utils.backoff.BackoffAlgorithm;
+import com.cloud.utils.component.AdapterBase;
+
+/**
+ * An implementation of BackoffAlgorithm that waits for some seconds.
+ * After the time the client can try to perform the operation again.
+ *
+ * @config
+ * {@table
+ * || Param Name | Description | Values | Default ||
+ * || seconds | seconds to sleep | integer | 5 ||
+ * }
+ **/
+@Local(value = {BackoffAlgorithm.class})
+public class ConstantTimeBackoff extends AdapterBase implements BackoffAlgorithm, ConstantTimeBackoffMBean {
+ long _time;
+ private final Map<String, Thread> _asleep = new ConcurrentHashMap<String, Thread>();
+ private final static Log LOG = LogFactory.getLog(ConstantTimeBackoff.class);
+
+ @Override
+ public void waitBeforeRetry() {
+ Thread current = Thread.currentThread();
+ try {
+ _asleep.put(current.getName(), current);
+ Thread.sleep(_time);
+ } catch (InterruptedException e) {
+ // JMX or other threads may interrupt this thread, but let's log it
+ // anyway, no exception to log as this is not an error
+ LOG.info("Thread " + current.getName() + " interrupted while waiting for retry");
+ } finally {
+ _asleep.remove(current.getName());
+ }
+ return;
+ }
+
+ @Override
+ public void reset() {
+ }
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) {
+ _time = NumbersUtil.parseLong((String)params.get("seconds"), 5) * 1000;
+ return true;
+ }
+
+ @Override
+ public Collection<String> getWaiters() {
+ return _asleep.keySet();
+ }
+
+ @Override
+ public boolean wakeup(String threadName) {
+ Thread th = _asleep.get(threadName);
+ if (th != null) {
+ th.interrupt();
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public long getTimeToWait() {
+ return _time;
+ }
+
+ @Override
+ public void setTimeToWait(long seconds) {
+ _time = seconds * 1000;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java b/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java
new file mode 100644
index 0000000..4dc9f9c
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java
@@ -0,0 +1,35 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.backoff.impl;
+
+import java.util.Collection;
+
+import com.cloud.utils.mgmt.ManagementBean;
+
+public interface ConstantTimeBackoffMBean extends ManagementBean {
+ public long getTimeToWait();
+
+ public void setTimeToWait(long seconds);
+
+ Collection<String> getWaiters();
+
+ boolean wakeup(String threadName);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
new file mode 100644
index 0000000..a6d905d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
@@ -0,0 +1,355 @@
+//
+// 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 com.cloud.utils.cisco.n1kv.vsm;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import com.trilead.ssh2.Connection;
+import com.trilead.ssh2.Session;
+
+import com.cloud.utils.Pair;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.ssh.SSHCmdHelper;
+
+public class NetconfHelper {
+ private static final Logger s_logger = Logger.getLogger(NetconfHelper.class);
+
+ private static final String SSH_NETCONF_TERMINATOR = "]]>]]>";
+
+ private Connection _connection;
+
+ private Session _session;
+
+ public NetconfHelper(String ip, String username, String password) throws CloudRuntimeException {
+ _connection = SSHCmdHelper.acquireAuthorizedConnection(ip, username, password);
+ if (_connection == null) {
+ throw new CloudRuntimeException("Error opening ssh connection.");
+ }
+
+ try {
+ _session = _connection.openSession();
+ _session.startSubSystem("xmlagent");
+ exchangeHello();
+ } catch (final Exception e) {
+ disconnect();
+ s_logger.error("Failed to connect to device SSH server: " + e.getMessage());
+ throw new CloudRuntimeException("Failed to connect to SSH server: " + _connection.getHostname());
+ }
+ }
+
+ public void disconnect() {
+ if (_session != null) {
+ _session.close();
+ }
+ SSHCmdHelper.releaseSshConnection(_connection);
+ }
+
+ public void queryStatus() throws CloudRuntimeException {
+ // This command is used to query the server status.
+ String status =
+ "<?xml version=\"1.0\"?>" + "<nc:rpc message-id=\"1\" xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0" + "\"xmlns=\"http://www.cisco.com/nxos:1.0:xml\">" +
+ " <nc:get>" + " <nc:filter type=\"subtree\">" + " <show>" + " <xml>" + " <server>" + " <status/>" +
+ " </server>" + " </xml>" + " </show>" + " </nc:filter>" + " </nc:get>" + "</nc:rpc>" + SSH_NETCONF_TERMINATOR;
+ send(status);
+ // parse the rpc reply.
+ parseOkReply(receive());
+ }
+
+ public void addPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName)
+ throws CloudRuntimeException {
+ String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid, vdc, espName);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for adding port profile.");
+ }
+ }
+
+ public void addPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) throws CloudRuntimeException {
+ String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for adding port profile.");
+ }
+ }
+
+ public void updatePortProfile(String name, SwitchPortMode mode, List<Pair<VsmCommand.OperationType, String>> params) throws CloudRuntimeException {
+ String command = VsmCommand.getUpdatePortProfile(name, mode, params);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for updating port profile.");
+ }
+ }
+
+ public void deletePortProfile(String name) throws CloudRuntimeException {
+ String command = VsmCommand.getDeletePortProfile(name);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for deleting port profile.");
+ }
+ }
+
+ public void addPolicyMap(String name, int averageRate, int maxRate, int burstRate) throws CloudRuntimeException {
+ String command = VsmCommand.getAddPolicyMap(name, averageRate, maxRate, burstRate);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for adding/updating policy map.");
+ }
+ }
+
+ public void deletePolicyMap(String name) throws CloudRuntimeException {
+ String command = VsmCommand.getDeletePolicyMap(name);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for deleting policy map.");
+ }
+ }
+
+ public void updatePolicyMap(String name, int averageRate, int maxRate, int burstRate) throws CloudRuntimeException {
+ // Add and update of policy map work in the exact same way.
+ addPolicyMap(name, averageRate, maxRate, burstRate);
+ }
+
+ public void attachServicePolicy(String policyMap, String portProfile) throws CloudRuntimeException {
+ String command = VsmCommand.getServicePolicy(policyMap, portProfile, true);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for adding policy map.");
+ }
+ }
+
+ public void detachServicePolicy(String policyMap, String portProfile) throws CloudRuntimeException {
+ String command = VsmCommand.getServicePolicy(policyMap, portProfile, false);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for removing policy map.");
+ }
+ }
+
+ public void addVServiceNode(String vlanId, String ipAddr) throws CloudRuntimeException {
+ String command = VsmCommand.getVServiceNode(vlanId, ipAddr);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ parseOkReply(sendAndReceive(command));
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for adding vservice node for vlan " + vlanId);
+ }
+ }
+
+ public PortProfile getPortProfileByName(String name) throws CloudRuntimeException {
+ String command = VsmCommand.getPortProfile(name);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ String received = sendAndReceive(command);
+ VsmPortProfileResponse response = new VsmPortProfileResponse(received.trim());
+ if (!response.isResponseOk()) {
+ throw new CloudRuntimeException(response.toString());
+ } else {
+ return response.getPortProfile();
+ }
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for getting port profile.");
+ }
+ }
+
+ public PolicyMap getPolicyMapByName(String name) throws CloudRuntimeException {
+ String command = VsmCommand.getPolicyMap(name);
+ if (command != null) {
+ command = command.concat(SSH_NETCONF_TERMINATOR);
+ String received = sendAndReceive(command);
+ VsmPolicyMapResponse response = new VsmPolicyMapResponse(received.trim());
+ if (!response.isResponseOk()) {
+ throw new CloudRuntimeException(response.toString());
+ } else {
+ return response.getPolicyMap();
+ }
+ } else {
+ throw new CloudRuntimeException("Error generating rpc request for getting policy map.");
+ }
+ }
+
+ private void exchangeHello() {
+ String ack = receive();
+ String hello = VsmCommand.getHello() + SSH_NETCONF_TERMINATOR;
+ send(hello);
+ }
+
+ private String sendAndReceive(String command) {
+ String received;
+ synchronized (NetconfHelper.class) {
+ send(command);
+ received = receive();
+ }
+ return received;
+ }
+
+ private void send(String message) {
+ try {
+ OutputStream outputStream = _session.getStdin();
+ outputStream.write(message.getBytes());
+ outputStream.flush();
+ } catch (Exception e) {
+ s_logger.error("Failed to send message: " + e.getMessage());
+ throw new CloudRuntimeException("Failed to send message: " + e.getMessage());
+ }
+ }
+
+ private String receive() {
+ String response = new String("");
+ InputStream inputStream = _session.getStdout();
+
+ try {
+ Delimiter delimiter = new Delimiter();
+ byte[] buffer = new byte[1024];
+ int count = 0;
+
+ // Read the input stream till we find the end sequence ']]>]]>'.
+ while (true) {
+ int data = inputStream.read();
+ if (data != -1) {
+ byte[] dataStream = delimiter.parse(data);
+ if (delimiter.endReached()) {
+ response += new String(buffer, 0, count);
+ break;
+ }
+
+ if (dataStream != null) {
+ for (int i = 0; i < dataStream.length; i++) {
+ buffer[count] = dataStream[i];
+ count++;
+ if (count == 1024) {
+ response += new String(buffer, 0, count);
+ count = 0;
+ }
+ }
+ }
+ } else {
+ break;
+ }
+ }
+ } catch (final Exception e) {
+ throw new CloudRuntimeException("Error occured while reading from the stream: " + e.getMessage());
+ }
+
+ return response;
+ }
+
+ private void parseOkReply(String reply) throws CloudRuntimeException {
+ VsmOkResponse response = new VsmOkResponse(reply.trim());
+ if (!response.isResponseOk()) {
+ throw new CloudRuntimeException(response.toString());
+ }
+ }
+
+ private static class Delimiter {
+ private boolean _endReached = false;
+
+ // Used to accumulate response read while searching for end of response.
+ private byte[] _gatherResponse = new byte[6];
+
+ // Index into number of bytes read.
+ private int _offset = 0;
+
+ // True if ']]>]]>' detected.
+ boolean endReached() {
+ return _endReached;
+ }
+
+ // Parses the input stream and checks if end sequence is reached.
+ byte[] parse(int input) throws RuntimeException {
+ boolean collect = false;
+ byte[] streamRead = null;
+
+ // Check if end sequence matched.
+ switch (_offset) {
+ case 0:
+ if (input == ']') {
+ collect = true;
+ }
+ break;
+ case 1:
+ if (input == ']') {
+ collect = true;
+ }
+ break;
+ case 2:
+ if (input == '>') {
+ collect = true;
+ }
+ break;
+ case 3:
+ if (input == ']') {
+ collect = true;
+ }
+ break;
+ case 4:
+ if (input == ']') {
+ collect = true;
+ }
+ break;
+ case 5:
+ if (input == '>') {
+ collect = true;
+ _endReached = true;
+ }
+ break;
+ default:
+ throw new RuntimeException("Invalid index value: " + _offset);
+ }
+
+ if (collect) {
+ _gatherResponse[_offset++] = (byte)input;
+ } else {
+ // End sequence not yet reached. Return the stream of bytes collected so far.
+ streamRead = new byte[_offset + 1];
+ for (int index = 0; index < _offset; ++index) {
+ streamRead[index] = _gatherResponse[index];
+ }
+
+ streamRead[_offset] = (byte)input;
+ _offset = 0;
+ }
+
+ return streamRead;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java
new file mode 100644
index 0000000..01605d7
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.cisco.n1kv.vsm;
+
+public class PolicyMap {
+ public String policyMapName;
+ public int committedRate;
+ public int burstRate;
+ public int peakRate;
+
+ PolicyMap() {
+ policyMapName = null;
+ committedRate = 0;
+ burstRate = 0;
+ peakRate = 0;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java
new file mode 100644
index 0000000..53d9728
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java
@@ -0,0 +1,48 @@
+//
+// 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 com.cloud.utils.cisco.n1kv.vsm;
+
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
+
+public class PortProfile {
+ public PortProfileType type;
+ public SwitchPortMode mode;
+ public BindingType binding;
+ public String profileName;
+ public String inputPolicyMap;
+ public String outputPolicyMap;
+ public String vlan;
+ public boolean status;
+ public int maxPorts;
+
+ PortProfile() {
+ profileName = null;
+ inputPolicyMap = null;
+ outputPolicyMap = null;
+ vlan = null;
+ status = false;
+ maxPorts = 32;
+ type = PortProfileType.none;
+ mode = SwitchPortMode.none;
+ binding = BindingType.none;
+ }
+}
[14/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/NioClient.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/NioClient.java b/utils/src/main/java/com/cloud/utils/nio/NioClient.java
new file mode 100644
index 0000000..2f742f9
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/NioClient.java
@@ -0,0 +1,125 @@
+//
+// 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 com.cloud.utils.nio;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
+import java.security.GeneralSecurityException;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.utils.security.SSLUtils;
+
+public class NioClient extends NioConnection {
+ private static final Logger s_logger = Logger.getLogger(NioClient.class);
+
+ protected String _host;
+ protected String _bindAddress;
+ protected SocketChannel _clientConnection;
+
+ public NioClient(String name, String host, int port, int workers, HandlerFactory factory) {
+ super(name, port, workers, factory);
+ _host = host;
+ }
+
+ public void setBindAddress(String ipAddress) {
+ _bindAddress = ipAddress;
+ }
+
+ @Override
+ protected void init() throws IOException {
+ _selector = Selector.open();
+ Task task = null;
+
+ try {
+ _clientConnection = SocketChannel.open();
+ _clientConnection.configureBlocking(true);
+ s_logger.info("Connecting to " + _host + ":" + _port);
+
+ if (_bindAddress != null) {
+ s_logger.info("Binding outbound interface at " + _bindAddress);
+
+ InetSocketAddress bindAddr = new InetSocketAddress(_bindAddress, 0);
+ _clientConnection.socket().bind(bindAddr);
+ }
+
+ InetSocketAddress peerAddr = new InetSocketAddress(_host, _port);
+ _clientConnection.connect(peerAddr);
+
+ SSLEngine sslEngine = null;
+ // Begin SSL handshake in BLOCKING mode
+ _clientConnection.configureBlocking(true);
+
+ SSLContext sslContext = Link.initSSLContext(true);
+ sslEngine = sslContext.createSSLEngine(_host, _port);
+ sslEngine.setUseClientMode(true);
+ sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols()));
+
+ Link.doHandshake(_clientConnection, sslEngine, true);
+ s_logger.info("SSL: Handshake done");
+ s_logger.info("Connected to " + _host + ":" + _port);
+
+ _clientConnection.configureBlocking(false);
+ Link link = new Link(peerAddr, this);
+ link.setSSLEngine(sslEngine);
+ SelectionKey key = _clientConnection.register(_selector, SelectionKey.OP_READ);
+ link.setKey(key);
+ key.attach(link);
+ // Notice we've already connected due to the handshake, so let's get the
+ // remaining task done
+ task = _factory.create(Task.Type.CONNECT, link, null);
+ } catch (GeneralSecurityException e) {
+ _selector.close();
+ throw new IOException("Failed to initialise security", e);
+ } catch (IOException e) {
+ _selector.close();
+ throw e;
+ }
+
+ _executor.execute(task);
+ }
+
+ @Override
+ protected void registerLink(InetSocketAddress saddr, Link link) {
+ // don't do anything.
+ }
+
+ @Override
+ protected void unregisterLink(InetSocketAddress saddr) {
+ // don't do anything.
+ }
+
+ @Override
+ public void cleanUp() throws IOException {
+ super.cleanUp();
+ if (_clientConnection != null) {
+ _clientConnection.close();
+ }
+ s_logger.info("NioClient connection closed");
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/NioConnection.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/NioConnection.java b/utils/src/main/java/com/cloud/utils/nio/NioConnection.java
new file mode 100644
index 0000000..4c66360
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/NioConnection.java
@@ -0,0 +1,476 @@
+//
+// 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 com.cloud.utils.nio;
+
+import static com.cloud.utils.AutoCloseableUtil.closeAutoCloseable;
+
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.channels.CancelledKeyException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.utils.security.SSLUtils;
+
+import com.cloud.utils.concurrency.NamedThreadFactory;
+
+/**
+ * NioConnection abstracts the NIO socket operations. The Java implementation
+ * provides that.
+ */
+public abstract class NioConnection implements Runnable {
+ private static final Logger s_logger = Logger.getLogger(NioConnection.class);;
+
+ protected Selector _selector;
+ protected Thread _thread;
+ protected boolean _isRunning;
+ protected boolean _isStartup;
+ protected int _port;
+ protected List<ChangeRequest> _todos;
+ protected HandlerFactory _factory;
+ protected String _name;
+ protected ExecutorService _executor;
+
+ public NioConnection(String name, int port, int workers, HandlerFactory factory) {
+ _name = name;
+ _isRunning = false;
+ _thread = null;
+ _selector = null;
+ _port = port;
+ _factory = factory;
+ _executor = new ThreadPoolExecutor(workers, 5 * workers, 1, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(name + "-Handler"));
+ }
+
+ public void start() {
+ _todos = new ArrayList<ChangeRequest>();
+
+ _thread = new Thread(this, _name + "-Selector");
+ _isRunning = true;
+ _thread.start();
+ // Wait until we got init() done
+ synchronized (_thread) {
+ try {
+ _thread.wait();
+ } catch (InterruptedException e) {
+ s_logger.warn("Interrupted start thread ", e);
+ }
+ }
+ }
+
+ public void stop() {
+ _executor.shutdown();
+ _isRunning = false;
+ if (_thread != null) {
+ _thread.interrupt();
+ }
+ }
+
+ public boolean isRunning() {
+ return _thread.isAlive();
+ }
+
+ public boolean isStartup() {
+ return _isStartup;
+ }
+
+ @Override
+ public void run() {
+ synchronized (_thread) {
+ try {
+ init();
+ } catch (ConnectException e) {
+ s_logger.warn("Unable to connect to remote: is there a server running on port " + _port);
+ return;
+ } catch (IOException e) {
+ s_logger.error("Unable to initialize the threads.", e);
+ return;
+ } catch (Exception e) {
+ s_logger.error("Unable to initialize the threads due to unknown exception.", e);
+ return;
+ }
+ _isStartup = true;
+ _thread.notifyAll();
+ }
+
+ while (_isRunning) {
+ try {
+ _selector.select();
+
+ // Someone is ready for I/O, get the ready keys
+ Set<SelectionKey> readyKeys = _selector.selectedKeys();
+ Iterator<SelectionKey> i = readyKeys.iterator();
+
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Keys Processing: " + readyKeys.size());
+ }
+ // Walk through the ready keys collection.
+ while (i.hasNext()) {
+ SelectionKey sk = i.next();
+ i.remove();
+
+ if (!sk.isValid()) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Selection Key is invalid: " + sk.toString());
+ }
+ Link link = (Link)sk.attachment();
+ if (link != null) {
+ link.terminated();
+ } else {
+ closeConnection(sk);
+ }
+ } else if (sk.isReadable()) {
+ read(sk);
+ } else if (sk.isWritable()) {
+ write(sk);
+ } else if (sk.isAcceptable()) {
+ accept(sk);
+ } else if (sk.isConnectable()) {
+ connect(sk);
+ }
+ }
+
+ s_logger.trace("Keys Done Processing.");
+
+ processTodos();
+ } catch (Throwable e) {
+ s_logger.warn("Caught an exception but continuing on.", e);
+ }
+ }
+ synchronized (_thread) {
+ _isStartup = false;
+ }
+ }
+
+ abstract void init() throws IOException;
+
+ abstract void registerLink(InetSocketAddress saddr, Link link);
+
+ abstract void unregisterLink(InetSocketAddress saddr);
+
+ protected void accept(SelectionKey key) throws IOException {
+ ServerSocketChannel serverSocketChannel = (ServerSocketChannel)key.channel();
+
+ SocketChannel socketChannel = serverSocketChannel.accept();
+ Socket socket = socketChannel.socket();
+ socket.setKeepAlive(true);
+
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Connection accepted for " + socket);
+ }
+
+ // Begin SSL handshake in BLOCKING mode
+ socketChannel.configureBlocking(true);
+
+ SSLEngine sslEngine = null;
+ try {
+ SSLContext sslContext = Link.initSSLContext(false);
+ sslEngine = sslContext.createSSLEngine();
+ sslEngine.setUseClientMode(false);
+ sslEngine.setNeedClientAuth(false);
+ sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols()));
+
+ Link.doHandshake(socketChannel, sslEngine, false);
+
+ } catch (Exception e) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Socket " + socket + " closed on read. Probably -1 returned: " + e.getMessage());
+ }
+ closeAutoCloseable(socketChannel, "accepting socketChannel");
+ closeAutoCloseable(socket, "opened socket");
+ return;
+ }
+
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("SSL: Handshake done");
+ }
+ socketChannel.configureBlocking(false);
+ InetSocketAddress saddr = (InetSocketAddress)socket.getRemoteSocketAddress();
+ Link link = new Link(saddr, this);
+ link.setSSLEngine(sslEngine);
+ link.setKey(socketChannel.register(key.selector(), SelectionKey.OP_READ, link));
+ Task task = _factory.create(Task.Type.CONNECT, link, null);
+ registerLink(saddr, link);
+ _executor.execute(task);
+ }
+
+ protected void terminate(SelectionKey key) {
+ Link link = (Link)key.attachment();
+ closeConnection(key);
+ if (link != null) {
+ link.terminated();
+ Task task = _factory.create(Task.Type.DISCONNECT, link, null);
+ unregisterLink(link.getSocketAddress());
+ _executor.execute(task);
+ }
+ }
+
+ protected void read(SelectionKey key) throws IOException {
+ Link link = (Link)key.attachment();
+ try {
+ SocketChannel socketChannel = (SocketChannel)key.channel();
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Reading from: " + socketChannel.socket().toString());
+ }
+ byte[] data = link.read(socketChannel);
+ if (data == null) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Packet is incomplete. Waiting for more.");
+ }
+ return;
+ }
+ Task task = _factory.create(Task.Type.DATA, link, data);
+ _executor.execute(task);
+ } catch (Exception e) {
+ logDebug(e, key, 1);
+ terminate(key);
+ }
+ }
+
+ protected void logTrace(Exception e, SelectionKey key, int loc) {
+ if (s_logger.isTraceEnabled()) {
+ Socket socket = null;
+ if (key != null) {
+ SocketChannel ch = (SocketChannel)key.channel();
+ if (ch != null) {
+ socket = ch.socket();
+ }
+ }
+
+ s_logger.trace("Location " + loc + ": Socket " + socket + " closed on read. Probably -1 returned.");
+ }
+ }
+
+ protected void logDebug(Exception e, SelectionKey key, int loc) {
+ if (s_logger.isDebugEnabled()) {
+ Socket socket = null;
+ if (key != null) {
+ SocketChannel ch = (SocketChannel)key.channel();
+ if (ch != null) {
+ socket = ch.socket();
+ }
+ }
+
+ s_logger.debug("Location " + loc + ": Socket " + socket + " closed on read. Probably -1 returned: " + e.getMessage());
+ }
+ }
+
+ protected void processTodos() {
+ List<ChangeRequest> todos;
+ if (_todos.size() == 0) {
+ return; // Nothing to do.
+ }
+
+ synchronized (this) {
+ todos = _todos;
+ _todos = new ArrayList<ChangeRequest>();
+ }
+
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Todos Processing: " + todos.size());
+ }
+ SelectionKey key;
+ for (ChangeRequest todo : todos) {
+ switch (todo.type) {
+ case ChangeRequest.CHANGEOPS:
+ try {
+ key = (SelectionKey)todo.key;
+ if (key != null && key.isValid()) {
+ if (todo.att != null) {
+ key.attach(todo.att);
+ Link link = (Link)todo.att;
+ link.setKey(key);
+ }
+ key.interestOps(todo.ops);
+ }
+ } catch (CancelledKeyException e) {
+ s_logger.debug("key has been cancelled");
+ }
+ break;
+ case ChangeRequest.REGISTER:
+ try {
+ key = ((SocketChannel)(todo.key)).register(_selector, todo.ops, todo.att);
+ if (todo.att != null) {
+ Link link = (Link)todo.att;
+ link.setKey(key);
+ }
+ } catch (ClosedChannelException e) {
+ s_logger.warn("Couldn't register socket: " + todo.key);
+ try {
+ ((SocketChannel)(todo.key)).close();
+ } catch (IOException ignore) {
+ s_logger.info("[ignored] socket channel");
+ } finally {
+ Link link = (Link)todo.att;
+ link.terminated();
+ }
+ }
+ break;
+ case ChangeRequest.CLOSE:
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Trying to close " + todo.key);
+ }
+ key = (SelectionKey)todo.key;
+ closeConnection(key);
+ if (key != null) {
+ Link link = (Link)key.attachment();
+ if (link != null) {
+ link.terminated();
+ }
+ }
+ break;
+ default:
+ s_logger.warn("Shouldn't be here");
+ throw new RuntimeException("Shouldn't be here");
+ }
+ }
+ s_logger.trace("Todos Done processing");
+ }
+
+ protected void connect(SelectionKey key) throws IOException {
+ SocketChannel socketChannel = (SocketChannel)key.channel();
+
+ try {
+ socketChannel.finishConnect();
+ key.interestOps(SelectionKey.OP_READ);
+ Socket socket = socketChannel.socket();
+ if (!socket.getKeepAlive()) {
+ socket.setKeepAlive(true);
+ }
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Connected to " + socket);
+ }
+ Link link = new Link((InetSocketAddress)socket.getRemoteSocketAddress(), this);
+ link.setKey(key);
+ key.attach(link);
+ Task task = _factory.create(Task.Type.CONNECT, link, null);
+ _executor.execute(task);
+ } catch (IOException e) {
+ logTrace(e, key, 2);
+ terminate(key);
+ }
+ }
+
+ protected void scheduleTask(Task task) {
+ _executor.execute(task);
+ }
+
+ protected void write(SelectionKey key) throws IOException {
+ Link link = (Link)key.attachment();
+ try {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Writing to " + link.getSocketAddress().toString());
+ }
+ boolean close = link.write((SocketChannel)key.channel());
+ if (close) {
+ closeConnection(key);
+ link.terminated();
+ } else {
+ key.interestOps(SelectionKey.OP_READ);
+ }
+ } catch (Exception e) {
+ logDebug(e, key, 3);
+ terminate(key);
+ }
+ }
+
+ protected void closeConnection(SelectionKey key) {
+ if (key != null) {
+ SocketChannel channel = (SocketChannel)key.channel();
+ key.cancel();
+ try {
+ if (channel != null) {
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Closing socket " + channel.socket());
+ }
+ channel.close();
+ }
+ } catch (IOException ignore) {
+ s_logger.info("[ignored] channel");
+ }
+ }
+ }
+
+ public void register(int ops, SocketChannel key, Object att) {
+ ChangeRequest todo = new ChangeRequest(key, ChangeRequest.REGISTER, ops, att);
+ synchronized (this) {
+ _todos.add(todo);
+ }
+ _selector.wakeup();
+ }
+
+ public void change(int ops, SelectionKey key, Object att) {
+ ChangeRequest todo = new ChangeRequest(key, ChangeRequest.CHANGEOPS, ops, att);
+ synchronized (this) {
+ _todos.add(todo);
+ }
+ _selector.wakeup();
+ }
+
+ public void close(SelectionKey key) {
+ ChangeRequest todo = new ChangeRequest(key, ChangeRequest.CLOSE, 0, null);
+ synchronized (this) {
+ _todos.add(todo);
+ }
+ _selector.wakeup();
+ }
+
+ /* Release the resource used by the instance */
+ public void cleanUp() throws IOException {
+ if (_selector != null) {
+ _selector.close();
+ }
+ }
+
+ public class ChangeRequest {
+ public static final int REGISTER = 1;
+ public static final int CHANGEOPS = 2;
+ public static final int CLOSE = 3;
+
+ public Object key;
+ public int type;
+ public int ops;
+ public Object att;
+
+ public ChangeRequest(Object key, int type, int ops, Object att) {
+ this.key = key;
+ this.type = type;
+ this.ops = ops;
+ this.att = att;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/NioServer.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/NioServer.java b/utils/src/main/java/com/cloud/utils/nio/NioServer.java
new file mode 100644
index 0000000..98a4a51
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/NioServer.java
@@ -0,0 +1,97 @@
+//
+// 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 com.cloud.utils.nio;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.WeakHashMap;
+
+import org.apache.log4j.Logger;
+
+public class NioServer extends NioConnection {
+ private final static Logger s_logger = Logger.getLogger(NioServer.class);
+
+ protected InetSocketAddress _localAddr;
+ private ServerSocketChannel _serverSocket;
+
+ protected WeakHashMap<InetSocketAddress, Link> _links;
+
+ public NioServer(String name, int port, int workers, HandlerFactory factory) {
+ super(name, port, workers, factory);
+ _localAddr = null;
+ _links = new WeakHashMap<InetSocketAddress, Link>(1024);
+ }
+
+ @Override
+ protected void init() throws IOException {
+ _selector = SelectorProvider.provider().openSelector();
+
+ _serverSocket = ServerSocketChannel.open();
+ _serverSocket.configureBlocking(false);
+
+ _localAddr = new InetSocketAddress(_port);
+ _serverSocket.socket().bind(_localAddr);
+
+ _serverSocket.register(_selector, SelectionKey.OP_ACCEPT, null);
+
+ s_logger.info("NioConnection started and listening on " + _localAddr.toString());
+ }
+
+ @Override
+ public void cleanUp() throws IOException {
+ super.cleanUp();
+ if (_serverSocket != null) {
+ _serverSocket.close();
+ }
+ s_logger.info("NioConnection stopped on " + _localAddr.toString());
+ }
+
+ @Override
+ protected void registerLink(InetSocketAddress addr, Link link) {
+ _links.put(addr, link);
+ }
+
+ @Override
+ protected void unregisterLink(InetSocketAddress saddr) {
+ _links.remove(saddr);
+ }
+
+ /**
+ * Sends the data to the address specified. If address is not already
+ * connected, this does nothing and returns null. If address is already
+ * connected, then it returns the attached object so the caller can
+ * prepare for any responses.
+ * @param saddr
+ * @param data
+ * @return null if not sent. attach object in link if sent.
+ */
+ public Object send(InetSocketAddress saddr, byte[] data) throws ClosedChannelException {
+ Link link = _links.get(saddr);
+ if (link == null) {
+ return null;
+ }
+ link.send(data);
+ return link.attachment();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/Task.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/Task.java b/utils/src/main/java/com/cloud/utils/nio/Task.java
new file mode 100644
index 0000000..c77c703
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/Task.java
@@ -0,0 +1,89 @@
+//
+// 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 com.cloud.utils.nio;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Task represents one todo item for the AgentManager or the AgentManager
+ *
+ */
+public abstract class Task implements Runnable {
+ private static final Logger s_logger = Logger.getLogger(Task.class);
+
+ public enum Type {
+ CONNECT, // Process a new connection.
+ DISCONNECT, // Process an existing connection disconnecting.
+ DATA, // data incoming.
+ CONNECT_FAILED, // Connection failed.
+ OTHER // Allows other tasks to be defined by the caller.
+ };
+
+ Object _data;
+ Type _type;
+ Link _link;
+
+ public Task(Type type, Link link, byte[] data) {
+ _data = data;
+ _type = type;
+ _link = link;
+ }
+
+ public Task(Type type, Link link, Object data) {
+ _data = data;
+ _type = type;
+ _link = link;
+ }
+
+ protected Task() {
+ }
+
+ public Type getType() {
+ return _type;
+ }
+
+ public Link getLink() {
+ return _link;
+ }
+
+ public byte[] getData() {
+ return (byte[])_data;
+ }
+
+ public Object get() {
+ return _data;
+ }
+
+ @Override
+ public String toString() {
+ return _type.toString();
+ }
+
+ abstract protected void doTask(Task task) throws Exception;
+
+ @Override
+ public final void run() {
+ try {
+ doTask(this);
+ } catch (Throwable e) {
+ s_logger.warn("Caught the following exception but pushing on", e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/TrustAllManager.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/TrustAllManager.java b/utils/src/main/java/com/cloud/utils/nio/TrustAllManager.java
new file mode 100644
index 0000000..5dffd62
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/TrustAllManager.java
@@ -0,0 +1,45 @@
+//
+// 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 com.cloud.utils.nio;
+
+public class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
+ @Override
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+
+ public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
+ return true;
+ }
+
+ public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
+ return true;
+ }
+
+ @Override
+ public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
+ return;
+ }
+
+ @Override
+ public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
+ return;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java b/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
new file mode 100644
index 0000000..bf001cd
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
@@ -0,0 +1,66 @@
+//
+// 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 com.cloud.utils.rest;
+
+import java.io.IOException;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethodBase;
+
+/**
+ * Base 64 encoded authorization strategy. This implementation as opposed to
+ * {@link RESTValidationStrategy} doesn't do a login after auth error, but instead
+ * includes the encoded credentials in each request, instead of a cookie.
+ */
+public class BasicEncodedRESTValidationStrategy extends RESTValidationStrategy {
+
+ public BasicEncodedRESTValidationStrategy(final String host, final String adminuser, final String adminpass) {
+ super();
+ this.host = host;
+ user = adminuser;
+ password = adminpass;
+ }
+
+ public BasicEncodedRESTValidationStrategy() {
+ }
+
+ @Override
+ public void executeMethod(final HttpMethodBase method, final HttpClient client,
+ final String protocol)
+ throws CloudstackRESTException, HttpException, IOException {
+ if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
+ throw new CloudstackRESTException("Hostname/credentials are null or empty");
+ }
+
+ final String encodedCredentials = encodeCredentials();
+ method.setRequestHeader("Authorization", "Basic " + encodedCredentials);
+ client.executeMethod(method);
+ }
+
+ private String encodeCredentials() {
+ final String authString = user + ":" + password;
+ final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
+ final String authStringEnc = new String(authEncBytes);
+ return authStringEnc;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java b/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
new file mode 100644
index 0000000..5985fa0
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
@@ -0,0 +1,39 @@
+//
+// 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 com.cloud.utils.rest;
+
+public class CloudstackRESTException extends Exception {
+
+ public CloudstackRESTException() {
+ }
+
+ public CloudstackRESTException(final String message) {
+ super(message);
+ }
+
+ public CloudstackRESTException(final Throwable cause) {
+ super(cause);
+ }
+
+ public CloudstackRESTException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
new file mode 100644
index 0000000..6ededcb
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
@@ -0,0 +1,395 @@
+//
+// 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 com.cloud.utils.rest;
+
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.reflect.TypeToken;
+import org.apache.cloudstack.utils.security.SSLUtils;
+import org.apache.cloudstack.utils.security.SecureSSLSocketFactory;
+import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpMethodBase;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.cookie.CookiePolicy;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.Protocol;
+import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
+import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+import org.apache.log4j.Logger;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Type;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.Socket;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * This abstraction encapsulates client side code for REST service communication. It encapsulates
+ * access in a delegate validation strategy. There may different implementations extending
+ * {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
+ *
+ * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide
+ * in the constructor a list of classes and a list of deserializers for these classes. These should
+ * be a correlated so that Nth deserializer is correctly mapped to Nth class.
+ */
+public class RESTServiceConnector {
+ private static final String HTTPS = "https";
+ protected static final String GET_METHOD_TYPE = "get";
+ protected static final String DELETE_METHOD_TYPE = "delete";
+ protected static final String PUT_METHOD_TYPE = "put";
+ protected static final String POST_METHOD_TYPE = "post";
+ private static final String TEXT_HTML_CONTENT_TYPE = "text/html";
+ private static final String JSON_CONTENT_TYPE = "application/json";
+ private static final String CONTENT_TYPE = "Content-Type";
+ private static final int BODY_RESP_MAX_LEN = 1024;
+ private static final int HTTPS_PORT = 443;
+
+ private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class);
+
+ protected final static String protocol = HTTPS;
+
+ private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
+
+ protected RESTValidationStrategy validation;
+
+ private final HttpClient client;
+
+ private final Gson gson;
+
+
+ /**
+ * Getter that may be needed only for test purpose
+ *
+ * @return
+ */
+ public Gson getGson() {
+ return gson;
+ }
+
+ public RESTServiceConnector(final RESTValidationStrategy validationStrategy) {
+ this(validationStrategy, null, null);
+ }
+
+ public RESTServiceConnector(final RESTValidationStrategy validationStrategy, final List<Class<?>> classList, final List<JsonDeserializer<?>> deserializerList) {
+ validation = validationStrategy;
+ client = createHttpClient();
+ client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
+
+ try {
+ // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
+ Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT));
+ } catch (final IOException e) {
+ s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
+ }
+
+ final GsonBuilder gsonBuilder = new GsonBuilder();
+ if(classList != null && deserializerList != null) {
+ for(int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
+ gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
+ }
+ }
+ gson = gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
+ }
+
+ public HttpClient createHttpClient() {
+ return new HttpClient(s_httpClientManager);
+ }
+
+ public HttpMethod createMethod(final String type, final String uri) throws CloudstackRESTException {
+ String url;
+ try {
+ url = new URL(protocol, validation.getHost(), uri).toString();
+ } catch (final MalformedURLException e) {
+ s_logger.error("Unable to build REST Service URL", e);
+ throw new CloudstackRESTException("Unable to build Nicira API URL", e);
+ }
+
+ if (POST_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new PostMethod(url);
+ } else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new GetMethod(url);
+ } else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new DeleteMethod(url);
+ } else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new PutMethod(url);
+ } else {
+ throw new CloudstackRESTException("Requesting unknown method type");
+ }
+ }
+
+ public void setControllerAddress(final String address) {
+ validation.setHost(address);
+ }
+
+ public void setAdminCredentials(final String username, final String password) {
+ validation.setUser(username);
+ validation.setPassword(password);
+ }
+
+ public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
+
+ final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri);
+ pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+ try {
+ pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
+ } catch (final UnsupportedEncodingException e) {
+ throw new CloudstackRESTException("Failed to encode json request body", e);
+ }
+
+ executeMethod(pm);
+
+ if (pm.getStatusCode() != HttpStatus.SC_OK) {
+ final String errorMessage = responseToErrorMessage(pm);
+ pm.releaseConnection();
+ s_logger.error("Failed to update object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to update object : " + errorMessage);
+ }
+ pm.releaseConnection();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters)
+ throws CloudstackRESTException {
+
+ final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri);
+ pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+ try {
+ pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
+ } catch (final UnsupportedEncodingException e) {
+ throw new CloudstackRESTException("Failed to encode json request body", e);
+ }
+
+ executeMethod(pm);
+
+ if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
+ final String errorMessage = responseToErrorMessage(pm);
+ pm.releaseConnection();
+ s_logger.error("Failed to create object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to create object : " + errorMessage);
+ }
+
+ T result;
+ try {
+ result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
+ } catch (final IOException e) {
+ throw new CloudstackRESTException("Failed to decode json response body", e);
+ } finally {
+ pm.releaseConnection();
+ }
+
+ return result;
+ }
+
+ public void executeDeleteObject(final String uri) throws CloudstackRESTException {
+ final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri);
+ dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+
+ executeMethod(dm);
+
+ if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
+ final String errorMessage = responseToErrorMessage(dm);
+ dm.releaseConnection();
+ s_logger.error("Failed to delete object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to delete object : " + errorMessage);
+ }
+ dm.releaseConnection();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
+ final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri);
+ gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+ if (parameters != null && !parameters.isEmpty()) {
+ final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
+ for (final Entry<String, String> e : parameters.entrySet()) {
+ nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
+ }
+ gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
+ }
+
+ executeMethod(gm);
+
+ if (gm.getStatusCode() != HttpStatus.SC_OK) {
+ final String errorMessage = responseToErrorMessage(gm);
+ gm.releaseConnection();
+ s_logger.error("Failed to retrieve object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
+ }
+
+ T returnValue;
+ try {
+ returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
+ } catch (final IOException e) {
+ s_logger.error("IOException while retrieving response body", e);
+ throw new CloudstackRESTException(e);
+ } finally {
+ gm.releaseConnection();
+ }
+ return returnValue;
+ }
+
+ public void executeMethod(final HttpMethodBase method) throws CloudstackRESTException {
+ try {
+ validation.executeMethod(method, client, protocol);
+ } catch (final HttpException e) {
+ s_logger.error("HttpException caught while trying to connect to the REST Service", e);
+ method.releaseConnection();
+ throw new CloudstackRESTException("API call to REST Service Failed", e);
+ } catch (final IOException e) {
+ s_logger.error("IOException caught while trying to connect to the REST Service", e);
+ method.releaseConnection();
+ throw new CloudstackRESTException("API call to Nicira REST Service Failed", e);
+ }
+ }
+
+ private String responseToErrorMessage(final HttpMethodBase method) {
+ assert method.isRequestSent() : "no use getting an error message unless the request is sent";
+
+ if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
+ // The error message is the response content
+ // Safety margin of 1024 characters, anything longer is probably useless
+ // and will clutter the logs
+ try {
+ return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
+ } catch (final IOException e) {
+ s_logger.debug("Error while loading response body", e);
+ }
+ }
+
+ // The default
+ return method.getStatusText();
+ }
+
+ /* Some controllers use a self-signed certificate. The
+ * TrustingProtocolSocketFactory will accept any provided
+ * certificate when making an SSL connection to the SDN
+ * Manager
+ */
+ private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
+
+ private SSLSocketFactory ssf;
+
+ public TrustingProtocolSocketFactory() throws IOException {
+ // Create a trust manager that does not validate certificate chains
+ final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+
+ @Override
+ public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
+ // Trust always
+ }
+
+ @Override
+ public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
+ // Trust always
+ }
+ }};
+
+ try {
+ // Install the all-trusting trust manager
+ final SSLContext sc = SSLUtils.getSSLContext();
+ sc.init(null, trustAllCerts, new java.security.SecureRandom());
+ ssf = new SecureSSLSocketFactory(sc);
+ } catch (final KeyManagementException e) {
+ throw new IOException(e);
+ } catch (final NoSuchAlgorithmException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public Socket createSocket(final String host, final int port) throws IOException {
+ SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
+ socket.setEnabledProtocols(SSLUtils.getSupportedProtocols(socket.getEnabledProtocols()));
+ return socket;
+ }
+
+ @Override
+ public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
+ Socket socket = ssf.createSocket(address, port, localAddress, localPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ @Override
+ public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
+ Socket s = ssf.createSocket(socket, host, port, autoClose);
+ if (s instanceof SSLSocket) {
+ ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
+ }
+ return s;
+ }
+
+ @Override
+ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
+ throws IOException, UnknownHostException, ConnectTimeoutException {
+ final int timeout = params.getConnectionTimeout();
+ if (timeout == 0) {
+ Socket socket = createSocket(host, port, localAddress, localPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ } else {
+ final Socket s = ssf.createSocket();
+ if (s instanceof SSLSocket) {
+ ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
+ }
+ s.bind(new InetSocketAddress(localAddress, localPort));
+ s.connect(new InetSocketAddress(host, port), timeout);
+ return s;
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
new file mode 100644
index 0000000..77ac8d0
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
@@ -0,0 +1,165 @@
+//
+// 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 com.cloud.utils.rest;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethodBase;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.log4j.Logger;
+
+/**
+ * Basic authentication strategy. This strategy needs user and password for authentication.
+ *
+ * A login URL is needed which will be used for login and getting the cookie to be
+ * used in next requests. If an executeMethod request fails due to authorization it will try
+ * to login, get the cookie and repeat the attempt to execute the method.
+ */
+public class RESTValidationStrategy {
+
+ private static final Logger s_logger = Logger.getLogger(RESTValidationStrategy.class);
+
+ protected String host;
+ protected String user;
+ protected String password;
+ protected String serverVersion;
+ protected String loginUrl;
+
+ public RESTValidationStrategy(final String host, final String user, final String password,
+ final String serverVersion, final String loginUrl) {
+ super();
+ this.host = host;
+ this.user = user;
+ this.password = password;
+ this.serverVersion = serverVersion;
+ this.loginUrl = loginUrl;
+ }
+
+ public RESTValidationStrategy(final String loginUrl) {
+ this.loginUrl = loginUrl;
+ }
+
+ public RESTValidationStrategy() {
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(final String user) {
+ this.user = user;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(final String password) {
+ this.password = password;
+ }
+
+ public String getLoginUrl() {
+ return loginUrl;
+ }
+
+ public void setLoginUrl(final String loginUrl) {
+ this.loginUrl = loginUrl;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(final String host) {
+ this.host = host;
+ }
+
+ public void executeMethod(final HttpMethodBase method, final HttpClient client,
+ final String protocol)
+ throws CloudstackRESTException, HttpException, IOException {
+ if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
+ throw new CloudstackRESTException("Hostname/credentials are null or empty");
+ }
+
+ client.executeMethod(method);
+ if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
+ method.releaseConnection();
+ // login and try again
+ login(protocol, client);
+ client.executeMethod(method);
+ }
+ }
+
+ /**
+ * Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable.
+ * <p>
+ * The method returns false if the login failed or the connection could not be made.
+ *
+ */
+ protected void login(final String protocol,
+ final HttpClient client)
+ throws CloudstackRESTException {
+ String url;
+
+ if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
+ throw new CloudstackRESTException("Hostname/credentials are null or empty");
+ }
+
+ try {
+ url = new URL(protocol, host, loginUrl).toString();
+ } catch (final MalformedURLException e) {
+ s_logger.error("Unable to build Nicira API URL", e);
+ throw new CloudstackRESTException("Unable to build Nicira API URL", e);
+ }
+
+ final PostMethod pm = new PostMethod(url);
+ pm.addParameter("username", user);
+ pm.addParameter("password", password);
+
+ try {
+ client.executeMethod(pm);
+ } catch (final HttpException e) {
+ throw new CloudstackRESTException("REST Service API login failed ", e);
+ } catch (final IOException e) {
+ throw new CloudstackRESTException("REST Service API login failed ", e);
+ } finally {
+ pm.releaseConnection();
+ }
+
+ if (pm.getStatusCode() != HttpStatus.SC_OK) {
+ s_logger.error("REST Service API login failed : " + pm.getStatusText());
+ throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText());
+ }
+
+ // Extract the version for later use
+ if (pm.getResponseHeader("Server") != null) {
+ serverVersion = pm.getResponseHeader("Server").getValue();
+ s_logger.debug("Server reports version " + serverVersion);
+ }
+
+ // Success; the cookie required for login is kept in _client
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/script/OutputInterpreter.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/script/OutputInterpreter.java b/utils/src/main/java/com/cloud/utils/script/OutputInterpreter.java
new file mode 100644
index 0000000..654f87e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/script/OutputInterpreter.java
@@ -0,0 +1,141 @@
+//
+// 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 com.cloud.utils.script;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+
+import org.apache.log4j.Logger;
+
+/**
+ */
+public abstract class OutputInterpreter {
+ public boolean drain() {
+ return false;
+ }
+
+ public String processError(BufferedReader reader) throws IOException {
+ StringBuilder buff = new StringBuilder();
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ buff.append(line);
+ }
+ return buff.toString();
+ }
+
+ public abstract String interpret(BufferedReader reader) throws IOException;
+
+ public static final OutputInterpreter NoOutputParser = new OutputInterpreter() {
+ @Override
+ public String interpret(BufferedReader reader) throws IOException {
+ return null;
+ }
+ };
+
+ public static class TimedOutLogger extends OutputInterpreter {
+ private static final Logger s_logger = Logger.getLogger(TimedOutLogger.class);
+ Process _process;
+
+ public TimedOutLogger(Process process) {
+ _process = process;
+ }
+
+ @Override
+ public boolean drain() {
+ return true;
+ }
+
+ @Override
+ public String interpret(BufferedReader reader) throws IOException {
+ StringBuilder buff = new StringBuilder();
+
+ while (reader.ready()) {
+ buff.append(reader.readLine());
+ }
+
+ _process.destroy();
+
+ try {
+ while (reader.ready()) {
+ buff.append(reader.readLine());
+ }
+ } catch (IOException e) {
+ s_logger.info("[ignored] can not append line to buffer",e);
+ }
+
+ return buff.toString();
+ }
+ }
+
+ public static class OutputLogger extends OutputInterpreter {
+ Logger _logger;
+
+ public OutputLogger(Logger logger) {
+ _logger = logger;
+ }
+
+ @Override
+ public String interpret(BufferedReader reader) throws IOException {
+ StringBuilder builder = new StringBuilder();
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ builder.append(line).append("\n");
+ }
+ if (builder.length() > 0) {
+ _logger.debug(builder.toString());
+ }
+ return null;
+ }
+ }
+
+ public static class OneLineParser extends OutputInterpreter {
+ String line = null;
+
+ @Override
+ public String interpret(BufferedReader reader) throws IOException {
+ line = reader.readLine();
+ return null;
+ }
+
+ public String getLine() {
+ return line;
+ }
+ };
+
+ public static class AllLinesParser extends OutputInterpreter {
+ String allLines = null;
+
+ @Override
+ public String interpret(BufferedReader reader) throws IOException {
+ StringBuilder builder = new StringBuilder();
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ builder.append(line).append("\n");
+ }
+ allLines = builder.toString();
+ return null;
+ }
+
+ public String getLines() {
+ return allLines;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/script/Script.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/script/Script.java b/utils/src/main/java/com/cloud/utils/script/Script.java
new file mode 100644
index 0000000..487c62c
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/script/Script.java
@@ -0,0 +1,502 @@
+//
+// 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 com.cloud.utils.script;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.PropertiesUtil;
+import com.cloud.utils.concurrency.NamedThreadFactory;
+import com.cloud.utils.script.OutputInterpreter.TimedOutLogger;
+
+public class Script implements Callable<String> {
+ private static final Logger s_logger = Logger.getLogger(Script.class);
+
+ private final Logger _logger;
+
+ public static final String ERR_EXECUTE = "execute.error";
+ public static final String ERR_TIMEOUT = "timeout";
+ private int _defaultTimeout = 3600 * 1000; /* 1 hour */
+ private volatile boolean _isTimeOut = false;
+
+ private boolean _passwordCommand = false;
+
+ private static final ScheduledExecutorService s_executors = Executors.newScheduledThreadPool(10, new NamedThreadFactory("Script"));
+
+ String _workDir;
+ ArrayList<String> _command;
+ long _timeout;
+ Process _process;
+ Thread _thread;
+
+ public int getExitValue() {
+ return _process.exitValue();
+ }
+
+ public Script(String command, long timeout, Logger logger) {
+ _command = new ArrayList<String>();
+ _command.add(command);
+ _timeout = timeout;
+ if (_timeout == 0) {
+ /* always using default timeout 1 hour to avoid thread hang */
+ _timeout = _defaultTimeout;
+ }
+ _process = null;
+ _logger = logger != null ? logger : s_logger;
+ }
+
+ public Script(boolean runWithSudo, String command, long timeout, Logger logger) {
+ this(command, timeout, logger);
+ if (runWithSudo) {
+ _command.add(0, "sudo");
+ }
+ }
+
+ public Script(String command, Logger logger) {
+ this(command, 0, logger);
+ }
+
+ public Script(String command) {
+ this(command, 0, s_logger);
+ }
+
+ public Script(String command, long timeout) {
+ this(command, timeout, s_logger);
+ }
+
+ public void add(String... params) {
+ for (String param : params) {
+ _command.add(param);
+ }
+ }
+
+ public void add(String param) {
+ _command.add(param);
+ }
+
+ public Script set(String name, String value) {
+ _command.add(name);
+ _command.add(value);
+ return this;
+ }
+
+ public void setWorkDir(String workDir) {
+ _workDir = workDir;
+ }
+
+ protected String buildCommandLine(String[] command) {
+ StringBuilder builder = new StringBuilder();
+ boolean obscureParam = false;
+ for (int i = 0; i < command.length; i++) {
+ String cmd = command[i];
+ if (obscureParam) {
+ builder.append("******").append(" ");
+ obscureParam = false;
+ } else {
+ builder.append(command[i]).append(" ");
+ }
+
+ if ("-y".equals(cmd) || "-z".equals(cmd)) {
+ obscureParam = true;
+ _passwordCommand = true;
+ }
+ }
+ return builder.toString();
+ }
+
+ protected String buildCommandLine(List<String> command) {
+ StringBuilder builder = new StringBuilder();
+ boolean obscureParam = false;
+ for (String cmd : command) {
+ if (obscureParam) {
+ builder.append("******").append(" ");
+ obscureParam = false;
+ } else {
+ builder.append(cmd).append(" ");
+ }
+
+ if ("-y".equals(cmd) || "-z".equals(cmd)) {
+ obscureParam = true;
+ _passwordCommand = true;
+ }
+ }
+ return builder.toString();
+ }
+
+ public String execute() {
+ return execute(new OutputInterpreter.OutputLogger(_logger));
+ }
+
+ @Override
+ public String toString() {
+ String[] command = _command.toArray(new String[_command.size()]);
+ return buildCommandLine(command);
+ }
+
+ static String stackTraceAsString(Throwable throwable) {
+ //TODO: a StringWriter is bit to heavy weight
+ try(StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out);) {
+ throwable.printStackTrace(writer);
+ return out.toString();
+ } catch (IOException e) {
+ return "";
+ }
+ }
+
+ public String execute(OutputInterpreter interpreter) {
+ String[] command = _command.toArray(new String[_command.size()]);
+
+ if (_logger.isDebugEnabled()) {
+ _logger.debug("Executing: " + buildCommandLine(command));
+ }
+
+ try {
+ ProcessBuilder pb = new ProcessBuilder(command);
+ pb.redirectErrorStream(true);
+ if (_workDir != null)
+ pb.directory(new File(_workDir));
+
+ _process = pb.start();
+ if (_process == null) {
+ _logger.warn("Unable to execute: " + buildCommandLine(command));
+ return "Unable to execute the command: " + command[0];
+ }
+
+ BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));
+
+ _thread = Thread.currentThread();
+ ScheduledFuture<String> future = null;
+ if (_timeout > 0) {
+ future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
+ }
+
+ Task task = null;
+ if (interpreter != null && interpreter.drain()) {
+ task = new Task(interpreter, ir);
+ s_executors.execute(task);
+ }
+
+ while (true) {
+ try {
+ if (_process.waitFor() == 0) {
+ _logger.debug("Execution is successful.");
+ if (interpreter != null) {
+ return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
+ } else {
+ // null return exitValue apparently
+ return String.valueOf(_process.exitValue());
+ }
+ } else {
+ break;
+ }
+ } catch (InterruptedException e) {
+ if (!_isTimeOut) {
+ /*
+ * This is not timeout, we are interrupted by others,
+ * continue
+ */
+ _logger.debug("We are interrupted but it's not a timeout, just continue");
+ continue;
+ }
+
+ TimedOutLogger log = new TimedOutLogger(_process);
+ Task timedoutTask = new Task(log, ir);
+
+ timedoutTask.run();
+ if (!_passwordCommand) {
+ _logger.warn("Timed out: " + buildCommandLine(command) + ". Output is: " + timedoutTask.getResult());
+ } else {
+ _logger.warn("Timed out: " + buildCommandLine(command));
+ }
+
+ return ERR_TIMEOUT;
+ } finally {
+ if (future != null) {
+ future.cancel(false);
+ }
+ Thread.interrupted();
+ }
+ }
+
+ _logger.debug("Exit value is " + _process.exitValue());
+
+ BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);
+
+ String error;
+ if (interpreter != null) {
+ error = interpreter.processError(reader);
+ } else {
+ error = String.valueOf(_process.exitValue());
+ }
+
+ if (_logger.isDebugEnabled()) {
+ _logger.debug(error);
+ }
+ return error;
+ } catch (SecurityException ex) {
+ _logger.warn("Security Exception....not running as root?", ex);
+ return stackTraceAsString(ex);
+ } catch (Exception ex) {
+ _logger.warn("Exception: " + buildCommandLine(command), ex);
+ return stackTraceAsString(ex);
+ } finally {
+ if (_process != null) {
+ IOUtils.closeQuietly(_process.getErrorStream());
+ IOUtils.closeQuietly(_process.getOutputStream());
+ IOUtils.closeQuietly(_process.getInputStream());
+ _process.destroy();
+ }
+ }
+ }
+
+ @Override
+ public String call() {
+ try {
+ _logger.trace("Checking exit value of process");
+ _process.exitValue();
+ _logger.trace("Script ran within the alloted time");
+ } catch (IllegalThreadStateException e) {
+ _logger.warn("Interrupting script.");
+ _isTimeOut = true;
+ _thread.interrupt();
+ }
+ return null;
+ }
+
+ public static class Task implements Runnable {
+ OutputInterpreter interpreter;
+ BufferedReader reader;
+ String result;
+ boolean done;
+
+ public Task(OutputInterpreter interpreter, BufferedReader reader) {
+ this.interpreter = interpreter;
+ this.reader = reader;
+ result = null;
+ }
+
+ @Override
+ public void run() {
+ synchronized(this) {
+ done = false;
+ try {
+ result = interpreter.interpret(reader);
+ } catch (IOException ex) {
+ result = stackTraceAsString(ex);
+ } catch (Exception ex) {
+ result = stackTraceAsString(ex);
+ } finally {
+ done = true;
+ notifyAll();
+ IOUtils.closeQuietly(reader);
+ }
+ }
+ }
+
+ public synchronized String getResult() throws InterruptedException {
+ if (!done) {
+ wait();
+ }
+ return result;
+ }
+ }
+
+ public static String findScript(String path, String script) {
+ s_logger.debug("Looking for " + script + " in the classpath");
+
+ URL url = ClassLoader.getSystemResource(script);
+ s_logger.debug("System resource: " + url);
+ File file = null;
+ if (url != null) {
+ file = new File(url.getFile());
+ s_logger.debug("Absolute path = " + file.getAbsolutePath());
+ return file.getAbsolutePath();
+ }
+
+ if (path == null) {
+ s_logger.warn("No search path specified, unable to look for " + script);
+ return null;
+ }
+ path = path.replace("/", File.separator);
+
+ /**
+ * Look in WEB-INF/classes of the webapp
+ * URI workaround the URL encoding of url.getFile
+ */
+ if (path.endsWith(File.separator)) {
+ url = Script.class.getClassLoader().getResource(path + script);
+ } else {
+ url = Script.class.getClassLoader().getResource(path + File.separator + script);
+ }
+ s_logger.debug("Classpath resource: " + url);
+ if (url != null) {
+ try {
+ file = new File(new URI(url.toString()).getPath());
+ s_logger.debug("Absolute path = " + file.getAbsolutePath());
+ return file.getAbsolutePath();
+ } catch (URISyntaxException e) {
+ s_logger.warn("Unable to convert " + url.toString() + " to a URI");
+ }
+ }
+
+ if (path.endsWith(File.separator)) {
+ path = path.substring(0, path.lastIndexOf(File.separator));
+ }
+
+ if (path.startsWith(File.separator)) {
+ // Path given was absolute so we assume the caller knows what they want.
+ file = new File(path + File.separator + script);
+ return file.exists() ? file.getAbsolutePath() : null;
+ }
+
+ s_logger.debug("Looking for " + script);
+ String search = null;
+ for (int i = 0; i < 3; i++) {
+ if (i == 0) {
+ String cp = Script.class.getResource(Script.class.getSimpleName() + ".class").toExternalForm();
+ int begin = cp.indexOf(File.separator);
+
+ // work around with the inconsistency of java classpath and file separator on Windows 7
+ if (begin < 0)
+ begin = cp.indexOf('/');
+
+ int endBang = cp.lastIndexOf("!");
+ int end = cp.lastIndexOf(File.separator, endBang);
+ if (end < 0)
+ end = cp.lastIndexOf('/', endBang);
+ if (end < 0)
+ cp = cp.substring(begin);
+ else
+ cp = cp.substring(begin, end);
+
+ s_logger.debug("Current binaries reside at " + cp);
+ search = cp;
+ } else if (i == 1) {
+ s_logger.debug("Searching in environment.properties");
+ try {
+ final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
+ if (propsFile == null) {
+ s_logger.debug("environment.properties could not be opened");
+ } else {
+ final Properties props = PropertiesUtil.loadFromFile(propsFile);
+ search = props.getProperty("paths.script");
+ }
+ } catch (IOException e) {
+ s_logger.debug("environment.properties could not be opened");
+ continue;
+ }
+ s_logger.debug("environment.properties says scripts should be in " + search);
+ } else {
+ s_logger.debug("Searching in the current directory");
+ search = ".";
+ }
+
+ search += File.separatorChar + path + File.separator;
+ do {
+ search = search.substring(0, search.lastIndexOf(File.separator));
+ file = new File(search + File.separator + script);
+ s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
+ } while (!file.exists() && search.lastIndexOf(File.separator) != -1);
+
+ if (file.exists()) {
+ return file.getAbsolutePath();
+ }
+
+ }
+
+ search = System.getProperty("paths.script");
+
+ search += File.separatorChar + path + File.separator;
+ do {
+ search = search.substring(0, search.lastIndexOf(File.separator));
+ file = new File(search + File.separator + script);
+ s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
+ } while (!file.exists() && search.lastIndexOf(File.separator) != -1);
+
+ if (file.exists()) {
+ return file.getAbsolutePath();
+ }
+
+ s_logger.warn("Unable to find script " + script);
+ return null;
+ }
+
+ public static String runSimpleBashScript(String command) {
+ return Script.runSimpleBashScript(command, 0);
+ }
+
+ public static String runSimpleBashScript(String command, int timeout) {
+
+ Script s = new Script("/bin/bash", timeout);
+ s.add("-c");
+ s.add(command);
+
+ OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
+ if (s.execute(parser) != null)
+ return null;
+
+ String result = parser.getLine();
+ if (result == null || result.trim().isEmpty())
+ return null;
+ else
+ return result.trim();
+ }
+
+ public static int runSimpleBashScriptForExitValue(String command) {
+ return runSimpleBashScriptForExitValue(command, 0);
+ }
+
+ public static int runSimpleBashScriptForExitValue(String command, int timeout) {
+
+ Script s = new Script("/bin/bash", timeout);
+ s.add("-c");
+ s.add(command);
+
+ String result = s.execute(null);
+ if (result == null || result.trim().isEmpty())
+ return -1;
+ else {
+ try {
+ return Integer.parseInt(result.trim());
+ } catch (NumberFormatException e) {
+ return -1;
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/script/Script2.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/script/Script2.java b/utils/src/main/java/com/cloud/utils/script/Script2.java
new file mode 100644
index 0000000..03c0e0d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/script/Script2.java
@@ -0,0 +1,70 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.script;
+
+import java.util.HashMap;
+
+import org.apache.log4j.Logger;
+
+public class Script2 extends Script {
+ HashMap<String, ParamType> _params = new HashMap<String, ParamType>();
+
+ public static enum ParamType {
+ NORMAL, PASSWORD,
+ }
+
+ public Script2(String command, Logger logger) {
+ this(command, 0, logger);
+ }
+
+ public Script2(String command, long timeout, Logger logger) {
+ super(command, timeout, logger);
+ }
+
+ public void add(String param, ParamType type) {
+ _params.put(param, type);
+ super.add(param);
+ }
+
+ @Override
+ public void add(String param) {
+ add(param, ParamType.NORMAL);
+ }
+
+ private ParamType getType(String cmd) {
+ return _params.get(cmd);
+ }
+
+ @Override
+ protected String buildCommandLine(String[] command) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < command.length; i++) {
+ String cmd = command[i];
+ ParamType type = getType(cmd);
+ if (type == ParamType.PASSWORD) {
+ builder.append("******").append(" ");
+ } else {
+ builder.append(command[i]).append(" ");
+ }
+ }
+
+ return builder.toString();
+ }
+}
[09/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java b/utils/test/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java
deleted file mode 100644
index 0f3f058..0000000
--- a/utils/test/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java
+++ /dev/null
@@ -1,45 +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 com.cloud.utils.crypto;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.Properties;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.cloud.utils.crypt.EncryptionSecretKeyChecker;
-import com.cloud.utils.db.DbProperties;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class EncryptionSecretKeyCheckerTest {
-
- private EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker();
-
- @Test(expected = CloudRuntimeException.class)
- public void testKeyFileDoesNotExists() throws IOException, URISyntaxException {
- Assert.assertNotNull(checker);
- Properties properties = DbProperties.getDbProperties();
- properties.setProperty("db.cloud.encryption.type", "file");
- checker.check(properties);
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/crypto/RSAHelperTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/crypto/RSAHelperTest.java b/utils/test/com/cloud/utils/crypto/RSAHelperTest.java
deleted file mode 100644
index 27d9d50..0000000
--- a/utils/test/com/cloud/utils/crypto/RSAHelperTest.java
+++ /dev/null
@@ -1,54 +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 com.cloud.utils.crypto;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Test;
-
-import com.cloud.utils.crypt.RSAHelper;
-
-public class RSAHelperTest {
- @Test
- public void testEncryptWithRSA() {
- String rsaKey =
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW"
- + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk"
- + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P"
- + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX";
- String encryptedString = RSAHelper.encryptWithSSHPublicKey(rsaKey, "content");
- assertNotNull(encryptedString);
- }
-
- @Test
- public void testEncryptWithDSA() {
- String dssKey =
- "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV"
- + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO"
- + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA"
- + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF"
- + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD"
- + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR"
- + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ==";
- String encryptedString = RSAHelper.encryptWithSSHPublicKey(dssKey, "content");
- assertNull(encryptedString);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java b/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java
deleted file mode 100644
index 3d4dfc9..0000000
--- a/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java
+++ /dev/null
@@ -1,33 +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 com.cloud.utils.encoding;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class UrlEncoderTest {
- @Test
- public void encode() {
- Assert.assertEquals("%2Ftmp%2F", new URLEncoder().encode("/tmp/"));
- Assert.assertEquals("%20", new URLEncoder().encode(" "));
- Assert.assertEquals("%5F", new URLEncoder().encode("_"));
- Assert.assertEquals("%25", new URLEncoder().encode("%"));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/exception/ExceptionUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/exception/ExceptionUtilTest.java b/utils/test/com/cloud/utils/exception/ExceptionUtilTest.java
deleted file mode 100644
index 9e1948e..0000000
--- a/utils/test/com/cloud/utils/exception/ExceptionUtilTest.java
+++ /dev/null
@@ -1,52 +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 com.cloud.utils.exception;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-import org.junit.Test;
-
-public class ExceptionUtilTest {
-
- @Test
- public void test() throws Exception {
- FileNotFoundException fnfe = new FileNotFoundException();
- try {
- ExceptionUtil.rethrow(fnfe, IOException.class);
- fail();
- } catch (IOException e) {
- assertTrue("we won !?!", true);
- }
-
- ExceptionUtil.rethrow(fnfe, ClassNotFoundException.class);
-
- try {
- ExceptionUtil.rethrow(fnfe, FileNotFoundException.class);
- fail();
- } catch (FileNotFoundException e) {
- assertTrue("we won !?!", true);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/net/Ip4AddressTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/Ip4AddressTest.java b/utils/test/com/cloud/utils/net/Ip4AddressTest.java
deleted file mode 100644
index 79ff238..0000000
--- a/utils/test/com/cloud/utils/net/Ip4AddressTest.java
+++ /dev/null
@@ -1,40 +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 com.cloud.utils.net;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.google.common.testing.EqualsTester;
-
-public class Ip4AddressTest {
-
- @Test
- public void testEquals() throws Exception {
- new EqualsTester()
- .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:02"), new Ip4Address(1L, 2L))
- .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:00"), new Ip4Address(1L, 0L), new Ip4Address(1L, 0L), new Ip4Address(1L), new Ip4Address("0.0.0.1"))
- .testEquals();
- }
-
- @Test
- public void testIsSameAddressAs() {
- Assert.assertTrue("1 and one should be considdered the same address", new Ip4Address(1L, 5L).isSameAddressAs("0.0.0.1"));
- Assert.assertFalse("zero and 0L should be considdered the same address but a Long won't be accepted", new Ip4Address("0.0.0.0", "00:00:00:00:00:08").isSameAddressAs(0L));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/net/IpTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/IpTest.java b/utils/test/com/cloud/utils/net/IpTest.java
deleted file mode 100644
index 89608f1..0000000
--- a/utils/test/com/cloud/utils/net/IpTest.java
+++ /dev/null
@@ -1,63 +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 com.cloud.utils.net;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.google.common.testing.EqualsTester;
-
-public class IpTest {
-
- @Test
- public void testUltimate() {
- Ip max = new Ip(2L * Integer.MAX_VALUE +1 );
- assertEquals("Maximal address not created", "255.255.255.255", max.addr());
- }
- @Test
- public void testTurningOfTheCentury() {
- Ip eve = new Ip(Integer.MAX_VALUE);
- assertEquals("Minimal address not created", "127.255.255.255", eve.addr());
- Ip dawn = new Ip(Integer.MAX_VALUE + 1L);
- assertEquals("Minimal address not created", "128.0.0.0", dawn.addr());
- }
- @Test
- public void testStart() {
- Ip min = new Ip(0);
- assertEquals("Minimal address not created", "0.0.0.0", min.addr());
- }
-
- @Test
- public void testEquals() {
- new EqualsTester()
- .addEqualityGroup(new Ip("0.0.0.1"), new Ip(1L))
- .addEqualityGroup(new Ip("0.0.0.0"), new Ip(0L))
- .testEquals();
- }
-
- @Test
- public void testIsSameAddressAs() {
- Assert.assertTrue("1 and one should be considdered the same address", new Ip(1L).isSameAddressAs("0.0.0.1"));
- Assert.assertTrue("zero and 0L should be considdered the same address", new Ip("0.0.0.0").isSameAddressAs(0L));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/net/MacAddressTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/MacAddressTest.java b/utils/test/com/cloud/utils/net/MacAddressTest.java
deleted file mode 100644
index 845a435..0000000
--- a/utils/test/com/cloud/utils/net/MacAddressTest.java
+++ /dev/null
@@ -1,60 +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 com.cloud.utils.net;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class MacAddressTest {
-
- @Test
- public final void testMacAddress() throws Exception {
- MacAddress mac = new MacAddress();
- assertEquals(0L,mac.toLong());
- }
-
- @Test
- public final void testMacAddressLong() throws Exception {
- MacAddress mac = new MacAddress(1L);
- assertEquals(1L,mac.toLong());
- }
-
- @Test
- public final void testMacAddressToLong() throws Exception {
- // TODO this test should fail this address is beyond the acceptable range for macaddresses
- MacAddress mac = new MacAddress(Long.MAX_VALUE);
- assertEquals(Long.MAX_VALUE,mac.toLong());
- System.out.println(mac.toString());
- }
-
- // TODO public final void testToLong() throws Exception {
- // TODO public final void testToByteArray() throws Exception {
- // TODO public final void testToStringString() throws Exception {
- // TODO public final void testToString() throws Exception {
- // TODO public final void testGetMacAddress() throws Exception {
- // TODO public final void testParse() throws Exception {
- // TODO public final void testMain() throws Exception {
- // TODO public final void testParseLong() throws Exception {
- // TODO public final void testParseInt() throws Exception {
- // TODO public final void testParseShort() throws Exception {
- // TODO public final void testParseByte() throws Exception {
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/net/NetUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/NetUtilsTest.java b/utils/test/com/cloud/utils/net/NetUtilsTest.java
deleted file mode 100644
index 1ab4459..0000000
--- a/utils/test/com/cloud/utils/net/NetUtilsTest.java
+++ /dev/null
@@ -1,421 +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 com.cloud.utils.net;
-
-import static org.hamcrest.Matchers.anyOf;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.hamcrest.Matchers.lessThanOrEqualTo;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import java.math.BigInteger;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.apache.log4j.Logger;
-import org.junit.Test;
-
-import com.googlecode.ipv6.IPv6Address;
-
-public class NetUtilsTest {
-
- private static final Logger s_logger = Logger.getLogger(NetUtilsTest.class);
-
- @Test
- public void testGetRandomIpFromCidrWithSize24() throws Exception {
- final String cidr = "192.168.124.1";
- final int size = 24;
- final int netCharacters = 12;
-
- final long ip = NetUtils.getRandomIpFromCidr(cidr, size, new TreeSet<Long>());
-
- assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip)
- .substring(0, netCharacters)));
- }
-
- @Test
- public void testGetRandomIpFromCidrWithSize16() throws Exception {
- final String cidr = "192.168.124.1";
- final int size = 16;
- final int netCharacters = 8;
-
- final long ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>());
-
- assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip)
- .substring(0, netCharacters)));
- }
-
- @Test
- public void testGetRandomIpFromCidrWithSize8() throws Exception {
- final String cidr = "192.168.124.1";
- final int size = 8;
- final int netCharacters = 4;
-
- final long ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>());
-
- assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip)
- .substring(0, netCharacters)));
- }
-
- @Test
- public void testGetRandomIpFromCidrUsignAvoid() throws Exception {
- final String cidr = "192.168.124.1";
- final int size = 30;
-
- final SortedSet<Long> avoid = new TreeSet<Long>();
- long ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
- assertThat("We should be able to retrieve an ip on the first call.", ip, not(equalTo(-1L)));
- avoid.add(ip);
- ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
- assertThat("We should be able to retrieve an ip on the second call.", ip, not(equalTo(-1L)));
- assertThat("ip returned is not in the avoid list", avoid, not(contains(ip)));
- avoid.add(ip);
- ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
- assertThat("We should be able to retrieve an ip on the third call.", ip, not(equalTo(-1L)));
- assertThat("ip returned is not in the avoid list", avoid, not(contains(ip)));
- avoid.add(ip);
- ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
- assertEquals("This should be -1 because we ran out of ip addresses: " + ip, ip, -1);
- }
-
- @Test
- public void testIsValidS2SVpnPolicy() {
- assertTrue(NetUtils.isValidS2SVpnPolicy("aes128-sha1"));
- assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1"));
- assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1,aes256-sha1"));
- assertTrue(NetUtils.isValidS2SVpnPolicy("3des-md5;modp1024"));
- assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1,aes128-sha1;modp1536"));
- assertFalse(NetUtils.isValidS2SVpnPolicy("des-md5;modp1024,aes128-sha1;modp1536"));
- assertFalse(NetUtils.isValidS2SVpnPolicy("des-sha1"));
- assertFalse(NetUtils.isValidS2SVpnPolicy("abc-123,ase-sha1"));
- assertFalse(NetUtils.isValidS2SVpnPolicy("de-sh,aes-sha1"));
- assertFalse(NetUtils.isValidS2SVpnPolicy(""));
- assertFalse(NetUtils.isValidS2SVpnPolicy(";modp1536"));
- assertFalse(NetUtils.isValidS2SVpnPolicy(",aes;modp1536,,,"));
- }
-
- @Test
- public void testGetIp6FromRange() {
- assertEquals(NetUtils.getIp6FromRange("1234:5678::1-1234:5678::1"), "1234:5678::1");
- for (int i = 0; i < 5; i++) {
- final String ip = NetUtils.getIp6FromRange("1234:5678::1-1234:5678::2");
- assertThat(ip, anyOf(equalTo("1234:5678::1"), equalTo("1234:5678::2")));
- s_logger.info("IP is " + ip);
- }
- String ipString = null;
- final IPv6Address ipStart = IPv6Address.fromString("1234:5678::1");
- final IPv6Address ipEnd = IPv6Address.fromString("1234:5678::ffff:ffff:ffff:ffff");
- for (int i = 0; i < 10; i++) {
- ipString = NetUtils.getIp6FromRange(ipStart.toString() + "-" + ipEnd.toString());
- s_logger.info("IP is " + ipString);
- final IPv6Address ip = IPv6Address.fromString(ipString);
- assertThat(ip, greaterThanOrEqualTo(ipStart));
- assertThat(ip, lessThanOrEqualTo(ipEnd));
- }
- }
-
- @Test
- public void testCountIp6InRange() {
- assertEquals(new BigInteger("2"), NetUtils.countIp6InRange("1234:5678::1-1234:5678::2"));
- }
-
- @Test
- public void testCountIp6InRangeWithInvalidRange() {
- assertEquals(null, NetUtils.countIp6InRange("1234:5678::2-1234:5678::0"));
- }
-
- @Test
- public void testCountIp6InRangeWithNullStart() {
- assertEquals(null, NetUtils.countIp6InRange("-1234:5678::0"));
- }
-
- @Test
- public void testCountIp6InRangeWithNoEnd() {
- assertEquals(new BigInteger("1"), NetUtils.countIp6InRange("1234:5678::2"));
- }
-
- @Test
- public void testGetIp6CidrSize() {
- assertEquals(NetUtils.getIp6CidrSize("1234:5678::1/32"), 32);
- assertEquals(NetUtils.getIp6CidrSize("1234:5678::1"), 0);
- }
-
- @Test
- public void testIsValidIp6Cidr() {
- assertTrue(NetUtils.isValidIp6Cidr("1234:5678::1/64"));
- assertFalse(NetUtils.isValidIp6Cidr("1234:5678::1"));
- }
-
- @Test
- public void testIsValidIpv6() {
- assertTrue(NetUtils.isValidIpv6("fc00::1"));
- assertFalse(NetUtils.isValidIpv6(""));
- assertFalse(NetUtils.isValidIpv6(null));
- assertFalse(NetUtils.isValidIpv6("1234:5678::1/64"));
- }
-
- @Test
- public void testIsIp6InRange() {
- assertTrue(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678:abcd::1-1234:5678:abcd::1"));
- assertFalse(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678:abcd::2-1234:5678:abcd::1"));
- assertFalse(NetUtils.isIp6InRange("1234:5678:abcd::1", null));
- assertTrue(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678::1-1234:5679::1"));
- }
-
- @Test
- public void testIsIp6InNetwork() {
- assertFalse(NetUtils.isIp6InNetwork("1234:5678:abcd::1", "1234:5678::/64"));
- assertTrue(NetUtils.isIp6InNetwork("1234:5678::1", "1234:5678::/64"));
- assertTrue(NetUtils.isIp6InNetwork("1234:5678::ffff:ffff:ffff:ffff", "1234:5678::/64"));
- assertTrue(NetUtils.isIp6InNetwork("1234:5678::", "1234:5678::/64"));
- }
-
- @Test
- public void testGetNextIp6InRange() {
- String range = "1234:5678::1-1234:5678::8000:0000";
- assertEquals(NetUtils.getNextIp6InRange("1234:5678::8000:0", range), "1234:5678::1");
- assertEquals(NetUtils.getNextIp6InRange("1234:5678::7fff:ffff", range), "1234:5678::8000:0");
- assertEquals(NetUtils.getNextIp6InRange("1234:5678::1", range), "1234:5678::2");
- range = "1234:5678::1-1234:5678::ffff:ffff:ffff:ffff";
- assertEquals(NetUtils.getNextIp6InRange("1234:5678::ffff:ffff:ffff:ffff", range), "1234:5678::1");
- }
-
- @Test
- public void testIsIp6RangeOverlap() {
- assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::1-1234:5678::ffff", "1234:5678:1::1-1234:5678:1::ffff"));
- assertTrue(NetUtils.isIp6RangeOverlap("1234:5678::1-1234:5678::ffff", "1234:5678::2-1234:5678::f"));
- assertTrue(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::ffff", "1234:5678::2-1234:5678::f"));
- assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::ffff", "1234:5678::2-1234:5678::e"));
- assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::f", "1234:5678::2-1234:5678::e"));
- }
-
- @Test
- public void testStandardizeIp6Address() {
- assertEquals(NetUtils.standardizeIp6Address("1234:0000:0000:5678:0000:0000:ABCD:0001"), "1234::5678:0:0:abcd:1");
- assertEquals(NetUtils.standardizeIp6Cidr("1234:0000:0000:5678:0000:0000:ABCD:0001/64"), "1234:0:0:5678::/64");
- }
-
- @Test
- public void testGenerateUriForPvlan() {
- assertEquals("pvlan://123-i456", NetUtils.generateUriForPvlan("123", "456").toString());
- }
-
- @Test
- public void testGetPrimaryPvlanFromUri() {
- assertEquals("123", NetUtils.getPrimaryPvlanFromUri(NetUtils.generateUriForPvlan("123", "456")));
- }
-
- @Test
- public void testGetIsolatedPvlanFromUri() {
- assertEquals("456", NetUtils.getIsolatedPvlanFromUri(NetUtils.generateUriForPvlan("123", "456")));
- }
-
- @Test
- public void testIsValidCIDR() throws Exception {
- //Test to check IP Range of 2 CIDR
- final String cidrFirst = "10.0.144.0/20";
- final String cidrSecond = "10.0.151.0/20";
- final String cidrThird = "10.0.144.0/21";
-
- assertTrue(NetUtils.isValidCIDR(cidrFirst));
- assertTrue(NetUtils.isValidCIDR(cidrSecond));
- assertTrue(NetUtils.isValidCIDR(cidrThird));
- }
-
- @Test
- public void testIsValidCidrList() throws Exception {
- final String cidrFirst = "10.0.144.0/20,1.2.3.4/32,5.6.7.8/24";
- final String cidrSecond = "10.0.151.0/20,129.0.0.0/4";
- final String cidrThird = "10.0.144.0/21";
-
- assertTrue(NetUtils.isValidCidrList(cidrFirst));
- assertTrue(NetUtils.isValidCidrList(cidrSecond));
- assertTrue(NetUtils.isValidCidrList(cidrThird));
- }
-
- @Test
- public void testIsSameIpRange() {
- final String cidrFirst = "10.0.144.0/20";
- final String cidrSecond = "10.0.151.0/20";
- final String cidrThird = "10.0.144.0/21";
-
- //Check for exactly same CIDRs
- assertTrue(NetUtils.isSameIpRange(cidrFirst, cidrFirst));
- //Check for 2 different CIDRs, but same IP Range
- assertTrue(NetUtils.isSameIpRange(cidrFirst, cidrSecond));
- //Check for 2 different CIDRs and different IP Range
- assertFalse(NetUtils.isSameIpRange(cidrFirst, cidrThird));
- //Check for Incorrect format of CIDR
- assertFalse(NetUtils.isSameIpRange(cidrFirst, "10.3.6.5/50"));
- }
-
- @Test
- public void testGenerateMacOnIncrease() {
- String mac = "06:01:23:00:45:67";
- assertEquals("06:01:25:00:45:67", NetUtils.generateMacOnIncrease(mac, 2));
- assertEquals("06:01:33:00:45:67", NetUtils.generateMacOnIncrease(mac, 16));
- mac = "06:ff:ff:00:45:67";
- assertEquals("06:00:00:00:45:67", NetUtils.generateMacOnIncrease(mac, 1));
- assertEquals("06:00:0f:00:45:67", NetUtils.generateMacOnIncrease(mac, 16));
- }
-
- @Test
- public void testGetLocalIPString() {
- assertNotNull(NetUtils.getLocalIPString());
- }
-
- @Test
- public void testSameIsolationId() {
- assertTrue(NetUtils.isSameIsolationId("1", "vlan://1"));
- assertTrue(NetUtils.isSameIsolationId("", null));
- assertTrue(NetUtils.isSameIsolationId("UnTagged", "vlan://uNtAGGED"));
- assertFalse(NetUtils.isSameIsolationId("2", "vlan://uNtAGGED"));
- assertFalse(NetUtils.isSameIsolationId("2", "vlan://3"));
- assertFalse(NetUtils.isSameIsolationId("bla", null));
- }
-
- @Test
- public void testValidateGuestCidr() throws Exception {
- final String guestCidr = "192.168.1.0/24";
-
- assertTrue(NetUtils.validateGuestCidr(guestCidr));
- }
-
- @Test
- public void testMac2Long() {
- assertEquals(0l, NetUtils.mac2Long("00:00:00:00:00:00"));
- assertEquals(1l, NetUtils.mac2Long("00:00:00:00:00:01"));
- assertEquals(0xFFl, NetUtils.mac2Long("00:00:00:00:00:FF"));
- assertEquals(0xFFAAl, NetUtils.mac2Long("00:00:00:00:FF:AA"));
- assertEquals(0x11FFAAl, NetUtils.mac2Long("00:00:00:11:FF:AA"));
- assertEquals(0x12345678l, NetUtils.mac2Long("00:00:12:34:56:78"));
- assertEquals(0x123456789Al, NetUtils.mac2Long("00:12:34:56:78:9A"));
- assertEquals(0x123456789ABCl, NetUtils.mac2Long("12:34:56:78:9A:BC"));
- }
-
- @Test
- public void testLong2Mac() {
- assertEquals("00:00:00:00:00:00", NetUtils.long2Mac(0l));
- assertEquals("00:00:00:00:00:01", NetUtils.long2Mac(1l));
- assertEquals("00:00:00:00:00:ff", NetUtils.long2Mac(0xFFl));
- assertEquals("00:00:00:00:ff:aa", NetUtils.long2Mac(0xFFAAl));
- assertEquals("00:00:00:11:ff:aa", NetUtils.long2Mac(0x11FFAAl));
- assertEquals("00:00:12:34:56:78", NetUtils.long2Mac(0x12345678l));
- assertEquals("00:12:34:56:78:9a", NetUtils.long2Mac(0x123456789Al));
- assertEquals("12:34:56:78:9a:bc", NetUtils.long2Mac(0x123456789ABCl));
- }
-
- @Test
- public void testIp2Long() {
- assertEquals(0x7f000001l, NetUtils.ip2Long("127.0.0.1"));
- assertEquals(0xc0a80001l, NetUtils.ip2Long("192.168.0.1"));
- assertEquals(0x08080808l, NetUtils.ip2Long("8.8.8.8"));
- }
-
- @Test
- public void testLong2Ip() {
- assertEquals("127.0.0.1", NetUtils.long2Ip(0x7f000001l));
- assertEquals("192.168.0.1", NetUtils.long2Ip(0xc0a80001l));
- assertEquals("8.8.8.8", NetUtils.long2Ip(0x08080808l));
- }
-
- @Test
- public void test31BitPrefixStart() {
- final String ipAddress = "192.168.0.0";
- final String cidr = "192.168.0.0/31";
-
- final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr);
-
- assertTrue("Check if the subnetUtils.setInclusiveHostCount(true) has been called.", isInRange);
- }
-
- @Test
- public void test31BitPrefixEnd() {
- final String ipAddress = "192.168.0.1";
- final String cidr = "192.168.0.0/31";
-
- final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr);
-
- assertTrue("Check if the subnetUtils.setInclusiveHostCount(true) has been called.", isInRange);
- }
-
- @Test
- public void test31BitPrefixFail() {
- final String ipAddress = "192.168.0.2";
- final String cidr = "192.168.0.0/31";
-
- final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr);
-
- assertFalse("Out of the range. Why did it return true?", isInRange);
- }
-
- @Test
- public void test31BitPrefixIpRangesOverlapd() {
- final String gw = "192.168.0.0";
- String ip1;
- String ip2;
-
- for (int i = 1, j = 2; i <= 254; i++, j++) {
- ip1 = "192.168.0." + i;
- ip2 = "192.168.0." + j;
-
- final boolean doesOverlap = NetUtils.ipRangesOverlap(ip1, ip2, gw, gw);
- assertFalse("It should overlap, but it's a 31-bit ip", doesOverlap);
- }
- }
-
- @Test
- public void test31BitPrefixIpRangesOverlapdFail() {
- String gw;
- String ip1;
- String ip2;
-
- for (int i = 10, j = 12; i <= 254; i++, j++) {
- gw = "192.168.0." + i;
- ip1 = "192.168.0." + i;
- ip2 = "192.168.0." + j;
-
- final boolean doesOverlap = NetUtils.ipRangesOverlap(ip1, ip2, gw, gw);
- assertTrue("It overlaps!", doesOverlap);
- }
- }
-
- @Test
- public void testIs31PrefixCidrFail() {
- final String cidr = "10.10.0.0/32";
- final boolean is31PrefixCidr = NetUtils.is31PrefixCidr(cidr);
-
- assertFalse("It should fail! 32 bit prefix.", is31PrefixCidr);
- }
-
- @Test
- public void testIs31PrefixCidr() {
- final String cidr = "10.10.0.0/31";
- final boolean is31PrefixCidr = NetUtils.is31PrefixCidr(cidr);
-
- assertTrue("It should pass! 31 bit prefix.", is31PrefixCidr);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java
deleted file mode 100644
index 6d58b5b..0000000
--- a/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java
+++ /dev/null
@@ -1,395 +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 com.cloud.utils.rest;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-import java.util.Collections;
-
-import org.apache.commons.httpclient.Header;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.params.HttpClientParams;
-import org.apache.http.HttpStatus;
-import org.junit.Before;
-import org.junit.Test;
-
-public class RESTServiceConnectorTest {
- protected static final String UUID = "aaaa";
- protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}";
-
- RESTServiceConnector connector;
- HttpClient client = mock(HttpClient.class);
- HttpMethod method;
- String type;
- String uri;
-
- @Before
- public void setUp() {
- final HttpClientParams hmp = mock(HttpClientParams.class);
- when(client.getParams()).thenReturn(hmp);
- connector = new RESTServiceConnector(null) {
- @Override
- public HttpClient createHttpClient() {
- return client;
- }
-
- @Override
- public HttpMethod createMethod(final String newType, final String newUri) {
- type = newType;
- uri = newUri;
- return method;
- }
- };
-
- connector.validation = new RESTValidationStrategy();
- connector.setAdminCredentials("admin", "adminpass");
- connector.setControllerAddress("localhost");
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteLoginWithoutHostname() throws CloudstackRESTException {
- connector.setControllerAddress(null);
- connector.validation.login(RESTServiceConnector.protocol, client);
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteLoginWithoutCredentials() throws CloudstackRESTException {
- method = mock(PutMethod.class);
- connector.setAdminCredentials(null, null);
- connector.validation.login(RESTServiceConnector.protocol, client);
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(PutMethod.class);
- connector.setControllerAddress(null);
- connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(PutMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(PostMethod.class);
- connector.setControllerAddress(null);
- connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(PostMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(DeleteMethod.class);
- connector.setControllerAddress(null);
- connector.executeDeleteObject("/");
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(DeleteMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeDeleteObject("/");
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(GetMethod.class);
- connector.setControllerAddress(null);
- connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(GetMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
- }
-
- @Test
- public void testExecuteMethod() throws CloudstackRESTException {
- final GetMethod gm = mock(GetMethod.class);
-
- when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- connector.executeMethod(gm);
- verify(gm, times(1)).getStatusCode();
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException {
- final GetMethod gm = mock(GetMethod.class);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
- when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
- connector.executeMethod(gm);
- verify(gm, times(1)).getStatusCode();
- }
-
- /* Bit of a roundabout way to ensure that login is called after an un authorized result
- * It not possible to properly mock login()
- */
- public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException, HttpException, IOException {
- // Prepare
- final GetMethod gm = mock(GetMethod.class);
- when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
-
- final RESTValidationStrategy previousValidationStrategy = connector.validation;
- connector.validation = new RESTValidationStrategy(){
- @Override
- protected void login(final String protocol, final HttpClient client)
- throws CloudstackRESTException {
- // Do nothing
- }
- };
- connector.setAdminCredentials("admin", "adminpass");
- connector.setControllerAddress("localhost");
-
- // Execute
- connector.executeMethod(gm);
- // Leave mock object as is was
- connector.validation = previousValidationStrategy;
-
- // Assert/verify
- verify(gm, times(2)).getStatusCode();
- }
-
- @Test
- public void testExecuteCreateObject() throws CloudstackRESTException, IOException {
- JsonEntity ls = new JsonEntity();
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
- assertTrue(UUID.equals(ls.getUuid()));
- verify(method, times(1)).releaseConnection();
-
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectFailure() throws CloudstackRESTException, IOException {
- JsonEntity ls = new JsonEntity();
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectException() throws CloudstackRESTException, IOException {
- JsonEntity ls = new JsonEntity();
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- try {
- ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test
- public void testExecuteUpdateObject() throws CloudstackRESTException, IOException {
- final JsonEntity ls = new JsonEntity();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
- verify(method, times(1)).releaseConnection();
- verify(client, times(1)).executeMethod(method);
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectFailure() throws CloudstackRESTException, IOException {
- final JsonEntity ls = new JsonEntity();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectException() throws CloudstackRESTException, IOException {
- final JsonEntity ls = new JsonEntity();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException());
- try {
- connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test
- public void testExecuteDeleteObject() throws CloudstackRESTException, IOException {
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
- connector.executeDeleteObject("/");
- verify(method, times(1)).releaseConnection();
- verify(client, times(1)).executeMethod(method);
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectFailure() throws CloudstackRESTException, IOException {
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- connector.executeDeleteObject("/");
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectException() throws CloudstackRESTException, IOException {
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
- try {
- connector.executeDeleteObject("/");
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test
- public void testExecuteRetrieveObject() throws CloudstackRESTException, IOException {
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
- verify(method, times(1)).releaseConnection();
- verify(client, times(1)).executeMethod(method);
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectFailure() throws CloudstackRESTException, IOException {
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectException() throws CloudstackRESTException, IOException {
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
- try {
- connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
-
-}
-
-class JsonEntity {
- private String displayName;
- private String uuid;
- private String href;
- private String schema;
-
- public String getDisplayName() {
- return displayName;
- }
-
- public void setDisplayName(final String displayName) {
- this.displayName = displayName;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(final String uuid) {
- this.uuid = uuid;
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(final String href) {
- this.href = href;
- }
-
- public String getSchema() {
- return schema;
- }
-
- public void setSchema(final String schema) {
- this.schema = schema;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/ssh/SSHKeysHelperTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/ssh/SSHKeysHelperTest.java b/utils/test/com/cloud/utils/ssh/SSHKeysHelperTest.java
deleted file mode 100644
index a3daf91..0000000
--- a/utils/test/com/cloud/utils/ssh/SSHKeysHelperTest.java
+++ /dev/null
@@ -1,73 +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 com.cloud.utils.ssh;
-
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class SSHKeysHelperTest {
- @Test
- public void rsaKeyTest() {
- String rsaKey =
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW"
- + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk"
- + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P"
- + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6"
- + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX test@testkey";
- String storedRsaKey =
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW"
- + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk"
- + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P"
- + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX";
- String parsedKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(rsaKey);
- String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(parsedKey);
-
- assertTrue(storedRsaKey.equals(parsedKey));
- assertTrue("f6:96:3f:f4:78:f7:80:11:6c:f8:e3:2b:40:20:f1:14".equals(fingerprint));
-
- }
-
- @Test
- public void dsaKeyTest() {
- String dssKey =
- "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV"
- + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO"
- + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA"
- + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF"
- + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD"
- + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR"
- + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ== test key";
- String storedDssKey =
- "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV"
- + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO"
- + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA"
- + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF"
- + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD"
- + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR"
- + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ==";
- String parsedKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(dssKey);
- String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(parsedKey);
-
- assertTrue(storedDssKey.equals(parsedKey));
- assertTrue("fc:6e:ef:31:93:f8:92:2b:a9:03:c7:06:90:f5:ec:bb".equals(fingerprint));
-
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/testcase/Log4jEnabledTestCase.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/testcase/Log4jEnabledTestCase.java b/utils/test/com/cloud/utils/testcase/Log4jEnabledTestCase.java
deleted file mode 100644
index 51cde2c..0000000
--- a/utils/test/com/cloud/utils/testcase/Log4jEnabledTestCase.java
+++ /dev/null
@@ -1,58 +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 com.cloud.utils.testcase;
-
-import java.io.File;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.Random;
-
-import junit.framework.TestCase;
-
-import org.apache.log4j.xml.DOMConfigurator;
-
-public class Log4jEnabledTestCase extends TestCase {
- @Override
- protected void setUp() {
- URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
- if (configUrl != null) {
- System.out.println("Configure log4j using log4j-cloud.xml");
-
- try {
- File file = new File(configUrl.toURI());
-
- System.out.println("Log4j configuration from : " + file.getAbsolutePath());
- DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
- } catch (URISyntaxException e) {
- System.out.println("Unable to convert log4j configuration Url to URI");
- }
- } else {
- System.out.println("Configure log4j with default properties");
- }
- }
-
- public static int getRandomMilliseconds(int rangeLo, int rangeHi) {
- int i = new Random().nextInt();
-
- long pos = (long)i - (long)Integer.MIN_VALUE;
- long iRange = (long)Integer.MAX_VALUE - (long)Integer.MIN_VALUE;
- return rangeLo + (int)((rangeHi - rangeLo) * pos / iRange);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/testcase/NioTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/testcase/NioTest.java b/utils/test/com/cloud/utils/testcase/NioTest.java
deleted file mode 100644
index fc16684..0000000
--- a/utils/test/com/cloud/utils/testcase/NioTest.java
+++ /dev/null
@@ -1,216 +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 com.cloud.utils.testcase;
-
-import java.nio.channels.ClosedChannelException;
-import java.util.Random;
-
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-import org.junit.Assert;
-
-import com.cloud.utils.nio.HandlerFactory;
-import com.cloud.utils.nio.Link;
-import com.cloud.utils.nio.NioClient;
-import com.cloud.utils.nio.NioServer;
-import com.cloud.utils.nio.Task;
-import com.cloud.utils.nio.Task.Type;
-
-/**
- *
- *
- *
- *
- */
-
-public class NioTest extends TestCase {
-
- private static final Logger s_logger = Logger.getLogger(NioTest.class);
-
- private NioServer _server;
- private NioClient _client;
-
- private Link _clientLink;
-
- private int _testCount;
- private int _completedCount;
-
- private boolean isTestsDone() {
- boolean result;
- synchronized (this) {
- result = (_testCount == _completedCount);
- }
- return result;
- }
-
- private void getOneMoreTest() {
- synchronized (this) {
- _testCount++;
- }
- }
-
- private void oneMoreTestDone() {
- synchronized (this) {
- _completedCount++;
- }
- }
-
- @Override
- public void setUp() {
- s_logger.info("Test");
-
- _testCount = 0;
- _completedCount = 0;
-
- _server = new NioServer("NioTestServer", 7777, 5, new NioTestServer());
- _server.start();
-
- _client = new NioClient("NioTestServer", "127.0.0.1", 7777, 5, new NioTestClient());
- _client.start();
-
- while (_clientLink == null) {
- try {
- s_logger.debug("Link is not up! Waiting ...");
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public void tearDown() {
- while (!isTestsDone()) {
- try {
- s_logger.debug(this._completedCount + "/" + this._testCount + " tests done. Waiting for completion");
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- stopClient();
- stopServer();
- }
-
- protected void stopClient() {
- _client.stop();
- s_logger.info("Client stopped.");
- }
-
- protected void stopServer() {
- _server.stop();
- s_logger.info("Server stopped.");
- }
-
- protected void setClientLink(Link link) {
- _clientLink = link;
- }
-
- Random randomGenerator = new Random();
-
- byte[] _testBytes;
-
- public void testConnection() {
- _testBytes = new byte[1000000];
- randomGenerator.nextBytes(_testBytes);
- try {
- getOneMoreTest();
- _clientLink.send(_testBytes);
- s_logger.info("Client: Data sent");
- getOneMoreTest();
- _clientLink.send(_testBytes);
- s_logger.info("Client: Data sent");
- } catch (ClosedChannelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- protected void doServerProcess(byte[] data) {
- oneMoreTestDone();
- Assert.assertArrayEquals(_testBytes, data);
- s_logger.info("Verify done.");
- }
-
- public class NioTestClient implements HandlerFactory {
-
- @Override
- public Task create(Type type, Link link, byte[] data) {
- return new NioTestClientHandler(type, link, data);
- }
-
- public class NioTestClientHandler extends Task {
-
- public NioTestClientHandler(Type type, Link link, byte[] data) {
- super(type, link, data);
- }
-
- @Override
- public void doTask(final Task task) {
- if (task.getType() == Task.Type.CONNECT) {
- s_logger.info("Client: Received CONNECT task");
- setClientLink(task.getLink());
- } else if (task.getType() == Task.Type.DATA) {
- s_logger.info("Client: Received DATA task");
- } else if (task.getType() == Task.Type.DISCONNECT) {
- s_logger.info("Client: Received DISCONNECT task");
- stopClient();
- } else if (task.getType() == Task.Type.OTHER) {
- s_logger.info("Client: Received OTHER task");
- }
- }
-
- }
- }
-
- public class NioTestServer implements HandlerFactory {
-
- @Override
- public Task create(Type type, Link link, byte[] data) {
- return new NioTestServerHandler(type, link, data);
- }
-
- public class NioTestServerHandler extends Task {
-
- public NioTestServerHandler(Type type, Link link, byte[] data) {
- super(type, link, data);
- }
-
- @Override
- public void doTask(final Task task) {
- if (task.getType() == Task.Type.CONNECT) {
- s_logger.info("Server: Received CONNECT task");
- } else if (task.getType() == Task.Type.DATA) {
- s_logger.info("Server: Received DATA task");
- doServerProcess(task.getData());
- } else if (task.getType() == Task.Type.DISCONNECT) {
- s_logger.info("Server: Received DISCONNECT task");
- stopServer();
- } else if (task.getType() == Task.Type.OTHER) {
- s_logger.info("Server: Received OTHER task");
- }
- }
-
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/xmlobject/TestXmlObject.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/xmlobject/TestXmlObject.java b/utils/test/com/cloud/utils/xmlobject/TestXmlObject.java
deleted file mode 100644
index faaf980..0000000
--- a/utils/test/com/cloud/utils/xmlobject/TestXmlObject.java
+++ /dev/null
@@ -1,53 +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 com.cloud.utils.xmlobject;
-
-import org.junit.Test;
-
-public class TestXmlObject {
-
- void p(String str) {
- System.out.println(str);
- }
-
- @Test
- public void test() {
-
- // deprecated, since we no longer use component.xml.in any more
- /*
- XmlObject xo = XmlObjectParser.parseFromFile("z:/components.xml.in");
- p(xo.getTag());
- p((String) xo.get("system-integrity-checker.checker").toString());
- List<XmlObject> lst = xo.get("management-server.adapters");
- for (XmlObject x : lst) {
- List<XmlObject> lst1 = x.getAsList("adapter");
- for (XmlObject y : lst1) {
- p(y.toString());
- }
- }
- */
-
- XmlObject xml = new XmlObject("vlan").putElement("vlan-id", String.valueOf(19)).putElement("tagged",
- new XmlObject("teng").putElement("name", "0/0")
- ).putElement("shutdown", "false");
- System.out.println(xml.toString());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java b/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java
deleted file mode 100644
index 9a27ca1..0000000
--- a/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java
+++ /dev/null
@@ -1,54 +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 com.cloud.utils.xmlobject;
-
-import org.junit.Test;
-
-public class TestXmlObject2 {
- void p(String str) {
- System.out.println(str);
- }
-
- XmlObject xo(String name) {
- return new XmlObject(name);
- }
-
- @Test
- public void test() {
- XmlObject root = new XmlObject("test");
- root.putElement("key1", "value1").putElement("key2", "value2");
- p(root.dump());
-
- XmlObject c1 = new XmlObject("child1");
- XmlObject c2 = new XmlObject("child2");
- c2.putElement("ckey1", "value1");
- c1.putElement(c2.getTag(), c2);
- root.putElement(c1.getTag(), c1);
- p(root.dump());
-
- root =
- xo("test2").putElement("key1", "value1")
- .putElement("child1", xo("child1").setText("yyy"))
- .putElement("child1", xo("child1").putElement("child2", xo("child2").putElement("child3", xo("child3").putElement("key3", "value3").setText("xxxxx"))));
-
- p(root.dump());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/test/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java b/utils/test/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java
deleted file mode 100644
index ace765a..0000000
--- a/utils/test/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java
+++ /dev/null
@@ -1,54 +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.utils.imagestore;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.UUID;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ImageStoreUtilTest {
-
- @Test
- public void testgeneratePostUploadUrl() throws MalformedURLException {
- String ssvmdomain = "*.realhostip.com";
- String ipAddress = "10.147.28.14";
- String uuid = UUID.randomUUID().toString();
-
- //ssvm domain is not set
- String url = ImageStoreUtil.generatePostUploadUrl(null, ipAddress, uuid);
- assertPostUploadUrl(url, ipAddress, uuid);
-
- //ssvm domain is set to empty value
- url = ImageStoreUtil.generatePostUploadUrl("", ipAddress, uuid);
- assertPostUploadUrl(url, ipAddress, uuid);
-
- //ssvm domain is set to a valid value
- url = ImageStoreUtil.generatePostUploadUrl(ssvmdomain, ipAddress, uuid);
- assertPostUploadUrl(url, ipAddress.replace(".", "-") + ssvmdomain.substring(1), uuid);
- }
-
- private void assertPostUploadUrl(String urlStr, String domain, String uuid) throws MalformedURLException {
- URL url = new URL(urlStr);
- Assert.assertNotNull(url);
- Assert.assertEquals(url.getHost(), domain);
- Assert.assertEquals(url.getPath(), "/upload/" + uuid);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
----------------------------------------------------------------------
diff --git a/utils/test/resources/com/cloud/utils/QualifierTestContext.xml b/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
deleted file mode 100644
index 39f494b..0000000
--- a/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:annotation-config />
- <context:component-scan base-package="org.apache.cloudstack, com.cloud" />
-
-</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
----------------------------------------------------------------------
diff --git a/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml b/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
deleted file mode 100644
index 81ca058..0000000
--- a/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:annotation-config />
- <context:component-scan base-package="org.apache.cloudstack, com.cloud" />
-
- <aop:config proxy-target-class="true">
- <aop:aspect id="dbContextBuilder" ref="transactionContextBuilder">
- <aop:pointcut id="captureAnyMethod"
- expression="execution(* *(..))" />
- <aop:around pointcut-ref="captureAnyMethod" method="AroundAnyMethod"/>
- </aop:aspect>
- </aop:config>
-
- <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
-
-</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/resources/log4j.xml
----------------------------------------------------------------------
diff --git a/utils/test/resources/log4j.xml b/utils/test/resources/log4j.xml
deleted file mode 100755
index cdae2fa..0000000
--- a/utils/test/resources/log4j.xml
+++ /dev/null
@@ -1,118 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
-
- <throwableRenderer class="com.cloud.utils.log.CglibThrowableRenderer"/>
- <!-- ================================= -->
- <!-- Preserve messages in a local file -->
- <!-- ================================= -->
-
- <!-- A regular appender FIXME implement code that will close/reopen logs on SIGHUP by logrotate FIXME make the paths configurable using the build system -->
-<!-- <appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
- <param name="Append" value="true"/>
- <param name="Threshold" value="TRACE"/>
- <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
- <param name="FileNamePattern" value="@MSLOG@.%d{yyyy-MM-dd}.gz"/>
- <param name="ActiveFileName" value="@MSLOG@"/>
- </rollingPolicy>
- <layout class="org.apache.log4j.EnhancedPatternLayout">
- <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
- </layout>
- </appender>
- -->
- <!--
- <appender name="APISERVER" class="org.apache.log4j.rolling.RollingFileAppender">
- <param name="Append" value="true"/>
- <param name="Threshold" value="TRACE"/>
- <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
- <param name="FileNamePattern" value="@APISERVERLOG@.%d{yyyy-MM-dd}.gz"/>
- <param name="ActiveFileName" value="@APISERVERLOG@"/>
- </rollingPolicy>
- <layout class="org.apache.log4j.EnhancedPatternLayout">
- <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
- </layout>
- </appender>
- -->
-
-
- <!-- ============================== -->
- <!-- Append warnings+ to the syslog if it is listening on UDP port FIXME make sysloghost configurable! -->
- <!-- ============================== -->
-<!--
- <appender name="SYSLOG" class="org.apache.log4j.net.SyslogAppender">
- <param name="Threshold" value="WARN"/>
- <param name="SyslogHost" value="localhost"/>
- <param name="Facility" value="LOCAL6"/>
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%-5p [%c{3}] (%t:%x) %m%n"/>
- </layout>
- </appender>
--->
- <!-- ============================== -->
- <!-- Append messages to the console -->
- <!-- ============================== -->
-
- <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
- <param name="Target" value="System.out"/>
- <param name="Threshold" value="TRACE"/>
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
- </layout>
- </appender>
-
- <!-- ================ -->
- <!-- Limit categories -->
- <!-- ================ -->
-
- <category name="com.cloud">
- <priority value="DEBUG"/>
- </category>
-
- <!-- Limit the org.apache category to INFO as its DEBUG is verbose -->
- <category name="org.apache">
- <priority value="INFO"/>
- </category>
-
- <category name="org">
- <priority value="INFO"/>
- </category>
-
- <category name="net">
- <priority value="INFO"/>
- </category>
-
- <category name="apiserver.com.cloud">
- <priority value="DEBUG"/>
- </category>
-
- <!-- ======================= -->
- <!-- Setup the Root category -->
- <!-- ======================= -->
-
- <root>
- <level value="INFO"/>
- <appender-ref ref="CONSOLE"/>
- </root>
-
-</log4j:configuration>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/resources/testContext.xml
----------------------------------------------------------------------
diff --git a/utils/test/resources/testContext.xml b/utils/test/resources/testContext.xml
deleted file mode 100644
index cb5b9b8..0000000
--- a/utils/test/resources/testContext.xml
+++ /dev/null
@@ -1,52 +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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-
- <context:annotation-config />
-
- <context:component-scan base-package="org.apache.cloudstack, com.cloud" />
-
- <!--
- @DB support
- -->
- <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
-
- <bean id="instantiatePostProcessor" class="com.cloud.utils.component.ComponentInstantiationPostProcessor">
- <property name="Interceptors">
- <list>
- <ref bean="transactionContextBuilder" />
- </list>
- </property>
- </bean>
-
-</beans>
[29/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Refactor cloud-utils project into Maven default structure
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/83fd8f60
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/83fd8f60
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/83fd8f60
Branch: refs/heads/deploy-from-snapshot
Commit: 83fd8f60f3c503cf6fda7833b0f45c23a215f559
Parents: 3d27e9e
Author: Miguel Ferreira <mi...@me.com>
Authored: Sun Aug 23 16:03:11 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 14:50:33 2015 +0200
----------------------------------------------------------------------
utils/certs/cloud.keystore | Bin 1316 -> 0 bytes
utils/pom.xml | 44 +-
utils/src/com/cloud/maint/Version.java | 77 -
utils/src/com/cloud/utils/ActionDelegate.java | 24 -
.../src/com/cloud/utils/AutoCloseableUtil.java | 36 -
.../com/cloud/utils/CloudResourceBundle.java | 48 -
.../com/cloud/utils/ConstantTimeComparator.java | 42 -
utils/src/com/cloud/utils/DateUtil.java | 274 ----
utils/src/com/cloud/utils/EncryptionUtil.java | 73 -
utils/src/com/cloud/utils/EnumUtils.java | 58 -
utils/src/com/cloud/utils/ExecutionResult.java | 46 -
utils/src/com/cloud/utils/FileUtil.java | 32 -
utils/src/com/cloud/utils/HttpUtils.java | 114 --
utils/src/com/cloud/utils/IteratorUtil.java | 72 -
utils/src/com/cloud/utils/Journal.java | 104 --
utils/src/com/cloud/utils/LogUtils.java | 45 -
utils/src/com/cloud/utils/MethodCapturer.java | 113 --
utils/src/com/cloud/utils/NumbersUtil.java | 139 --
utils/src/com/cloud/utils/Pair.java | 87 -
.../src/com/cloud/utils/PasswordGenerator.java | 90 -
utils/src/com/cloud/utils/Predicate.java | 24 -
utils/src/com/cloud/utils/ProcessUtil.java | 112 --
utils/src/com/cloud/utils/Profiler.java | 91 -
utils/src/com/cloud/utils/PropertiesUtil.java | 196 ---
utils/src/com/cloud/utils/ReflectUtil.java | 213 ---
utils/src/com/cloud/utils/ReflectionUse.java | 31 -
utils/src/com/cloud/utils/S3Utils.java | 603 -------
utils/src/com/cloud/utils/SerialVersionUID.java | 69 -
utils/src/com/cloud/utils/StringUtils.java | 323 ----
utils/src/com/cloud/utils/SwiftUtil.java | 239 ---
utils/src/com/cloud/utils/Ternary.java | 85 -
utils/src/com/cloud/utils/UriUtils.java | 394 -----
.../cloud/utils/UsernamePasswordValidator.java | 49 -
utils/src/com/cloud/utils/UuidUtils.java | 34 -
.../cloud/utils/backoff/BackoffAlgorithm.java | 38 -
.../utils/backoff/impl/ConstantTimeBackoff.java | 102 --
.../backoff/impl/ConstantTimeBackoffMBean.java | 35 -
.../utils/cisco/n1kv/vsm/NetconfHelper.java | 355 ----
.../cloud/utils/cisco/n1kv/vsm/PolicyMap.java | 34 -
.../cloud/utils/cisco/n1kv/vsm/PortProfile.java | 48 -
.../cloud/utils/cisco/n1kv/vsm/VsmCommand.java | 999 -----------
.../utils/cisco/n1kv/vsm/VsmOkResponse.java | 44 -
.../cisco/n1kv/vsm/VsmPolicyMapResponse.java | 84 -
.../cisco/n1kv/vsm/VsmPortProfileResponse.java | 166 --
.../cloud/utils/cisco/n1kv/vsm/VsmResponse.java | 222 ---
.../src/com/cloud/utils/component/Adapter.java | 27 -
.../com/cloud/utils/component/AdapterBase.java | 40 -
.../com/cloud/utils/component/AdapterList.java | 37 -
.../cloud/utils/component/ComponentContext.java | 282 ----
.../ComponentInstantiationPostProcessor.java | 149 --
.../utils/component/ComponentLifecycle.java | 64 -
.../utils/component/ComponentLifecycleBase.java | 87 -
.../component/ComponentMethodInterceptable.java | 27 -
.../component/ComponentMethodInterceptor.java | 32 -
.../utils/component/ComponentNamingPolicy.java | 65 -
.../src/com/cloud/utils/component/Manager.java | 27 -
.../com/cloud/utils/component/ManagerBase.java | 28 -
utils/src/com/cloud/utils/component/Named.java | 26 -
.../cloud/utils/component/PluggableService.java | 29 -
.../src/com/cloud/utils/component/Registry.java | 51 -
.../utils/component/SystemIntegrityChecker.java | 30 -
.../utils/concurrency/NamedThreadFactory.java | 38 -
.../com/cloud/utils/concurrency/Scheduler.java | 31 -
.../utils/concurrency/SynchronizationEvent.java | 89 -
.../com/cloud/utils/concurrency/TestClock.java | 161 --
.../com/cloud/utils/crypt/DBEncryptionUtil.java | 87 -
.../utils/crypt/EncryptionSecretKeyChecker.java | 146 --
.../utils/crypt/EncryptionSecretKeySender.java | 65 -
utils/src/com/cloud/utils/crypt/RSAHelper.java | 90 -
utils/src/com/cloud/utils/db/DbProperties.java | 109 --
utils/src/com/cloud/utils/db/EntityManager.java | 84 -
utils/src/com/cloud/utils/db/UUIDManager.java | 48 -
.../com/cloud/utils/encoding/URLEncoder.java | 113 --
utils/src/com/cloud/utils/events/EventArgs.java | 44 -
.../com/cloud/utils/events/SubscriptionMgr.java | 164 --
.../utils/exception/CSExceptionErrorCode.java | 100 --
.../utils/exception/CloudRuntimeException.java | 141 --
.../com/cloud/utils/exception/ErrorContext.java | 31 -
.../utils/exception/ExceptionProxyObject.java | 55 -
.../cloud/utils/exception/ExceptionUtil.java | 54 -
.../utils/exception/ExecutionException.java | 49 -
.../HypervisorVersionChangedException.java | 35 -
utils/src/com/cloud/utils/fsm/ChangeEvent.java | 24 -
utils/src/com/cloud/utils/fsm/FiniteState.java | 58 -
utils/src/com/cloud/utils/fsm/FiniteState2.java | 34 -
.../com/cloud/utils/fsm/FiniteStateObject.java | 25 -
.../cloud/utils/fsm/NoTransitionException.java | 36 -
utils/src/com/cloud/utils/fsm/State.java | 27 -
utils/src/com/cloud/utils/fsm/StateDao.java | 25 -
.../src/com/cloud/utils/fsm/StateListener.java | 43 -
utils/src/com/cloud/utils/fsm/StateMachine.java | 147 --
.../src/com/cloud/utils/fsm/StateMachine2.java | 261 ---
utils/src/com/cloud/utils/fsm/StateObject.java | 27 -
.../cloud/utils/log/CglibThrowableRenderer.java | 84 -
utils/src/com/cloud/utils/mgmt/JmxUtil.java | 90 -
.../com/cloud/utils/mgmt/ManagementBean.java | 27 -
.../utils/mgmt/PropertyMapDynamicBean.java | 120 --
utils/src/com/cloud/utils/net/Ip.java | 98 --
utils/src/com/cloud/utils/net/Ip4Address.java | 80 -
utils/src/com/cloud/utils/net/MacAddress.java | 367 -----
utils/src/com/cloud/utils/net/NetUtils.java | 1550 ------------------
utils/src/com/cloud/utils/net/NfsUtils.java | 55 -
utils/src/com/cloud/utils/net/UrlUtil.java | 63 -
.../src/com/cloud/utils/nio/HandlerFactory.java | 28 -
utils/src/com/cloud/utils/nio/Link.java | 567 -------
utils/src/com/cloud/utils/nio/NioClient.java | 125 --
.../src/com/cloud/utils/nio/NioConnection.java | 476 ------
utils/src/com/cloud/utils/nio/NioServer.java | 97 --
utils/src/com/cloud/utils/nio/Task.java | 89 -
.../com/cloud/utils/nio/TrustAllManager.java | 45 -
.../BasicEncodedRESTValidationStrategy.java | 66 -
.../utils/rest/CloudstackRESTException.java | 39 -
.../cloud/utils/rest/RESTServiceConnector.java | 395 -----
.../utils/rest/RESTValidationStrategy.java | 165 --
.../cloud/utils/script/OutputInterpreter.java | 141 --
utils/src/com/cloud/utils/script/Script.java | 502 ------
utils/src/com/cloud/utils/script/Script2.java | 70 -
.../cloud/utils/security/CertificateHelper.java | 166 --
utils/src/com/cloud/utils/ssh/SSHCmdHelper.java | 179 --
.../src/com/cloud/utils/ssh/SSHKeysHelper.java | 115 --
utils/src/com/cloud/utils/ssh/SshException.java | 30 -
utils/src/com/cloud/utils/ssh/SshHelper.java | 209 ---
.../storage/encoding/DecodedDataObject.java | 56 -
.../storage/encoding/DecodedDataStore.java | 68 -
.../cloud/utils/storage/encoding/Decoder.java | 66 -
.../utils/storage/encoding/EncodingType.java | 32 -
.../com/cloud/utils/time/InaccurateClock.java | 102 --
.../cloud/utils/time/InaccurateClockMBean.java | 28 -
.../com/cloud/utils/xmlobject/XmlObject.java | 214 ---
.../cloud/utils/xmlobject/XmlObjectParser.java | 128 --
.../src/main/java/com/cloud/maint/Version.java | 77 +
.../java/com/cloud/utils/ActionDelegate.java | 24 +
.../java/com/cloud/utils/AutoCloseableUtil.java | 36 +
.../com/cloud/utils/CloudResourceBundle.java | 48 +
.../com/cloud/utils/ConstantTimeComparator.java | 42 +
.../src/main/java/com/cloud/utils/DateUtil.java | 274 ++++
.../java/com/cloud/utils/EncryptionUtil.java | 73 +
.../main/java/com/cloud/utils/EnumUtils.java | 58 +
.../java/com/cloud/utils/ExecutionResult.java | 46 +
.../src/main/java/com/cloud/utils/FileUtil.java | 32 +
.../main/java/com/cloud/utils/HttpUtils.java | 114 ++
.../main/java/com/cloud/utils/IteratorUtil.java | 72 +
.../src/main/java/com/cloud/utils/Journal.java | 104 ++
.../src/main/java/com/cloud/utils/LogUtils.java | 45 +
.../java/com/cloud/utils/MethodCapturer.java | 113 ++
.../main/java/com/cloud/utils/NumbersUtil.java | 139 ++
utils/src/main/java/com/cloud/utils/Pair.java | 87 +
.../java/com/cloud/utils/PasswordGenerator.java | 90 +
.../main/java/com/cloud/utils/Predicate.java | 24 +
.../main/java/com/cloud/utils/ProcessUtil.java | 112 ++
.../src/main/java/com/cloud/utils/Profiler.java | 91 +
.../java/com/cloud/utils/PropertiesUtil.java | 196 +++
.../main/java/com/cloud/utils/ReflectUtil.java | 213 +++
.../java/com/cloud/utils/ReflectionUse.java | 31 +
.../src/main/java/com/cloud/utils/S3Utils.java | 603 +++++++
.../java/com/cloud/utils/SerialVersionUID.java | 69 +
.../main/java/com/cloud/utils/StringUtils.java | 323 ++++
.../main/java/com/cloud/utils/SwiftUtil.java | 239 +++
.../src/main/java/com/cloud/utils/Ternary.java | 85 +
.../src/main/java/com/cloud/utils/UriUtils.java | 394 +++++
.../cloud/utils/UsernamePasswordValidator.java | 49 +
.../main/java/com/cloud/utils/UuidUtils.java | 34 +
.../cloud/utils/backoff/BackoffAlgorithm.java | 38 +
.../utils/backoff/impl/ConstantTimeBackoff.java | 102 ++
.../backoff/impl/ConstantTimeBackoffMBean.java | 35 +
.../utils/cisco/n1kv/vsm/NetconfHelper.java | 355 ++++
.../cloud/utils/cisco/n1kv/vsm/PolicyMap.java | 34 +
.../cloud/utils/cisco/n1kv/vsm/PortProfile.java | 48 +
.../cloud/utils/cisco/n1kv/vsm/VsmCommand.java | 999 +++++++++++
.../utils/cisco/n1kv/vsm/VsmOkResponse.java | 44 +
.../cisco/n1kv/vsm/VsmPolicyMapResponse.java | 84 +
.../cisco/n1kv/vsm/VsmPortProfileResponse.java | 166 ++
.../cloud/utils/cisco/n1kv/vsm/VsmResponse.java | 222 +++
.../java/com/cloud/utils/component/Adapter.java | 27 +
.../com/cloud/utils/component/AdapterBase.java | 40 +
.../com/cloud/utils/component/AdapterList.java | 37 +
.../cloud/utils/component/ComponentContext.java | 282 ++++
.../ComponentInstantiationPostProcessor.java | 149 ++
.../utils/component/ComponentLifecycle.java | 64 +
.../utils/component/ComponentLifecycleBase.java | 87 +
.../component/ComponentMethodInterceptable.java | 27 +
.../component/ComponentMethodInterceptor.java | 32 +
.../utils/component/ComponentNamingPolicy.java | 65 +
.../java/com/cloud/utils/component/Manager.java | 27 +
.../com/cloud/utils/component/ManagerBase.java | 28 +
.../java/com/cloud/utils/component/Named.java | 26 +
.../cloud/utils/component/PluggableService.java | 29 +
.../com/cloud/utils/component/Registry.java | 51 +
.../utils/component/SystemIntegrityChecker.java | 30 +
.../utils/concurrency/NamedThreadFactory.java | 38 +
.../com/cloud/utils/concurrency/Scheduler.java | 31 +
.../utils/concurrency/SynchronizationEvent.java | 89 +
.../com/cloud/utils/concurrency/TestClock.java | 161 ++
.../com/cloud/utils/crypt/DBEncryptionUtil.java | 87 +
.../utils/crypt/EncryptionSecretKeyChecker.java | 146 ++
.../utils/crypt/EncryptionSecretKeySender.java | 65 +
.../java/com/cloud/utils/crypt/RSAHelper.java | 90 +
.../java/com/cloud/utils/db/DbProperties.java | 109 ++
.../java/com/cloud/utils/db/EntityManager.java | 84 +
.../java/com/cloud/utils/db/UUIDManager.java | 48 +
.../com/cloud/utils/encoding/URLEncoder.java | 113 ++
.../java/com/cloud/utils/events/EventArgs.java | 44 +
.../com/cloud/utils/events/SubscriptionMgr.java | 164 ++
.../utils/exception/CSExceptionErrorCode.java | 100 ++
.../utils/exception/CloudRuntimeException.java | 141 ++
.../com/cloud/utils/exception/ErrorContext.java | 31 +
.../utils/exception/ExceptionProxyObject.java | 55 +
.../cloud/utils/exception/ExceptionUtil.java | 54 +
.../utils/exception/ExecutionException.java | 49 +
.../HypervisorVersionChangedException.java | 35 +
.../java/com/cloud/utils/fsm/ChangeEvent.java | 24 +
.../java/com/cloud/utils/fsm/FiniteState.java | 58 +
.../java/com/cloud/utils/fsm/FiniteState2.java | 34 +
.../com/cloud/utils/fsm/FiniteStateObject.java | 25 +
.../cloud/utils/fsm/NoTransitionException.java | 36 +
.../main/java/com/cloud/utils/fsm/State.java | 27 +
.../main/java/com/cloud/utils/fsm/StateDao.java | 25 +
.../java/com/cloud/utils/fsm/StateListener.java | 43 +
.../java/com/cloud/utils/fsm/StateMachine.java | 147 ++
.../java/com/cloud/utils/fsm/StateMachine2.java | 261 +++
.../java/com/cloud/utils/fsm/StateObject.java | 27 +
.../main/java/com/cloud/utils/mgmt/JmxUtil.java | 90 +
.../com/cloud/utils/mgmt/ManagementBean.java | 27 +
.../utils/mgmt/PropertyMapDynamicBean.java | 120 ++
utils/src/main/java/com/cloud/utils/net/Ip.java | 98 ++
.../java/com/cloud/utils/net/Ip4Address.java | 80 +
.../java/com/cloud/utils/net/MacAddress.java | 367 +++++
.../main/java/com/cloud/utils/net/NetUtils.java | 1550 ++++++++++++++++++
.../main/java/com/cloud/utils/net/NfsUtils.java | 55 +
.../main/java/com/cloud/utils/net/UrlUtil.java | 63 +
.../com/cloud/utils/nio/HandlerFactory.java | 28 +
.../src/main/java/com/cloud/utils/nio/Link.java | 567 +++++++
.../java/com/cloud/utils/nio/NioClient.java | 125 ++
.../java/com/cloud/utils/nio/NioConnection.java | 476 ++++++
.../java/com/cloud/utils/nio/NioServer.java | 97 ++
.../src/main/java/com/cloud/utils/nio/Task.java | 89 +
.../com/cloud/utils/nio/TrustAllManager.java | 45 +
.../BasicEncodedRESTValidationStrategy.java | 66 +
.../utils/rest/CloudstackRESTException.java | 39 +
.../cloud/utils/rest/RESTServiceConnector.java | 395 +++++
.../utils/rest/RESTValidationStrategy.java | 165 ++
.../cloud/utils/script/OutputInterpreter.java | 141 ++
.../java/com/cloud/utils/script/Script.java | 502 ++++++
.../java/com/cloud/utils/script/Script2.java | 70 +
.../cloud/utils/security/CertificateHelper.java | 166 ++
.../java/com/cloud/utils/ssh/SSHCmdHelper.java | 179 ++
.../java/com/cloud/utils/ssh/SSHKeysHelper.java | 115 ++
.../java/com/cloud/utils/ssh/SshException.java | 30 +
.../java/com/cloud/utils/ssh/SshHelper.java | 209 +++
.../storage/encoding/DecodedDataObject.java | 56 +
.../storage/encoding/DecodedDataStore.java | 68 +
.../cloud/utils/storage/encoding/Decoder.java | 66 +
.../utils/storage/encoding/EncodingType.java | 32 +
.../com/cloud/utils/time/InaccurateClock.java | 102 ++
.../cloud/utils/time/InaccurateClockMBean.java | 28 +
.../com/cloud/utils/xmlobject/XmlObject.java | 214 +++
.../cloud/utils/xmlobject/XmlObjectParser.java | 128 ++
.../utils/baremetal/BaremetalUtils.java | 24 +
.../utils/graphite/GraphiteClient.java | 123 ++
.../utils/graphite/GraphiteException.java | 31 +
.../utils/identity/ManagementServerNode.java | 63 +
.../utils/imagestore/ImageStoreUtil.java | 110 ++
.../cloudstack/utils/security/SSLUtils.java | 58 +
.../utils/security/SecureSSLSocketFactory.java | 124 ++
.../cloudstack/utils/usage/UsageUtils.java | 24 +
.../ssl/EasySSLProtocolSocketFactory.java | 210 +++
.../contrib/ssl/EasyX509TrustManager.java | 110 ++
utils/src/main/resources/cloud.keystore | Bin 0 -> 1316 bytes
.../utils/baremetal/BaremetalUtils.java | 24 -
.../utils/graphite/GraphiteClient.java | 123 --
.../utils/graphite/GraphiteException.java | 31 -
.../utils/identity/ManagementServerNode.java | 63 -
.../utils/imagestore/ImageStoreUtil.java | 110 --
.../cloudstack/utils/security/SSLUtils.java | 58 -
.../utils/security/SecureSSLSocketFactory.java | 124 --
.../cloudstack/utils/usage/UsageUtils.java | 24 -
.../ssl/EasySSLProtocolSocketFactory.java | 210 ---
.../contrib/ssl/EasyX509TrustManager.java | 110 --
.../test/java/com/cloud/utils/DateUtilTest.java | 60 +
.../test/java/com/cloud/utils/DummyImpl.java | 31 +
.../java/com/cloud/utils/DummyInterface.java | 24 +
.../java/com/cloud/utils/DummyPremiumImpl.java | 28 +
.../java/com/cloud/utils/HttpUtilsTest.java | 94 ++
.../java/com/cloud/utils/NumbersUtilTest.java | 47 +
.../com/cloud/utils/PasswordGeneratorTest.java | 42 +
.../java/com/cloud/utils/ProcessUtilTest.java | 76 +
.../com/cloud/utils/PropertiesUtilsTest.java | 64 +
.../java/com/cloud/utils/ReflectUtilTest.java | 148 ++
.../test/java/com/cloud/utils/ScriptTest.java | 135 ++
.../java/com/cloud/utils/StringUtilsTest.java | 253 +++
.../test/java/com/cloud/utils/TernaryTest.java | 34 +
.../test/java/com/cloud/utils/TestProfiler.java | 116 ++
.../test/java/com/cloud/utils/UriUtilsTest.java | 60 +
.../java/com/cloud/utils/UuidUtilsTest.java | 42 +
.../backoff/impl/ConstantTimeBackoffTest.java | 112 ++
.../crypto/EncryptionSecretKeyCheckerTest.java | 45 +
.../com/cloud/utils/crypto/RSAHelperTest.java | 54 +
.../cloud/utils/encoding/UrlEncoderTest.java | 33 +
.../utils/exception/ExceptionUtilTest.java | 52 +
.../com/cloud/utils/net/Ip4AddressTest.java | 40 +
.../test/java/com/cloud/utils/net/IpTest.java | 63 +
.../com/cloud/utils/net/MacAddressTest.java | 60 +
.../java/com/cloud/utils/net/NetUtilsTest.java | 421 +++++
.../utils/rest/RESTServiceConnectorTest.java | 395 +++++
.../com/cloud/utils/ssh/SSHKeysHelperTest.java | 73 +
.../utils/testcase/Log4jEnabledTestCase.java | 58 +
.../java/com/cloud/utils/testcase/NioTest.java | 216 +++
.../cloud/utils/xmlobject/TestXmlObject.java | 53 +
.../cloud/utils/xmlobject/TestXmlObject2.java | 54 +
.../utils/imagestore/ImageStoreUtilTest.java | 54 +
.../com/cloud/utils/QualifierTestContext.xml | 38 +
.../utils/db/transactionContextBuilderTest.xml | 48 +
utils/src/test/resources/log4j.xml | 118 ++
utils/src/test/resources/testContext.xml | 52 +
utils/test/com/cloud/utils/DateUtilTest.java | 60 -
utils/test/com/cloud/utils/DummyImpl.java | 31 -
utils/test/com/cloud/utils/DummyInterface.java | 24 -
.../test/com/cloud/utils/DummyPremiumImpl.java | 28 -
utils/test/com/cloud/utils/HttpUtilsTest.java | 94 --
utils/test/com/cloud/utils/NumbersUtilTest.java | 47 -
.../com/cloud/utils/PasswordGeneratorTest.java | 42 -
utils/test/com/cloud/utils/ProcessUtilTest.java | 76 -
.../com/cloud/utils/PropertiesUtilsTest.java | 64 -
utils/test/com/cloud/utils/ReflectUtilTest.java | 148 --
utils/test/com/cloud/utils/ScriptTest.java | 135 --
utils/test/com/cloud/utils/StringUtilsTest.java | 253 ---
utils/test/com/cloud/utils/TernaryTest.java | 34 -
utils/test/com/cloud/utils/TestProfiler.java | 116 --
utils/test/com/cloud/utils/UriUtilsTest.java | 60 -
utils/test/com/cloud/utils/UuidUtilsTest.java | 42 -
.../backoff/impl/ConstantTimeBackoffTest.java | 112 --
.../crypto/EncryptionSecretKeyCheckerTest.java | 45 -
.../com/cloud/utils/crypto/RSAHelperTest.java | 54 -
.../cloud/utils/encoding/UrlEncoderTest.java | 33 -
.../utils/exception/ExceptionUtilTest.java | 52 -
.../com/cloud/utils/net/Ip4AddressTest.java | 40 -
utils/test/com/cloud/utils/net/IpTest.java | 63 -
.../com/cloud/utils/net/MacAddressTest.java | 60 -
.../test/com/cloud/utils/net/NetUtilsTest.java | 421 -----
.../utils/rest/RESTServiceConnectorTest.java | 395 -----
.../com/cloud/utils/ssh/SSHKeysHelperTest.java | 73 -
.../utils/testcase/Log4jEnabledTestCase.java | 58 -
.../test/com/cloud/utils/testcase/NioTest.java | 216 ---
.../cloud/utils/xmlobject/TestXmlObject.java | 53 -
.../cloud/utils/xmlobject/TestXmlObject2.java | 54 -
.../utils/imagestore/ImageStoreUtilTest.java | 54 -
.../com/cloud/utils/QualifierTestContext.xml | 38 -
.../utils/db/transactionContextBuilderTest.xml | 48 -
utils/test/resources/log4j.xml | 118 --
utils/test/resources/testContext.xml | 52 -
350 files changed, 20350 insertions(+), 20426 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/certs/cloud.keystore
----------------------------------------------------------------------
diff --git a/utils/certs/cloud.keystore b/utils/certs/cloud.keystore
deleted file mode 100644
index 33d7777..0000000
Binary files a/utils/certs/cloud.keystore and /dev/null differ
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/pom.xml
----------------------------------------------------------------------
diff --git a/utils/pom.xml b/utils/pom.xml
index 937dc08..d01f6ff 100755
--- a/utils/pom.xml
+++ b/utils/pom.xml
@@ -18,7 +18,8 @@
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/xsd/maven-4.0.0.xsd">
+<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-utils</artifactId>
<name>Apache CloudStack Utils</name>
@@ -96,8 +97,8 @@
<artifactId>ejb-api</artifactId>
</dependency>
<dependency>
- <groupId>com.googlecode.java-ipv6</groupId>
- <artifactId>java-ipv6</artifactId>
+ <groupId>com.googlecode.java-ipv6</groupId>
+ <artifactId>java-ipv6</artifactId>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
@@ -115,10 +116,10 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <scope>provided</scope>
- <version>${cs.commons-io.version}</version>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <scope>provided</scope>
+ <version>${cs.commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
@@ -154,9 +155,9 @@
<version>${cs.opensaml.version}</version>
</dependency>
<dependency>
- <groupId>commons-net</groupId>
- <artifactId>commons-net</artifactId>
- <version>3.3</version>
+ <groupId>commons-net</groupId>
+ <artifactId>commons-net</artifactId>
+ <version>3.3</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
@@ -169,6 +170,20 @@
</dependency>
</dependencies>
<build>
+ <sourceDirectory>src/main/java</sourceDirectory>
+ <testSourceDirectory>src/test/java</testSourceDirectory>
+ <outputDirectory>target/classes</outputDirectory>
+ <testOutputDirectory>target/test-classes</testOutputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ </resource>
+ </resources>
+ <testResources>
+ <testResource>
+ <directory>src/test/resources</directory>
+ </testResource>
+ </testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -191,15 +206,9 @@
<exclude>com/cloud/utils/testcase/NioTest.java</exclude>
</excludes>
</configuration>
- </plugin>
+ </plugin>
</plugins>
- <resources>
- <resource>
- <directory>certs</directory>
- </resource>
- </resources>
</build>
-
<profiles>
<profile>
<id>integration</id>
@@ -221,5 +230,4 @@
</build>
</profile>
</profiles>
-
</project>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/maint/Version.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/maint/Version.java b/utils/src/com/cloud/maint/Version.java
deleted file mode 100644
index 925806e..0000000
--- a/utils/src/com/cloud/maint/Version.java
+++ /dev/null
@@ -1,77 +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 com.cloud.maint;
-
-public class Version {
- /**
- * Compares two version strings and see which one is higher version.
- * @param ver1
- * @param ver2
- * @return positive if ver1 is higher. negative if ver1 is lower; zero if the same.
- */
- public static int compare(String ver1, String ver2) {
- String[] tokens1 = ver1.split("[.]");
- String[] tokens2 = ver2.split("[.]");
-// assert(tokens1.length <= tokens2.length);
-
- int compareLength = Math.min(tokens1.length, tokens2.length);
- for (int i = 0; i < compareLength; i++) {
- long version1 = Long.parseLong(tokens1[i]);
- long version2 = Long.parseLong(tokens2[i]);
- if (version1 != version2) {
- return version1 < version2 ? -1 : 1;
- }
- }
-
- if (tokens1.length > tokens2.length) {
- return 1;
- } else if (tokens1.length < tokens2.length) {
- return -1;
- }
-
- return 0;
- }
-
- public static String trimToPatch(String version) {
- int index = version.indexOf("-");
-
- if (index > 0)
- version = version.substring(0, index);
-
- String[] tokens = version.split("[.]");
-
- if (tokens.length < 3)
- return "0";
- return tokens[0] + "." + tokens[1] + "." + tokens[2];
- }
-
- public static String trimRouterVersion(String version) {
- String[] tokens = version.split(" ");
- if (tokens.length >= 3 && tokens[2].matches("[0-9]+(\\.[0-9]+)*")) {
- return tokens[2];
- }
- return "0";
- }
-
- public static void main(String[] args) {
- System.out.println("Result is " + compare(args[0], args[1]));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ActionDelegate.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ActionDelegate.java b/utils/src/com/cloud/utils/ActionDelegate.java
deleted file mode 100644
index 02f76d9..0000000
--- a/utils/src/com/cloud/utils/ActionDelegate.java
+++ /dev/null
@@ -1,24 +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 com.cloud.utils;
-
-public interface ActionDelegate<T> {
- void action(T param);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/AutoCloseableUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/AutoCloseableUtil.java b/utils/src/com/cloud/utils/AutoCloseableUtil.java
deleted file mode 100644
index f93265b..0000000
--- a/utils/src/com/cloud/utils/AutoCloseableUtil.java
+++ /dev/null
@@ -1,36 +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 com.cloud.utils;
-
-import org.apache.log4j.Logger;
-
-public class AutoCloseableUtil {
- private final static Logger s_logger = Logger.getLogger(AutoCloseableUtil.class);
-
- public static void closeAutoCloseable(AutoCloseable ac, String message) {
- try {
-
- if (ac != null) {
- ac.close();
- }
-
- } catch (Exception e) {
- s_logger.warn("[ignored] " + message, e);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/CloudResourceBundle.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/CloudResourceBundle.java b/utils/src/com/cloud/utils/CloudResourceBundle.java
deleted file mode 100644
index cf27d79..0000000
--- a/utils/src/com/cloud/utils/CloudResourceBundle.java
+++ /dev/null
@@ -1,48 +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 com.cloud.utils;
-
-import java.util.Locale;
-import java.util.ResourceBundle;
-
-public class CloudResourceBundle {
-
- private ResourceBundle _bundle;
-
- public CloudResourceBundle(ResourceBundle bundle) {
- _bundle = bundle;
- }
-
- public static CloudResourceBundle getBundle(String baseName, Locale locale) {
- return new CloudResourceBundle(ResourceBundle.getBundle(baseName, locale));
- }
-
- private String getString(String key) {
- try {
- return _bundle.getString(key);
- } catch (Exception e) {
- return key; //if translation is not found, just return original word (i.e. English).
- }
- }
-
- public String t(String key) {
- return getString(key);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ConstantTimeComparator.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ConstantTimeComparator.java b/utils/src/com/cloud/utils/ConstantTimeComparator.java
deleted file mode 100644
index baf2bc2..0000000
--- a/utils/src/com/cloud/utils/ConstantTimeComparator.java
+++ /dev/null
@@ -1,42 +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 com.cloud.utils;
-
-import java.nio.charset.Charset;
-
-public class ConstantTimeComparator {
-
- public static boolean compareBytes(byte[] b1, byte[] b2) {
- if (b1.length != b2.length) {
- return false;
- }
-
- int result = 0;
- for (int i = 0; i < b1.length; i++) {
- result |= b1[i] ^ b2[i];
- }
- return result == 0;
- }
-
- public static boolean compareStrings(String s1, String s2) {
- final Charset encoding = Charset.forName("UTF-8");
- return compareBytes(s1.getBytes(encoding), s2.getBytes(encoding));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/DateUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/DateUtil.java b/utils/src/com/cloud/utils/DateUtil.java
deleted file mode 100644
index 7787e1b..0000000
--- a/utils/src/com/cloud/utils/DateUtil.java
+++ /dev/null
@@ -1,274 +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 com.cloud.utils;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.TimeZone;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class DateUtil {
- public static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
- public static final String YYYYMMDD_FORMAT = "yyyyMMddHHmmss";
- private static final DateFormat s_outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-
- public static Date currentGMTTime() {
- // Date object always stores miliseconds offset based on GMT internally
- return new Date();
- }
-
- // yyyy-MM-ddTHH:mm:ssZxxxx
- public static Date parseTZDateString(String str) throws ParseException {
- DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z");
- return dfParse.parse(str);
- }
-
- public static Date parseDateString(TimeZone tz, String dateString) {
- return parseDateString(tz, dateString, "yyyy-MM-dd HH:mm:ss");
- }
-
- public static Date parseDateString(TimeZone tz, String dateString, String formatString) {
- DateFormat df = new SimpleDateFormat(formatString);
- df.setTimeZone(tz);
-
- try {
- return df.parse(dateString);
- } catch (ParseException e) {
- throw new CloudRuntimeException("why why ", e);
- }
- }
-
- public static String displayDateInTimezone(TimeZone tz, Date time) {
- return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss z");
- }
-
- public static String getDateDisplayString(TimeZone tz, Date time) {
- return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss");
- }
-
- public static String getDateDisplayString(TimeZone tz, Date time, String formatString) {
- DateFormat df = new SimpleDateFormat(formatString);
- df.setTimeZone(tz);
-
- return df.format(time);
- }
-
- public static String getOutputString(Date date) {
- if (date == null) {
- return "";
- }
- String formattedString = null;
- synchronized (s_outputFormat) {
- formattedString = s_outputFormat.format(date);
- }
- return formattedString;
- }
-
- public static Date now() {
- return new Date(System.currentTimeMillis());
- }
-
- public enum IntervalType {
- HOURLY, DAILY, WEEKLY, MONTHLY;
-
- boolean equals(String intervalType) {
- return super.toString().equalsIgnoreCase(intervalType);
- }
-
- public static IntervalType getIntervalType(String intervalTypeStr) {
- for (IntervalType intervalType : IntervalType.values()) {
- if (intervalType.equals(intervalTypeStr)) {
- return intervalType;
- }
- }
- return null;
- }
- }
-
- public static IntervalType getIntervalType(short type) {
- if (type < 0 || type >= IntervalType.values().length) {
- return null;
- }
- return IntervalType.values()[type];
- }
-
- /**
- * Return next run time
- * @param intervalType hourly/daily/weekly/monthly
- * @param schedule MM[:HH][:DD] format. DD is day of week for weekly and day of month for monthly
- * @param timezone The timezone in which the schedule string is specified
- * @param startDate if specified, returns next run time after the specified startDate
- * @return
- */
- public static Date getNextRunTime(IntervalType type, String schedule, String timezone, Date startDate) {
-
- String[] scheduleParts = schedule.split(":"); //MM:HH:DAY
-
- final Calendar scheduleTime = Calendar.getInstance();
- scheduleTime.setTimeZone(TimeZone.getTimeZone(timezone));
-
- if (startDate == null) {
- startDate = new Date();
- }
- scheduleTime.setTime(startDate);
- // Throw an ArrayIndexOutOfBoundsException if schedule is badly formatted.
- scheduleTime.setLenient(false);
- int minutes = 0;
- int hour = 0;
- int day = 0;
- Date execDate = null;
-
- switch (type) {
- case HOURLY:
- if (scheduleParts.length < 1) {
- throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
- }
- minutes = Integer.parseInt(scheduleParts[0]);
- scheduleTime.set(Calendar.MINUTE, minutes);
- scheduleTime.set(Calendar.SECOND, 0);
- scheduleTime.set(Calendar.MILLISECOND, 0);
- try {
- execDate = scheduleTime.getTime();
- } catch (IllegalArgumentException ex) {
- scheduleTime.setLenient(true);
- execDate = scheduleTime.getTime();
- scheduleTime.setLenient(false);
- }
- // XXX: !execDate.after(startDate) is strictly for testing.
- // During testing we use a test clock which runs much faster than the real clock
- // So startDate and execDate will always be ahead in the future
- // and we will never increase the time here
- if (execDate.before(new Date()) || !execDate.after(startDate)) {
- scheduleTime.add(Calendar.HOUR_OF_DAY, 1);
- }
- break;
- case DAILY:
- if (scheduleParts.length < 2) {
- throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
- }
- minutes = Integer.parseInt(scheduleParts[0]);
- hour = Integer.parseInt(scheduleParts[1]);
-
- scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
- scheduleTime.set(Calendar.MINUTE, minutes);
- scheduleTime.set(Calendar.SECOND, 0);
- scheduleTime.set(Calendar.MILLISECOND, 0);
- try {
- execDate = scheduleTime.getTime();
- } catch (IllegalArgumentException ex) {
- scheduleTime.setLenient(true);
- execDate = scheduleTime.getTime();
- scheduleTime.setLenient(false);
- }
- // XXX: !execDate.after(startDate) is strictly for testing.
- // During testing we use a test clock which runs much faster than the real clock
- // So startDate and execDate will always be ahead in the future
- // and we will never increase the time here
- if (execDate.before(new Date()) || !execDate.after(startDate)) {
- scheduleTime.add(Calendar.DAY_OF_YEAR, 1);
- }
- break;
- case WEEKLY:
- if (scheduleParts.length < 3) {
- throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
- }
- minutes = Integer.parseInt(scheduleParts[0]);
- hour = Integer.parseInt(scheduleParts[1]);
- day = Integer.parseInt(scheduleParts[2]);
- scheduleTime.set(Calendar.DAY_OF_WEEK, day);
- scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
- scheduleTime.set(Calendar.MINUTE, minutes);
- scheduleTime.set(Calendar.SECOND, 0);
- scheduleTime.set(Calendar.MILLISECOND, 0);
- try {
- execDate = scheduleTime.getTime();
- } catch (IllegalArgumentException ex) {
- scheduleTime.setLenient(true);
- execDate = scheduleTime.getTime();
- scheduleTime.setLenient(false);
- }
- // XXX: !execDate.after(startDate) is strictly for testing.
- // During testing we use a test clock which runs much faster than the real clock
- // So startDate and execDate will always be ahead in the future
- // and we will never increase the time here
- if (execDate.before(new Date()) || !execDate.after(startDate)) {
- scheduleTime.add(Calendar.DAY_OF_WEEK, 7);
- }
- ;
- break;
- case MONTHLY:
- if (scheduleParts.length < 3) {
- throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
- }
- minutes = Integer.parseInt(scheduleParts[0]);
- hour = Integer.parseInt(scheduleParts[1]);
- day = Integer.parseInt(scheduleParts[2]);
- if (day > 28) {
- throw new CloudRuntimeException("Day cannot be greater than 28 for monthly schedule");
- }
- scheduleTime.set(Calendar.DAY_OF_MONTH, day);
- scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
- scheduleTime.set(Calendar.MINUTE, minutes);
- scheduleTime.set(Calendar.SECOND, 0);
- scheduleTime.set(Calendar.MILLISECOND, 0);
- try {
- execDate = scheduleTime.getTime();
- } catch (IllegalArgumentException ex) {
- scheduleTime.setLenient(true);
- execDate = scheduleTime.getTime();
- scheduleTime.setLenient(false);
- }
- // XXX: !execDate.after(startDate) is strictly for testing.
- // During testing we use a test clock which runs much faster than the real clock
- // So startDate and execDate will always be ahead in the future
- // and we will never increase the time here
- if (execDate.before(new Date()) || !execDate.after(startDate)) {
- scheduleTime.add(Calendar.MONTH, 1);
- }
- break;
- default:
- throw new CloudRuntimeException("Incorrect interval: " + type.toString());
- }
-
- try {
- return scheduleTime.getTime();
- } catch (IllegalArgumentException ex) {
- scheduleTime.setLenient(true);
- Date nextScheduledDate = scheduleTime.getTime();
- scheduleTime.setLenient(false);
- return nextScheduledDate;
- }
- }
-
- public static long getTimeDifference(Date date1, Date date2){
-
- Calendar dateCalendar1 = Calendar.getInstance();
- dateCalendar1.setTime(date1);
- Calendar dateCalendar2 = Calendar.getInstance();
- dateCalendar2.setTime(date2);
-
- return (dateCalendar1.getTimeInMillis() - dateCalendar2.getTimeInMillis() )/1000;
-
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/EncryptionUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/EncryptionUtil.java b/utils/src/com/cloud/utils/EncryptionUtil.java
deleted file mode 100644
index b82842e..0000000
--- a/utils/src/com/cloud/utils/EncryptionUtil.java
+++ /dev/null
@@ -1,73 +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 com.cloud.utils;
-
-import java.io.UnsupportedEncodingException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-
-import javax.crypto.Mac;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-import org.jasypt.encryption.pbe.PBEStringEncryptor;
-import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class EncryptionUtil {
- public static final Logger s_logger = Logger.getLogger(EncryptionUtil.class.getName());
- private static PBEStringEncryptor encryptor;
-
- private static void initialize(String key) {
- StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
- standardPBEStringEncryptor.setAlgorithm("PBEWITHSHA1ANDDESEDE");
- standardPBEStringEncryptor.setPassword(key);
- encryptor = standardPBEStringEncryptor;
- }
-
- public static String encodeData(String data, String key) {
- if (encryptor == null) {
- initialize(key);
- }
- return encryptor.encrypt(data);
- }
-
- public static String decodeData(String encodedData, String key) {
- if (encryptor == null) {
- initialize(key);
- }
- return encryptor.decrypt(encodedData);
- }
-
- public static String generateSignature(String data, String key) {
- try {
- final Mac mac = Mac.getInstance("HmacSHA1");
- final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
- mac.init(keySpec);
- mac.update(data.getBytes("UTF-8"));
- final byte[] encryptedBytes = mac.doFinal();
- return Base64.encodeBase64String(encryptedBytes);
- } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
- s_logger.error("exception occurred which encoding the data." + e.getMessage());
- throw new CloudRuntimeException("unable to generate signature", e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/EnumUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/EnumUtils.java b/utils/src/com/cloud/utils/EnumUtils.java
deleted file mode 100644
index 02b6a25..0000000
--- a/utils/src/com/cloud/utils/EnumUtils.java
+++ /dev/null
@@ -1,58 +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 com.cloud.utils;
-
-public class EnumUtils {
- public static String listValues(Enum<?>[] enums) {
- StringBuilder b = new StringBuilder("[");
-
- for (Enum<?> e : enums) {
- b.append(e).append(", ");
- }
- b.append("]");
- return b.toString();
- }
-
- public static <T extends Enum<T>> T fromString(Class<T> clz, String value, T defaultVal) {
- assert (clz != null);
-
- if (value != null) {
- try {
- return Enum.valueOf(clz, value.trim());
- } catch (IllegalArgumentException ex) {
- assert (false);
- }
- }
- return defaultVal;
- }
-
- public static <T extends Enum<T>> T fromString(Class<T> clz, String value) {
- assert (clz != null);
-
- if (value != null) {
- try {
- return Enum.valueOf(clz, value.trim());
- } catch (IllegalArgumentException ex) {
- assert (false);
- }
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ExecutionResult.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ExecutionResult.java b/utils/src/com/cloud/utils/ExecutionResult.java
deleted file mode 100644
index c8b620a..0000000
--- a/utils/src/com/cloud/utils/ExecutionResult.java
+++ /dev/null
@@ -1,46 +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 com.cloud.utils;
-
-public class ExecutionResult {
- private Boolean success;
- private String details;
-
- public ExecutionResult(Boolean success, String details) {
- this.success = success;
- this.details = details;
- }
-
- public Boolean isSuccess() {
- return success;
- }
-
- public void setSuccess(Boolean success) {
- this.success = success;
- }
-
- public String getDetails() {
- return details;
- }
-
- public void setDetails(String details) {
- this.details = details;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/FileUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/FileUtil.java b/utils/src/com/cloud/utils/FileUtil.java
deleted file mode 100644
index c55dd74..0000000
--- a/utils/src/com/cloud/utils/FileUtil.java
+++ /dev/null
@@ -1,32 +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 com.cloud.utils;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.commons.io.FileUtils;
-
-public class FileUtil {
-
- public static void copyfile(File source, File destination) throws IOException {
- FileUtils.copyFile(source, destination);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/HttpUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/HttpUtils.java b/utils/src/com/cloud/utils/HttpUtils.java
deleted file mode 100644
index d2e844a..0000000
--- a/utils/src/com/cloud/utils/HttpUtils.java
+++ /dev/null
@@ -1,114 +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 com.cloud.utils;
-
-import org.apache.log4j.Logger;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-import java.io.IOException;
-import java.util.Map;
-
-public class HttpUtils {
-
- public static final Logger s_logger = Logger.getLogger(HttpUtils.class);
-
- public static final String UTF_8 = "UTF-8";
- public static final String RESPONSE_TYPE_JSON = "json";
- public static final String RESPONSE_TYPE_XML = "xml";
- public static final String JSON_CONTENT_TYPE = "application/json; charset=UTF-8";
- public static final String XML_CONTENT_TYPE = "text/xml; charset=UTF-8";
-
- public static void addSecurityHeaders(final HttpServletResponse resp) {
- if (resp.containsHeader("X-Content-Type-Options")) {
- resp.setHeader("X-Content-Type-Options", "nosniff");
- }
- else {
- resp.addHeader("X-Content-Type-Options", "nosniff");
- }
- if (resp.containsHeader("X-XSS-Protection")) {
- resp.setHeader("X-XSS-Protection", "1;mode=block");
- }
- else {
- resp.addHeader("X-XSS-Protection", "1;mode=block");
- }
- }
-
- public static void writeHttpResponse(final HttpServletResponse resp, final String response,
- final Integer responseCode, final String responseType, final String jsonContentType) {
- try {
- if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
- if (jsonContentType != null && !jsonContentType.isEmpty()) {
- resp.setContentType(jsonContentType);
- } else {
- resp.setContentType(JSON_CONTENT_TYPE);
- }
- } else if (RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)){
- resp.setContentType(XML_CONTENT_TYPE);
- }
- if (responseCode != null) {
- resp.setStatus(responseCode);
- }
- addSecurityHeaders(resp);
- resp.getWriter().print(response);
- } catch (final IOException ioex) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Exception writing http response: " + ioex);
- }
- } catch (final Exception ex) {
- if (!(ex instanceof IllegalStateException)) {
- s_logger.error("Unknown exception writing http response", ex);
- }
- }
- }
-
- public static String findCookie(final Cookie[] cookies, final String key) {
- if (cookies == null || key == null || key.isEmpty()) {
- return null;
- }
- for (Cookie cookie: cookies) {
- if (cookie != null && cookie.getName().equals(key)) {
- return cookie.getValue();
- }
- }
- return null;
- }
-
- public static boolean validateSessionKey(final HttpSession session, final Map<String, Object[]> params, final Cookie[] cookies, final String sessionKeyString) {
- if (session == null || sessionKeyString == null) {
- return false;
- }
- final String sessionKey = (String) session.getAttribute(sessionKeyString);
- final String sessionKeyFromCookie = HttpUtils.findCookie(cookies, sessionKeyString);
- String[] sessionKeyFromParams = null;
- if (params != null) {
- sessionKeyFromParams = (String[]) params.get(sessionKeyString);
- }
- if ((sessionKey == null)
- || (sessionKeyFromParams == null && sessionKeyFromCookie == null)
- || (sessionKeyFromParams != null && !sessionKey.equals(sessionKeyFromParams[0]))
- || (sessionKeyFromCookie != null && !sessionKey.equals(sessionKeyFromCookie))) {
- return false;
- }
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/IteratorUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/IteratorUtil.java b/utils/src/com/cloud/utils/IteratorUtil.java
deleted file mode 100644
index 8ab88f5..0000000
--- a/utils/src/com/cloud/utils/IteratorUtil.java
+++ /dev/null
@@ -1,72 +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 com.cloud.utils;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-
-public class IteratorUtil {
- public static <T> Iterable<T> enumerationAsIterable(final Enumeration<T> e) {
- return new Iterable<T>() {
- @Override
- public Iterator<T> iterator() {
- return new Iterator<T>() {
- @Override
- public boolean hasNext() {
- return e.hasMoreElements();
- }
-
- @Override
- public T next() {
- return e.nextElement();
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
- };
- }
-
- public static <T> Enumeration<T> iteratorAsEnumeration(final Iterator<T> it) {
- return new Enumeration<T>() {
- @Override
- public boolean hasMoreElements() {
- return it.hasNext();
- }
-
- @Override
- public T nextElement() {
- return it.next();
- }
- };
- }
-
- public static <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
- List<T> list = new ArrayList<T>(c);
- java.util.Collections.sort(list);
- return list;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/Journal.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/Journal.java b/utils/src/com/cloud/utils/Journal.java
deleted file mode 100644
index e88dba3..0000000
--- a/utils/src/com/cloud/utils/Journal.java
+++ /dev/null
@@ -1,104 +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 com.cloud.utils;
-
-import java.util.ArrayList;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-
-/**
- * Journal is used to kept what has happened during a process so someone can track
- * what happens during a process.
- *
- */
-public class Journal {
- String _name;
- ArrayList<Pair<String, Object[]>> _entries;
-
- public Journal(String name) {
- _name = name;
- _entries = new ArrayList<Pair<String, Object[]>>();
- }
-
- final private void log(String msg, Object... params) {
- Pair<String, Object[]> entry = new Pair<String, Object[]>(msg, params);
- assert msg != null : "Message can not be null or else it's useless!";
- _entries.add(entry);
- }
-
- public void record(String msg, Object... params) {
- log(msg, params);
- }
-
- public void record(Logger logger, Level p, String msg, Object... params) {
- if (logger.isEnabledFor(p)) {
- StringBuilder buf = new StringBuilder();
- toString(buf, msg, params);
- String entry = buf.toString();
- log(entry);
- logger.log(p, entry);
- } else {
- log(msg, params);
- }
- }
-
- protected void toString(StringBuilder buf, String msg, Object[] params) {
- buf.append(msg);
- if (params != null) {
- buf.append(" - ");
- int i = 0;
- for (Object obj : params) {
- buf.append('P').append(i).append('=');
- buf.append(obj != null ? obj.toString() : "null");
- buf.append(", ");
- }
- buf.delete(buf.length() - 2, buf.length());
- }
- }
-
- public String toString(String separator) {
- StringBuilder buf = new StringBuilder(_name).append(": ");
- for (Pair<String, Object[]> entry : _entries) {
- toString(buf, entry.first(), entry.second());
- buf.append(separator);
- }
- return buf.toString();
- }
-
- @Override
- public String toString() {
- return toString("; ");
- }
-
- public static class LogJournal extends Journal {
- Logger _logger;
-
- public LogJournal(String name, Logger logger) {
- super(name);
- _logger = logger;
- }
-
- @Override
- public void record(String msg, Object... params) {
- record(_logger, Level.DEBUG, msg, params);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/LogUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/LogUtils.java b/utils/src/com/cloud/utils/LogUtils.java
deleted file mode 100644
index d86766c..0000000
--- a/utils/src/com/cloud/utils/LogUtils.java
+++ /dev/null
@@ -1,45 +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 com.cloud.utils;
-
-import java.io.File;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.xml.DOMConfigurator;
-
-public class LogUtils {
- public static final Logger s_logger = Logger.getLogger(LogUtils.class);
-
- public static void initLog4j(String log4jConfigFileName) {
- assert (log4jConfigFileName != null);
- File file = PropertiesUtil.findConfigFile(log4jConfigFileName);
- if (file != null) {
- s_logger.info("log4j configuration found at " + file.getAbsolutePath());
- DOMConfigurator.configureAndWatch(file.getAbsolutePath());
- } else {
- String nameWithoutExtension = log4jConfigFileName.substring(0, log4jConfigFileName.lastIndexOf('.'));
- file = PropertiesUtil.findConfigFile(nameWithoutExtension + ".properties");
- if (file != null) {
- s_logger.info("log4j configuration found at " + file.getAbsolutePath());
- DOMConfigurator.configureAndWatch(file.getAbsolutePath());
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/MethodCapturer.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/MethodCapturer.java b/utils/src/com/cloud/utils/MethodCapturer.java
deleted file mode 100644
index 655a45d..0000000
--- a/utils/src/com/cloud/utils/MethodCapturer.java
+++ /dev/null
@@ -1,113 +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 com.cloud.utils;
-
-import java.lang.reflect.Method;
-import java.util.WeakHashMap;
-
-import net.sf.cglib.proxy.Callback;
-import net.sf.cglib.proxy.CallbackFilter;
-import net.sf.cglib.proxy.Enhancer;
-import net.sf.cglib.proxy.MethodInterceptor;
-import net.sf.cglib.proxy.MethodProxy;
-
-/*
- * This helper class provides a way to retrieve Method in a strong-type way. It takes advantage of power of
- * Intelligent IDE(Eclipse) in code-editing
- *
- * DummyImpl dummy = new DummyImpl();
- * MethodCapturer<DummyImpl> capturer = MethodCapturer.capture(dummy);
- * Method method = capturer.get(capturer.instance().foo2());
- *
- */
-public class MethodCapturer<T> {
-
- private final static int CACHE_SIZE = 1024;
-
- private T _instance;
- private Method _method;
-
- private static WeakHashMap<Object, Object> s_cache = new WeakHashMap<Object, Object>();
-
- private MethodCapturer() {
- }
-
- @SuppressWarnings("unchecked")
- public static <T> MethodCapturer<T> capture(T obj) {
- synchronized (s_cache) {
- MethodCapturer<T> capturer = (MethodCapturer<T>)s_cache.get(obj);
- if (capturer != null) {
- return capturer;
- }
-
- final MethodCapturer<T> capturerNew = new MethodCapturer<T>();
-
- Enhancer en = new Enhancer();
- en.setSuperclass(obj.getClass());
- en.setCallbacks(new Callback[] {new MethodInterceptor() {
- @Override
- public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
- capturerNew.setMethod(arg1);
- return null;
- }
- }, new MethodInterceptor() {
- @Override
- public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
- return null;
- }
- }});
- en.setCallbackFilter(new CallbackFilter() {
- @Override
- public int accept(Method method) {
- if (method.getParameterTypes().length == 0 && method.getName().equals("finalize")) {
- return 1;
- }
- return 0;
- }
- });
-
- capturerNew.setInstance((T)en.create());
-
- // We expect MethodCapturer is only used for singleton objects here, so we only maintain a limited cache
- // here
- if (s_cache.size() < CACHE_SIZE) {
- s_cache.put(obj, capturerNew);
- }
-
- return capturerNew;
- }
- }
-
- public T instance() {
- return _instance;
- }
-
- private void setInstance(T instance) {
- _instance = instance;
- }
-
- public Method get(Object... useless) {
- return _method;
- }
-
- private void setMethod(Method method) {
- _method = method;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/NumbersUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/NumbersUtil.java b/utils/src/com/cloud/utils/NumbersUtil.java
deleted file mode 100644
index 8b93a40..0000000
--- a/utils/src/com/cloud/utils/NumbersUtil.java
+++ /dev/null
@@ -1,139 +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 com.cloud.utils;
-
-import java.nio.ByteBuffer;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Formatter;
-import java.util.Locale;
-
-import org.apache.commons.lang.math.NumberUtils;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class NumbersUtil {
- public static long parseLong(String s, long defaultValue) {
- return NumberUtils.toLong(s, defaultValue);
- }
-
- public static int parseInt(String s, int defaultValue) {
- return NumberUtils.toInt(s, defaultValue);
- }
-
- public static float parseFloat(String s, float defaultValue) {
- return NumberUtils.toFloat(s, defaultValue);
- }
-
- /**
- * Converts bytes to long on input.
- */
- public static long bytesToLong(byte b[]) {
- return bytesToLong(b, 0);
- }
-
- public static long bytesToLong(byte b[], int pos) {
- return ByteBuffer.wrap(b, pos, 8).getLong();
- }
-
- /**
- * Converts a byte array to a hex readable string.
- **/
- public static String bytesToString(byte[] data, int start, int end) {
- StringBuilder buf = new StringBuilder();
- if (end > data.length) {
- end = data.length;
- }
- for (int i = start; i < end; i++) {
- buf.append(" ");
- buf.append(Integer.toHexString(data[i] & 0xff));
- }
- return buf.toString();
- }
-
- protected static final long KB = 1024;
- protected static final long MB = 1024 * KB;
- protected static final long GB = 1024 * MB;
- protected static final long TB = 1024 * GB;
-
- public static String toReadableSize(long bytes) {
- if (bytes < KB && bytes >= 0) {
- return Long.toString(bytes) + " bytes";
- }
- StringBuilder builder = new StringBuilder();
- Formatter format = new Formatter(builder, Locale.getDefault());
- if (bytes < MB) {
- format.format("%.2f KB", (float)bytes / (float)KB);
- } else if (bytes < GB) {
- format.format("%.2f MB", (float)bytes / (float)MB);
- } else if (bytes < TB) {
- format.format("%.2f GB", (float)bytes / (float)GB);
- } else {
- format.format("%.4f TB", (float)bytes / (float)TB);
- }
- format.close();
- return builder.toString();
- }
-
- /**
- * Converts a string of the format 'yy-MM-dd'T'HH:mm:ss.SSS" into ms.
- *
- * @param str containing the interval.
- * @param defaultValue value to return if str doesn't parse. If -1, throws VmopsRuntimeException
- * @return interval in ms
- */
- public static long parseInterval(String str, long defaultValue) {
- try {
- if (str == null) {
- throw new ParseException("String is wrong", 0);
- }
-
- SimpleDateFormat sdf = null;
- if (str.contains("D")) {
- sdf = new SimpleDateFormat("dd'D'HH'h'mm'M'ss'S'SSS'ms'");
- } else if (str.contains("h")) {
- sdf = new SimpleDateFormat("HH'h'mm'M'ss'S'SSS'ms'");
- } else if (str.contains("M")) {
- sdf = new SimpleDateFormat("mm'M'ss'S'SSS'ms'");
- } else if (str.contains("S")) {
- sdf = new SimpleDateFormat("ss'S'SSS'ms'");
- } else if (str.contains("ms")) {
- sdf = new SimpleDateFormat("SSS'ms'");
- }
- if (sdf == null) {
- throw new ParseException("String is wrong", 0);
- }
-
- Date date = sdf.parse(str);
- return date.getTime();
- } catch (ParseException e) {
- if (defaultValue != -1) {
- return defaultValue;
- } else {
- throw new CloudRuntimeException("Unable to parse: " + str, e);
- }
- }
- }
-
- public static int hash(long value) {
- return (int)(value ^ (value >>> 32));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/Pair.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/Pair.java b/utils/src/com/cloud/utils/Pair.java
deleted file mode 100644
index 73d3562..0000000
--- a/utils/src/com/cloud/utils/Pair.java
+++ /dev/null
@@ -1,87 +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 com.cloud.utils;
-
-import java.io.Serializable;
-
-public class Pair<T, U> implements Serializable {
- private static final long serialVersionUID = 2L;
- T t;
- U u;
-
- protected Pair() {
-
- }
-
- public Pair(T t, U u) {
- this.t = t;
- this.u = u;
- }
-
- public T first() {
- return t;
- }
-
- public U second() {
- return u;
- }
-
- public U second(U value) {
- u = value;
- return u;
- }
-
- public T first(T value) {
- t = value;
- return t;
- }
-
- public void set(T t, U u) {
- this.t = t;
- this.u = u;
- }
-
- @Override
- // Note: This means any two pairs with null for both values will match each
- // other but what can I do? This is due to stupid type erasure.
- public
- int hashCode() {
- return (t != null ? t.hashCode() : 0) | (u != null ? u.hashCode() : 0);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof Pair)) {
- return false;
- }
- Pair<?, ?> that = (Pair<?, ?>)obj;
- return (t != null ? t.equals(that.t) : that.t == null) && (u != null ? u.equals(that.u) : that.u == null);
- }
-
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder("P[");
- b.append((t != null) ? t.toString() : "null");
- b.append(":");
- b.append((u != null) ? u.toString() : "null");
- b.append("]");
- return b.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/PasswordGenerator.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/PasswordGenerator.java b/utils/src/com/cloud/utils/PasswordGenerator.java
deleted file mode 100644
index 0d79143..0000000
--- a/utils/src/com/cloud/utils/PasswordGenerator.java
+++ /dev/null
@@ -1,90 +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 com.cloud.utils;
-
-import java.security.SecureRandom;
-import java.util.Random;
-
-/**
- * Generate random passwords
- *
- */
-public class PasswordGenerator {
- //Leave out visually confusing l,L,1,o,O,0
- static private char[] lowerCase = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
- static private char[] upperCase = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
- static private char[] numeric = new char[] {'2', '3', '4', '5', '6', '7', '8', '9'};
-
- static private char[] alphaNumeric = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
- 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9'};
-
- static private int minLength = 3;
-
- public static String generateRandomPassword(int num) {
- Random r = new SecureRandom();
- StringBuilder password = new StringBuilder();
-
- //Guard for num < minLength
- if (num < minLength) {
- //Add alphanumeric chars at random
- for (int i = 0; i < minLength; i++) {
- password.append(generateAlphaNumeric(r));
- }
- } else {
- // Generate random 3-character string with a lowercase character,
- // uppercase character, and a digit
- password.append(generateLowercaseChar(r)).append(generateUppercaseChar(r)).append(generateDigit(r));
-
- // Generate a random n-character string with only lowercase
- // characters
- for (int i = 0; i < num - 3; i++) {
- password.append(generateLowercaseChar(r));
- }
- }
-
- return password.toString();
- }
-
- private static char generateLowercaseChar(Random r) {
- return lowerCase[r.nextInt(lowerCase.length)];
- }
-
- private static char generateDigit(Random r) {
- return numeric[r.nextInt(numeric.length)];
- }
-
- private static char generateUppercaseChar(Random r) {
- return upperCase[r.nextInt(upperCase.length)];
- }
-
- private static char generateAlphaNumeric(Random r) {
- return alphaNumeric[r.nextInt(alphaNumeric.length)];
- }
-
- public static String generatePresharedKey(int numChars) {
- Random r = new SecureRandom();
- StringBuilder psk = new StringBuilder();
- for (int i = 0; i < numChars; i++) {
- psk.append(generateAlphaNumeric(r));
- }
- return psk.toString();
-
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/Predicate.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/Predicate.java b/utils/src/com/cloud/utils/Predicate.java
deleted file mode 100644
index 6079d16..0000000
--- a/utils/src/com/cloud/utils/Predicate.java
+++ /dev/null
@@ -1,24 +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 com.cloud.utils;
-
-public interface Predicate {
- boolean checkCondition();
-}
[35/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java
new file mode 100644
index 0000000..8a4c053
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java
@@ -0,0 +1,209 @@
+//
+// 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 com.cloud.network.nicira;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+
+@SuppressWarnings("serial")
+public class AclRule extends AccessRule {
+
+ public static final String ETHERTYPE_ARP = "ARP";
+
+ /**
+ * @TODO Convert this String into Enum and check the JSON communication still works
+ */
+ protected String action;
+
+ protected String sourceIpPrefix;
+
+ protected String destinationIpPrefix;
+
+ protected String sourceMacAddress;
+
+ protected String destinationMacAddress;
+
+ protected Integer sourcePortRangeMin;
+
+ protected Integer destinationPortRangeMin;
+
+ protected Integer sourcePortRangeMax;
+
+ protected Integer destinationPortRangeMax;
+
+ protected Integer icmpProtocolCode;
+
+ protected Integer icmpProtocolType;
+
+ protected int order;
+
+
+ /**
+ * Default constructor
+ */
+ public AclRule() {
+ }
+
+ /**
+ * Fully parameterized constructor
+ */
+ public AclRule(String ethertype, int protocol, String action, String sourceMacAddress,
+ String destinationMacAddress, String sourceIpPrefix, String destinationIpPrefix,
+ Integer sourcePortRangeMin, Integer sourcePortRangeMax,
+ Integer destinationPortRangeMin, Integer destinationPortRangeMax,
+ int order, Integer icmpProtocolCode, Integer icmpProtocolType) {
+ this.ethertype = ethertype;
+ this.protocol = protocol;
+ this.action = action;
+ this.sourceMacAddress = sourceMacAddress;
+ this.destinationMacAddress = destinationMacAddress;
+ this.sourceIpPrefix = sourceIpPrefix;
+ this.destinationIpPrefix = destinationIpPrefix;
+ this.sourcePortRangeMin = sourcePortRangeMin;
+ this.sourcePortRangeMax = sourcePortRangeMax;
+ this.destinationPortRangeMin = destinationPortRangeMin;
+ this.destinationPortRangeMax = destinationPortRangeMax;
+ this.order = order;
+ this.icmpProtocolCode = icmpProtocolCode;
+ this.icmpProtocolType = icmpProtocolType;
+ }
+
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getSourceIpPrefix() {
+ return sourceIpPrefix;
+ }
+
+ public void setSourceIpPrefix(String sourceIpPrefix) {
+ this.sourceIpPrefix = sourceIpPrefix;
+ }
+
+ public String getDestinationIpPrefix() {
+ return destinationIpPrefix;
+ }
+
+ public void setDestinationIpPrefix(String destinationIpPrefix) {
+ this.destinationIpPrefix = destinationIpPrefix;
+ }
+
+ public String getSourceMacAddress() {
+ return sourceMacAddress;
+ }
+
+ public void setSourceMacAddress(String sourceMacAddress) {
+ this.sourceMacAddress = sourceMacAddress;
+ }
+
+ public String getDestinationMacAddress() {
+ return destinationMacAddress;
+ }
+
+ public void setDestinationMacAddress(String destinationMacAddress) {
+ this.destinationMacAddress = destinationMacAddress;
+ }
+
+ public Integer getSourcePortRangeMin() {
+ return sourcePortRangeMin;
+ }
+
+ public void setSourcePortRangeMin(Integer sourcePortRangeMin) {
+ this.sourcePortRangeMin = sourcePortRangeMin;
+ }
+
+ public Integer getDestinationPortRangeMin() {
+ return destinationPortRangeMin;
+ }
+
+ public void setDestinationPortRangeMin(Integer destinationPortRangeMin) {
+ this.destinationPortRangeMin = destinationPortRangeMin;
+ }
+
+ public Integer getSourcePortRangeMax() {
+ return sourcePortRangeMax;
+ }
+
+ public void setSourcePortRangeMax(Integer sourcePortRangeMax) {
+ this.sourcePortRangeMax = sourcePortRangeMax;
+ }
+
+ public Integer getDestinationPortRangeMax() {
+ return destinationPortRangeMax;
+ }
+
+ public void setDestinationPortRangeMax(Integer destinationPortRangeMax) {
+ this.destinationPortRangeMax = destinationPortRangeMax;
+ }
+
+ public Integer getIcmpProtocolCode() {
+ return icmpProtocolCode;
+ }
+
+ public void setIcmpProtocolCode(Integer icmpProtocolCode) {
+ this.icmpProtocolCode = icmpProtocolCode;
+ }
+
+ public Integer getIcmpProtocolType() {
+ return icmpProtocolType;
+ }
+
+ public void setIcmpProtocolType(Integer icmpProtocolType) {
+ this.icmpProtocolType = icmpProtocolType;
+ }
+
+ public int getOrder() {
+ return order;
+ }
+
+ public void setOrder(int order) {
+ this.order = order;
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 31)
+ .append(ethertype).append(protocol)
+ .toHashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof AclRule)) {
+ return false;
+ }
+ AclRule another = (AclRule) obj;
+ return new EqualsBuilder()
+ .append(ethertype, another.ethertype)
+ .append(protocol, another.protocol)
+ .isEquals();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java
new file mode 100644
index 0000000..90ff131
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.network.nicira;
+
+public abstract class Attachment {
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java
new file mode 100644
index 0000000..afcd233
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java
@@ -0,0 +1,85 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.io.Serializable;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.commons.lang.builder.ReflectionToStringBuilder;
+import org.apache.commons.lang.builder.ToStringStyle;
+
+public abstract class BaseNiciraEntity implements Serializable {
+ protected String href;
+ protected String schema;
+ protected String uuid;
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(final String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getHref() {
+ return href;
+ }
+
+ public void setHref(final String href) {
+ this.href = href;
+ }
+
+ public String getSchema() {
+ return schema;
+ }
+
+ public void setSchema(final String schema) {
+ this.schema = schema;
+ }
+
+ @Override
+ public String toString() {
+ return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 31)
+ .append(this.getClass())
+ .append(uuid)
+ .toHashCode();
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (!(this.getClass().isInstance(obj))) {
+ return false;
+ }
+ final BaseNiciraEntity another = (BaseNiciraEntity) obj;
+ return new EqualsBuilder().append(uuid, another.uuid).isEquals();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java
new file mode 100644
index 0000000..0e21ddb
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.nicira;
+
+import java.util.List;
+
+public abstract class BaseNiciraNamedEntity extends BaseNiciraEntity {
+
+ protected String displayName;
+ protected List<NiciraNvpTag> tags;
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public void setDisplayName(final String displayName) {
+ this.displayName = displayName;
+ }
+
+ public List<NiciraNvpTag> getTags() {
+ return tags;
+ }
+
+ public void setTags(final List<NiciraNvpTag> tags) {
+ this.tags = tags;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java
new file mode 100644
index 0000000..8d6399e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java
@@ -0,0 +1,87 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class ControlClusterStatus {
+ private String clusterStatus;
+ private Stats nodeStats;
+ private Stats queueStats;
+ private Stats portStats;
+ private Stats routerportStats;
+ private Stats switchStats;
+ private Stats zoneStats;
+ private Stats routerStats;
+ private Stats securityProfileStats;
+
+ public String getClusterStatus() {
+ return clusterStatus;
+ }
+
+ public Stats getNodeStats() {
+ return nodeStats;
+ }
+
+ public Stats getLqueueStats() {
+ return queueStats;
+ }
+
+ public Stats getLportStats() {
+ return portStats;
+ }
+
+ public Stats getLrouterportStats() {
+ return routerportStats;
+ }
+
+ public Stats getLswitchStats() {
+ return switchStats;
+ }
+
+ public Stats getZoneStats() {
+ return zoneStats;
+ }
+
+ public Stats getLrouterStats() {
+ return routerStats;
+ }
+
+ public Stats getSecurityProfileStats() {
+ return securityProfileStats;
+ }
+
+ public class Stats {
+ private int errorStateCount;
+ private int registeredCount;
+ private int activeCount;
+
+ public int getErrorStateCount() {
+ return errorStateCount;
+ }
+
+ public int getRegisteredCount() {
+ return registeredCount;
+ }
+
+ public int getActiveCount() {
+ return activeCount;
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java
new file mode 100644
index 0000000..a0d5afc
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java
@@ -0,0 +1,113 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class DestinationNatRule extends NatRule {
+ private String toDestinationIpAddress;
+ private Integer toDestinationPort;
+
+ public DestinationNatRule() {
+ setType("DestinationNatRule");
+ }
+
+ public String getToDestinationIpAddress() {
+ return toDestinationIpAddress;
+ }
+
+ public void setToDestinationIpAddress(final String toDestinationIpAddress) {
+ this.toDestinationIpAddress = toDestinationIpAddress;
+ }
+
+ public Integer getToDestinationPort() {
+ return toDestinationPort;
+ }
+
+ public void setToDestinationPort(final Integer toDestinationPort) {
+ this.toDestinationPort = toDestinationPort;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result + ((toDestinationIpAddress == null) ? 0 : toDestinationIpAddress.hashCode());
+ result = prime * result + ((toDestinationPort == null) ? 0 : toDestinationPort.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!super.equals(obj)) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ DestinationNatRule other = (DestinationNatRule)obj;
+ if (toDestinationIpAddress == null) {
+ if (other.toDestinationIpAddress != null) {
+ return false;
+ }
+ } else if (!toDestinationIpAddress.equals(other.toDestinationIpAddress)) {
+ return false;
+ }
+ if (toDestinationPort == null) {
+ if (other.toDestinationPort != null) {
+ return false;
+ }
+ } else if (!toDestinationPort.equals(other.toDestinationPort)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean equalsIgnoreUuid(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!super.equalsIgnoreUuid(obj)) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ DestinationNatRule other = (DestinationNatRule)obj;
+ if (toDestinationIpAddress == null) {
+ if (other.toDestinationIpAddress != null) {
+ return false;
+ }
+ } else if (!toDestinationIpAddress.equals(other.toDestinationIpAddress)) {
+ return false;
+ }
+ if (toDestinationPort == null) {
+ if (other.toDestinationPort != null) {
+ return false;
+ }
+ } else if (!toDestinationPort.equals(other.toDestinationPort)) {
+ return false;
+ }
+ return true;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java
new file mode 100644
index 0000000..a1d5ce4
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java
@@ -0,0 +1,55 @@
+//
+// 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 com.cloud.network.nicira;
+
+/**
+ *
+ */
+public class L3GatewayAttachment extends Attachment {
+ private String l3GatewayServiceUuid;
+ private final String type = "L3GatewayAttachment";
+ private Long vlanId;
+
+ public L3GatewayAttachment(String l3GatewayServiceUuid) {
+ this.l3GatewayServiceUuid = l3GatewayServiceUuid;
+ }
+
+ public L3GatewayAttachment(final String l3GatewayServiceUuid, final long vlanId) {
+ this.l3GatewayServiceUuid = l3GatewayServiceUuid;
+ this.vlanId = vlanId;
+ }
+
+ public String getL3GatewayServiceUuid() {
+ return l3GatewayServiceUuid;
+ }
+
+ public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) {
+ this.l3GatewayServiceUuid = l3GatewayServiceUuid;
+ }
+
+ public long getVlanId() {
+ return vlanId;
+ }
+
+ public void setVlanId(long vlanId) {
+ this.vlanId = vlanId;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java
new file mode 100644
index 0000000..edc9351
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java
@@ -0,0 +1,71 @@
+//
+// 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 com.cloud.network.nicira;
+
+
+/**
+ *
+ */
+public class LogicalRouter extends BaseNiciraNamedEntity {
+ public static final String REPLICATION_MODE_SERVICE = "service";
+ public static final String REPLICATION_MODE_SOURCE = "source";
+
+ private final String type = "LogicalRouterConfig";
+ private RoutingConfig routingConfig;
+ private boolean distributed;
+ private boolean natSynchronizationEnabled;
+ private String replicationMode;
+
+ public String getType() {
+ return type;
+ }
+
+ public RoutingConfig getRoutingConfig() {
+ return routingConfig;
+ }
+
+ public void setRoutingConfig(final RoutingConfig routingConfig) {
+ this.routingConfig = routingConfig;
+ }
+
+ public boolean isDistributed() {
+ return distributed;
+ }
+
+ public void setDistributed(final boolean distributed) {
+ this.distributed = distributed;
+ }
+
+ public boolean isNatSynchronizationEnabled() {
+ return natSynchronizationEnabled;
+ }
+
+ public void setNatSynchronizationEnabled(final boolean natSynchronizationEnabled) {
+ this.natSynchronizationEnabled = natSynchronizationEnabled;
+ }
+
+ public String getReplicationMode() {
+ return replicationMode;
+ }
+
+ public void setReplicationMode(final String replicationMode) {
+ this.replicationMode = replicationMode;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java
new file mode 100644
index 0000000..d9ee09a
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java
@@ -0,0 +1,62 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.util.List;
+
+public class LogicalRouterPort extends BaseNiciraNamedEntity {
+ private Integer portno;
+ private boolean adminStatusEnabled;
+ private List<String> ipAddresses;
+ private String macAddress;
+ private final String type = "LogicalRouterPortConfig";
+
+ public int getPortno() {
+ return portno;
+ }
+
+ public void setPortno(final int portno) {
+ this.portno = portno;
+ }
+
+ public boolean isAdminStatusEnabled() {
+ return adminStatusEnabled;
+ }
+
+ public void setAdminStatusEnabled(final boolean adminStatusEnabled) {
+ this.adminStatusEnabled = adminStatusEnabled;
+ }
+
+ public List<String> getIpAddresses() {
+ return ipAddresses;
+ }
+
+ public void setIpAddresses(final List<String> ipAddresses) {
+ this.ipAddresses = ipAddresses;
+ }
+
+ public String getMacAddress() {
+ return macAddress;
+ }
+
+ public void setMacAddress(final String macAddress) {
+ this.macAddress = macAddress;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java
new file mode 100644
index 0000000..b527d94
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java
@@ -0,0 +1,60 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.util.List;
+
+public class LogicalSwitch extends BaseNiciraNamedEntity {
+ public static final String REPLICATION_MODE_SERVICE = "service";
+ public static final String REPLICATION_MODE_SOURCE = "source";
+
+ private final String type = "LogicalSwitchConfig";
+ private boolean portIsolationEnabled;
+ private List<TransportZoneBinding> transportZones;
+ private String replicationMode;
+
+ public boolean isPortIsolationEnabled() {
+ return portIsolationEnabled;
+ }
+
+ public void setPortIsolationEnabled(final boolean portIsolationEnabled) {
+ this.portIsolationEnabled = portIsolationEnabled;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public List<TransportZoneBinding> getTransportZones() {
+ return transportZones;
+ }
+
+ public void setTransportZones(final List<TransportZoneBinding> transportZones) {
+ this.transportZones = transportZones;
+ }
+
+ public String getReplicationMode() {
+ return replicationMode;
+ }
+
+ public void setReplicationMode(final String replicationMode) {
+ this.replicationMode = replicationMode;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java
new file mode 100644
index 0000000..5e07423
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java
@@ -0,0 +1,82 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.util.List;
+
+public class LogicalSwitchPort extends BaseNiciraNamedEntity {
+ private Integer portno;
+ private boolean adminStatusEnabled;
+ private String queueUuid;
+ private List<String> securityProfiles;
+ private List<String> mirrorTargets;
+ private final String type = "LogicalSwitchPortConfig";
+
+ public LogicalSwitchPort() {
+ super();
+ }
+
+ public LogicalSwitchPort(final String displayName, final List<NiciraNvpTag> tags, final boolean adminStatusEnabled) {
+ super();
+ this.displayName = displayName;
+ this.tags = tags;
+ this.adminStatusEnabled = adminStatusEnabled;
+ }
+
+ public Integer getPortno() {
+ return portno;
+ }
+
+ public void setPortno(final Integer portno) {
+ this.portno = portno;
+ }
+
+ public boolean isAdminStatusEnabled() {
+ return adminStatusEnabled;
+ }
+
+ public void setAdminStatusEnabled(final boolean adminStatusEnabled) {
+ this.adminStatusEnabled = adminStatusEnabled;
+ }
+
+ public String getQueueUuid() {
+ return queueUuid;
+ }
+
+ public void setQueueUuid(final String queueUuid) {
+ this.queueUuid = queueUuid;
+ }
+
+ public List<String> getSecurityProfiles() {
+ return securityProfiles;
+ }
+
+ public void setSecurityProfiles(final List<String> securityProfiles) {
+ this.securityProfiles = securityProfiles;
+ }
+
+ public List<String> getMirrorTargets() {
+ return mirrorTargets;
+ }
+
+ public void setMirrorTargets(final List<String> mirrorTargets) {
+ this.mirrorTargets = mirrorTargets;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java
new file mode 100644
index 0000000..ae3a86c
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java
@@ -0,0 +1,146 @@
+//
+// 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 com.cloud.network.nicira;
+
+/**
+ *
+ */
+public class Match {
+ private Integer protocol;
+ private String sourceIpAddresses;
+ private String destinationIpAddresses;
+ private Integer sourcePort;
+ private Integer destinationPort;
+ private String ethertype = "IPv4";
+
+ public Integer getProtocol() {
+ return protocol;
+ }
+
+ public void setProtocol(final Integer protocol) {
+ this.protocol = protocol;
+ }
+
+ public Integer getSourcePort() {
+ return sourcePort;
+ }
+
+ public void setSourcePort(final Integer sourcePort) {
+ this.sourcePort = sourcePort;
+ }
+
+ public Integer getDestinationPort() {
+ return destinationPort;
+ }
+
+ public void setDestinationPort(final Integer destinationPort) {
+ this.destinationPort = destinationPort;
+ }
+
+ public String getEthertype() {
+ return ethertype;
+ }
+
+ public void setEthertype(final String ethertype) {
+ this.ethertype = ethertype;
+ }
+
+ public String getSourceIpAddresses() {
+ return sourceIpAddresses;
+ }
+
+ public void setSourceIpAddresses(final String sourceIpAddresses) {
+ this.sourceIpAddresses = sourceIpAddresses;
+ }
+
+ public String getDestinationIpAddresses() {
+ return destinationIpAddresses;
+ }
+
+ public void setDestinationIpAddresses(final String destinationIpAddresses) {
+ this.destinationIpAddresses = destinationIpAddresses;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((destinationIpAddresses == null) ? 0 : destinationIpAddresses.hashCode());
+ result = prime * result + ((destinationPort == null) ? 0 : destinationPort.hashCode());
+ result = prime * result + ((ethertype == null) ? 0 : ethertype.hashCode());
+ result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
+ result = prime * result + ((sourceIpAddresses == null) ? 0 : sourceIpAddresses.hashCode());
+ result = prime * result + ((sourcePort == null) ? 0 : sourcePort.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ Match other = (Match)obj;
+ if (destinationIpAddresses == null) {
+ if (other.destinationIpAddresses != null)
+ return false;
+ } else if (!destinationIpAddresses.equals(other.destinationIpAddresses)) {
+ return false;
+ }
+ if (destinationPort == null) {
+ if (other.destinationPort != null) {
+ return false;
+ }
+ } else if (!destinationPort.equals(other.destinationPort)) {
+ return false;
+ }
+ if (ethertype == null) {
+ if (other.ethertype != null)
+ return false;
+ } else if (!ethertype.equals(other.ethertype)) {
+ return false;
+ }
+ if (protocol == null) {
+ if (other.protocol != null)
+ return false;
+ } else if (!protocol.equals(other.protocol)) {
+ return false;
+ }
+ if (sourceIpAddresses == null) {
+ if (other.sourceIpAddresses != null)
+ return false;
+ } else if (!sourceIpAddresses.equals(other.sourceIpAddresses)) {
+ return false;
+ }
+ if (sourcePort == null) {
+ if (other.sourcePort != null)
+ return false;
+ } else if (!sourcePort.equals(other.sourcePort)) {
+ return false;
+ }
+ return true;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java
new file mode 100644
index 0000000..912e352
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java
@@ -0,0 +1,130 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.util.UUID;
+
+/**
+ *
+ */
+public abstract class NatRule {
+ protected Match match;
+ protected UUID uuid;
+ protected String type;
+ protected int order;
+
+ public NatRule() {
+ }
+
+ public Match getMatch() {
+ return match;
+ }
+
+ public void setMatch(final Match match) {
+ this.match = match;
+ }
+
+ public UUID getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(final UUID uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(final String type) {
+ this.type = type;
+ }
+
+ public int getOrder() {
+ return order;
+ }
+
+ public void setOrder(final int order) {
+ this.order = order;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((match == null) ? 0 : match.hashCode());
+ result = prime * result + order;
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ NatRule other = (NatRule)obj;
+ if (match == null) {
+ if (other.match != null)
+ return false;
+ } else if (!match.equals(other.match))
+ return false;
+ if (order != other.order)
+ return false;
+ if (type == null) {
+ if (other.type != null)
+ return false;
+ } else if (!type.equals(other.type))
+ return false;
+ if (uuid == null) {
+ if (other.uuid != null)
+ return false;
+ } else if (!uuid.equals(other.uuid))
+ return false;
+ return true;
+ }
+
+ public boolean equalsIgnoreUuid(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ NatRule other = (NatRule)obj;
+ if (match == null) {
+ if (other.match != null)
+ return false;
+ } else if (!match.equals(other.match))
+ return false;
+ if (order != other.order)
+ return false;
+ if (type == null) {
+ if (other.type != null)
+ return false;
+ } else if (!type.equals(other.type))
+ return false;
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
new file mode 100644
index 0000000..810453c
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
@@ -0,0 +1,658 @@
+//
+// 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 com.cloud.network.nicira;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.reflect.TypeToken;
+
+import com.cloud.utils.rest.CloudstackRESTException;
+import com.cloud.utils.rest.RESTServiceConnector;
+import com.cloud.utils.rest.RESTValidationStrategy;
+
+@SuppressWarnings("rawtypes")
+public class NiciraNvpApi {
+ protected static final String GET_METHOD_TYPE = "get";
+ protected static final String DELETE_METHOD_TYPE = "delete";
+ protected static final String PUT_METHOD_TYPE = "put";
+ protected static final String POST_METHOD_TYPE = "post";
+
+ protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile";
+ protected static final String ACL_URI_PREFIX = "/ws.v1/acl";
+ private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch";
+ private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter";
+ private static final String LOGIN_URL = "/ws.v1/login";
+
+ protected RESTServiceConnector restConnector;
+
+ protected final static Map<Class, String> prefixMap;
+
+ protected final static Map<Class, Type> listTypeMap;
+
+ protected final static Map<String, String> defaultListParams;
+
+ static {
+ prefixMap = new HashMap<Class, String>();
+ prefixMap.put(SecurityProfile.class, SEC_PROFILE_URI_PREFIX);
+ prefixMap.put(Acl.class, ACL_URI_PREFIX);
+ prefixMap.put(LogicalSwitch.class, SWITCH_URI_PREFIX);
+ prefixMap.put(LogicalRouter.class, ROUTER_URI_PREFIX);
+
+ listTypeMap = new HashMap<Class, Type>();
+ listTypeMap.put(SecurityProfile.class, new TypeToken<NiciraNvpList<SecurityProfile>>() {
+ }.getType());
+ listTypeMap.put(Acl.class, new TypeToken<NiciraNvpList<Acl>>() {
+ }.getType());
+ listTypeMap.put(LogicalSwitch.class, new TypeToken<NiciraNvpList<LogicalSwitch>>() {
+ }.getType());
+ listTypeMap.put(LogicalRouter.class, new TypeToken<NiciraNvpList<LogicalRouter>>() {
+ }.getType());
+
+ defaultListParams = new HashMap<String, String>();
+ defaultListParams.put("fields", "*");
+ }
+
+ public NiciraNvpApi() {
+ final List<Class<?>> classList = new ArrayList<Class<?>>();
+ classList.add(NatRule.class);
+ classList.add(RoutingConfig.class);
+ final List<JsonDeserializer<?>> deserializerList = new ArrayList<JsonDeserializer<?>>();
+ deserializerList.add(new NatRuleAdapter());
+ deserializerList.add(new RoutingConfigAdapter());
+
+ restConnector = new RESTServiceConnector(new RESTValidationStrategy(LOGIN_URL), classList, deserializerList);
+ }
+
+ public NiciraNvpApi(final String address, final String username, final String password) {
+ this();
+ restConnector.setControllerAddress(address);
+ restConnector.setAdminCredentials(username, password);
+ }
+
+ public void setControllerAddress(final String address) {
+ restConnector.setControllerAddress(address);
+ }
+
+ public void setAdminCredentials(final String username, final String password) {
+ restConnector.setAdminCredentials(username, password);
+ }
+
+ /**
+ * POST
+ *
+ * @param entity
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ protected <T> T create(final T entity) throws NiciraNvpApiException {
+ final String uri = prefixMap.get(entity.getClass());
+ return createWithUri(entity, uri);
+ }
+
+ /**
+ * POST
+ *
+ * @param entity
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ protected <T> T createWithUri(final T entity, final String uri) throws NiciraNvpApiException {
+ T createdEntity;
+ try {
+ createdEntity = restConnector.executeCreateObject(entity, new TypeToken<T>() {
+ }.getType(), uri, Collections.<String, String> emptyMap());
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+
+ return createdEntity;
+ }
+
+ /**
+ * GET list of items
+ *
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ protected <T> NiciraNvpList<T> find(final Class<T> clazz) throws NiciraNvpApiException {
+ return find(null, clazz);
+ }
+
+ /**
+ * GET list of items
+ *
+ * @param uuid
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public <T> NiciraNvpList<T> find(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
+ final String uri = prefixMap.get(clazz);
+ Map<String, String> params = defaultListParams;
+ if (uuid != null) {
+ params = new HashMap<String, String>(defaultListParams);
+ params.put("uuid", uuid);
+ }
+
+ NiciraNvpList<T> entities;
+ try {
+ entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+
+ if (entities == null) {
+ throw new NiciraNvpApiException("Unexpected response from API");
+ }
+
+ return entities;
+ }
+
+ /**
+ * PUT item given a UUID as key and an item object
+ * with the new data
+ *
+ * @param item
+ * @param uuid
+ * @throws NiciraNvpApiException
+ */
+ public <T> void update(final T item, final String uuid)
+ throws NiciraNvpApiException {
+ final String uri = prefixMap.get(item.getClass()) + "/" + uuid;
+ updateWithUri(item, uri);
+ }
+
+ /**
+ * PUT item given a UUID as key and an item object
+ * with the new data
+ *
+ * @param item
+ * @param uuid
+ * @throws NiciraNvpApiException
+ */
+ public <T> void updateWithUri(final T item, final String uri)
+ throws NiciraNvpApiException {
+ try {
+ restConnector.executeUpdateObject(item, uri, Collections.<String, String> emptyMap());
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+ }
+
+ /**
+ * DELETE Security Profile given a UUID as key
+ *
+ * @param securityProfileUuid
+ * @throws NiciraNvpApiException
+ */
+ public <T> void delete(final String uuid, final Class<T> clazz)
+ throws NiciraNvpApiException {
+ final String uri = prefixMap.get(clazz) + "/" + uuid;
+ deleteWithUri(uri);
+ }
+
+ /**
+ * DELETE Security Profile given a UUID as key
+ *
+ * @param securityProfileUuid
+ * @throws NiciraNvpApiException
+ */
+ public <T> void deleteWithUri(final String uri)
+ throws NiciraNvpApiException {
+ try {
+ restConnector.executeDeleteObject(uri);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+ }
+
+ /**
+ * POST {@link SecurityProfile}
+ *
+ * @param securityProfile
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public SecurityProfile createSecurityProfile(final SecurityProfile securityProfile) throws NiciraNvpApiException {
+ return create(securityProfile);
+ }
+
+ /**
+ * GET list of {@link SecurityProfile}
+ *
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<SecurityProfile> findSecurityProfile() throws NiciraNvpApiException {
+ return findSecurityProfile(null);
+ }
+
+ /**
+ * GET list of {@link SecurityProfile} filtered by UUID
+ *
+ * We could have invoked the service:
+ * SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid
+ * but it is not working currently
+ *
+ * @param uuid
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<SecurityProfile> findSecurityProfile(final String uuid) throws NiciraNvpApiException {
+ return find(uuid, SecurityProfile.class);
+ }
+
+ /**
+ * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile}
+ * with the new data
+ *
+ * @param securityProfile
+ * @param securityProfileUuid
+ * @throws NiciraNvpApiException
+ */
+ public void updateSecurityProfile(final SecurityProfile securityProfile,
+ final String securityProfileUuid)
+ throws NiciraNvpApiException {
+ update(securityProfile, securityProfileUuid);
+ }
+
+ /**
+ * DELETE Security Profile given a UUID as key
+ *
+ * @param securityProfileUuid
+ * @throws NiciraNvpApiException
+ */
+ public void deleteSecurityProfile(final String securityProfileUuid)
+ throws NiciraNvpApiException {
+ delete(securityProfileUuid, SecurityProfile.class);
+ }
+
+
+ /**
+ * POST {@link Acl}
+ *
+ * @param acl
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public Acl createAcl(final Acl acl) throws NiciraNvpApiException {
+ return create(acl);
+ }
+
+ /**
+ * GET list of {@link Acl}
+ *
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<Acl> findAcl() throws NiciraNvpApiException {
+ return findAcl(null);
+ }
+
+ /**
+ * GET list of {@link Acl} filtered by UUID
+ *
+ * @param uuid
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<Acl> findAcl(final String uuid) throws NiciraNvpApiException {
+ return find(uuid, Acl.class);
+ }
+
+ /**
+ * PUT {@link Acl} given a UUID as key and a {@link Acl}
+ * with the new data
+ *
+ * @param acl
+ * @param aclUuid
+ * @throws NiciraNvpApiException
+ */
+ public void updateAcl(final Acl acl,
+ final String aclUuid)
+ throws NiciraNvpApiException {
+ update(acl, aclUuid);
+ }
+
+ /**
+ * DELETE Acl given a UUID as key
+ *
+ * @param acl
+ * @throws NiciraNvpApiException
+ */
+ public void deleteAcl(final String aclUuid) throws NiciraNvpApiException {
+ delete(aclUuid, Acl.class);
+ }
+
+ public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException {
+ return create(logicalSwitch);
+ }
+
+ /**
+ * GET list of {@link LogicalSwitch}
+ *
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<LogicalSwitch> findLogicalSwitch() throws NiciraNvpApiException {
+ return findLogicalSwitch(null);
+ }
+
+ /**
+ * GET list of {@link LogicalSwitch} filtered by UUID
+ *
+ * @param uuid
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<LogicalSwitch> findLogicalSwitch(final String uuid) throws NiciraNvpApiException {
+ return find(uuid, LogicalSwitch.class);
+ }
+
+ /**
+ * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch}
+ * with the new data
+ *
+ * @param logicalSwitch
+ * @param logicalSwitchUuid
+ * @throws NiciraNvpApiException
+ */
+ public void updateLogicalSwitch(final LogicalSwitch logicalSwitch,
+ final String logicalSwitchUuid)
+ throws NiciraNvpApiException {
+ update(logicalSwitch, logicalSwitchUuid);
+ }
+
+ public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException {
+ delete(uuid, LogicalSwitch.class);
+ }
+
+ public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
+ final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
+ return createWithUri(logicalSwitchPort, uri);
+ }
+
+ public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
+ final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPort.getUuid();
+ updateWithUri(logicalSwitchPort, uri);
+ }
+
+ public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid,
+ final Attachment attachment) throws NiciraNvpApiException {
+ final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment";
+ updateWithUri(attachment, uri);
+ }
+
+ public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
+ final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid;
+ deleteWithUri(uri);
+ }
+
+ public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException {
+ final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put("attachment_vif_uuid", vifAttachmentUuid);
+ params.put("fields", "uuid");
+
+ NiciraNvpList<LogicalSwitchPort> lspl;
+ try {
+ lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
+ }.getType(), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+
+ if (lspl == null || lspl.getResultCount() != 1) {
+ throw new NiciraNvpApiException("Unexpected response from API");
+ }
+
+ final LogicalSwitchPort lsp = lspl.getResults().get(0);
+ return lsp.getUuid();
+ }
+
+ public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException {
+ final String uri = "/ws.v1/control-cluster/status";
+ ControlClusterStatus ccs;
+ try {
+ ccs = restConnector.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
+ }.getType(), uri, null);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+
+ return ccs;
+ }
+
+ public NiciraNvpList<LogicalSwitchPort> findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
+ final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put("uuid", logicalSwitchPortUuid);
+ params.put("fields", "uuid");
+
+ NiciraNvpList<LogicalSwitchPort> lspl;
+ try {
+ lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
+ }.getType(), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+
+ if (lspl == null) {
+ throw new NiciraNvpApiException("Unexpected response from API");
+ }
+
+ return lspl;
+ }
+
+ public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put("uuid", logicalRouterPortUuid);
+ params.put("fields", "uuid");
+
+ NiciraNvpList<LogicalRouterPort> lrpl;
+ try {
+ lrpl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
+ }.getType(), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+
+ if (lrpl == null) {
+ throw new NiciraNvpApiException("Unexpected response from API");
+ }
+
+ return lrpl;
+ }
+
+ public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException {
+ return create(logicalRouter);
+ }
+
+ /**
+ * GET list of {@link LogicalRouter}
+ *
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<LogicalRouter> findLogicalRouter() throws NiciraNvpApiException {
+ return findLogicalRouter(null);
+ }
+
+ /**
+ * GET list of {@link LogicalRouter} filtered by UUID
+ *
+ * @param uuid
+ * @return
+ * @throws NiciraNvpApiException
+ */
+ public NiciraNvpList<LogicalRouter> findLogicalRouter(final String uuid) throws NiciraNvpApiException {
+ return find(uuid, LogicalRouter.class);
+ }
+
+ public LogicalRouter findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
+ return findLogicalRouter(logicalRouterUuid).getResults().get(0);
+ }
+
+ public void updateLogicalRouter(final LogicalRouter logicalRouter,
+ final String logicalRouterUuid)
+ throws NiciraNvpApiException {
+ update(logicalRouter, logicalRouterUuid);
+ }
+
+ public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid;
+ deleteWithUri(uri);
+ }
+
+ public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
+ return createWithUri(logicalRouterPort, uri);
+ }
+
+ public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid;
+ deleteWithUri(uri);
+ }
+
+ public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid();
+ updateWithUri(logicalRouterPort, uri);
+ }
+
+ public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment)
+ throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment";
+ updateWithUri(attachment, uri);
+ }
+
+ public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
+ return createWithUri(natRule, uri);
+ }
+
+ public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid();
+ updateWithUri(natRule, uri);
+ }
+
+ public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString();
+ deleteWithUri(uri);
+ }
+
+ public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid,
+ final long vlanId) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put("attachment_gwsvc_uuid", gatewayServiceUuid);
+ params.put("attachment_vlan", "0");
+ params.put("fields", "*");
+
+ try {
+ return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
+ }.getType(), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+ }
+
+ public NiciraNvpList<NatRule> findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put("fields", "*");
+
+ try {
+ return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<NatRule>>() {
+ }.getType(), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+ }
+
+ public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid)
+ throws NiciraNvpApiException {
+ final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put("fields", "*");
+ params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid);
+
+ try {
+ return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
+ }.getType(), uri, params);
+ } catch (final CloudstackRESTException e) {
+ throw new NiciraNvpApiException(e);
+ }
+ }
+
+ public static class NatRuleAdapter implements JsonDeserializer<NatRule> {
+
+ @Override
+ public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
+ final JsonObject jsonObject = jsonElement.getAsJsonObject();
+
+ if (!jsonObject.has("type")) {
+ throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object");
+ }
+
+ final String natRuleType = jsonObject.get("type").getAsString();
+ if ("SourceNatRule".equals(natRuleType)) {
+ return context.deserialize(jsonElement, SourceNatRule.class);
+ } else if ("DestinationNatRule".equals(natRuleType)) {
+ return context.deserialize(jsonElement, DestinationNatRule.class);
+ }
+
+ throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\"");
+ }
+ }
+
+ public static class RoutingConfigAdapter implements JsonDeserializer<RoutingConfig> {
+
+ private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig";
+ private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig";
+
+ @Override
+ public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
+ final JsonObject jsonObject = jsonElement.getAsJsonObject();
+
+ if (!jsonObject.has("type")) {
+ throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object");
+ }
+
+ final String routingConfigType = jsonObject.get("type").getAsString();
+ if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) {
+ return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class);
+ } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) {
+ return context.deserialize(jsonElement, RoutingTableRoutingConfig.class);
+ }
+
+ throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\"");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java
new file mode 100644
index 0000000..0d27820
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java
@@ -0,0 +1,39 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class NiciraNvpApiException extends Exception {
+
+ public NiciraNvpApiException() {
+ }
+
+ public NiciraNvpApiException(final String message) {
+ super(message);
+ }
+
+ public NiciraNvpApiException(final Throwable cause) {
+ super(cause);
+ }
+
+ public NiciraNvpApiException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java
new file mode 100644
index 0000000..34b5e19
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java
@@ -0,0 +1,48 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.util.List;
+
+public class NiciraNvpList<T> {
+ private List<T> results;
+ private int resultCount;
+
+ public List<T> getResults() {
+ return this.results;
+ }
+
+ public void setResults(List<T> results) {
+ this.results = results;
+ }
+
+ public int getResultCount() {
+ return resultCount;
+ }
+
+ public void setResultCount(int resultCount) {
+ this.resultCount = resultCount;
+ }
+
+ public boolean isEmpty() {
+ return this.resultCount == 0;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java
new file mode 100644
index 0000000..625e49c
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java
@@ -0,0 +1,64 @@
+//
+// 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 com.cloud.network.nicira;
+
+import org.apache.log4j.Logger;
+
+public class NiciraNvpTag {
+ private static final int TAG_MAX_LEN = 40;
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpTag.class);
+ private String scope;
+ private String tag;
+
+ public NiciraNvpTag() {
+ }
+
+ public NiciraNvpTag(String scope, String tag) {
+ this.scope = scope;
+ if (tag.length() > 40) {
+ s_logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters");
+ this.tag = tag.substring(0, TAG_MAX_LEN);
+ } else {
+ this.tag = tag;
+ }
+ }
+
+ public String getScope() {
+ return scope;
+ }
+
+ public void setScope(String scope) {
+ this.scope = scope;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ public void setTag(String tag) {
+ if (tag.length() > 40) {
+ s_logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters");
+ this.tag = tag.substring(0, 40);
+ } else {
+ this.tag = tag;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java
new file mode 100644
index 0000000..26fa048
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java
@@ -0,0 +1,41 @@
+//
+// 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 com.cloud.network.nicira;
+
+/**
+ *
+ */
+public class PatchAttachment extends Attachment {
+ private final String type = "PatchAttachment";
+ private String peerPortUuid;
+
+ public PatchAttachment(String peerPortUuid) {
+ this.peerPortUuid = peerPortUuid;
+ }
+
+ public String getPeerPortUuid() {
+ return peerPortUuid;
+ }
+
+ public void setPeerPortUuid(String peerPortUuid) {
+ this.peerPortUuid = peerPortUuid;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java
new file mode 100644
index 0000000..8dd8840
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java
@@ -0,0 +1,40 @@
+//
+// 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 com.cloud.network.nicira;
+
+/**
+ *
+ */
+public class RouterNextHop {
+ private String gatewayIpAddress;
+ private final String type = "RouterNextHop";
+
+ public RouterNextHop(String gatewayIpAddress) {
+ this.gatewayIpAddress = gatewayIpAddress;
+ }
+
+ public String getGatewayIpAddress() {
+ return gatewayIpAddress;
+ }
+
+ public void setGatewayIpAddress(String gatewayIpAddress) {
+ this.gatewayIpAddress = gatewayIpAddress;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java
new file mode 100644
index 0000000..5eaef0a
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class RoutingConfig {
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java
new file mode 100644
index 0000000..f0a80b8
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java
@@ -0,0 +1,30 @@
+//
+// 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 com.cloud.network.nicira;
+
+/**
+ *
+ */
+public class RoutingTableRoutingConfig extends RoutingConfig {
+ public final String type = "RoutingTableRoutingConfig";
+
+ public RoutingTableRoutingConfig() {
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java
new file mode 100644
index 0000000..d83ce49
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.network.nicira;
+
+@SuppressWarnings("serial")
+public class SecurityProfile extends AccessConfiguration<SecurityRule> {
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java
new file mode 100644
index 0000000..e23593c
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java
@@ -0,0 +1,138 @@
+//
+// 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 com.cloud.network.nicira;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+
+@SuppressWarnings("serial")
+public class SecurityRule extends AccessRule {
+
+ protected String ipPrefix;
+
+ protected int portRangeMin;
+
+ protected int portRangeMax;
+
+ protected String profileUuid;
+
+
+ /**
+ * Default constructor
+ */
+ public SecurityRule() {
+ }
+
+ /**
+ * Fully parameterized constructor
+ */
+ public SecurityRule(final String ethertype, final String ipPrefix, final String profileUuid,
+ final int portRangeMin, final int portRangeMax, final int protocol) {
+ this.ethertype = ethertype;
+ this.ipPrefix = ipPrefix;
+ this.portRangeMin = portRangeMin;
+ this.portRangeMax = portRangeMax;
+ this.profileUuid = profileUuid;
+ this.protocol = protocol;
+ }
+
+ @Override
+ public String getEthertype() {
+ return ethertype;
+ }
+
+ @Override
+ public void setEthertype(final String ethertype) {
+ this.ethertype = ethertype;
+ }
+
+ public String getIpPrefix() {
+ return ipPrefix;
+ }
+
+ public void setIpPrefix(final String ipPrefix) {
+ this.ipPrefix = ipPrefix;
+ }
+
+ public int getPortRangeMin() {
+ return portRangeMin;
+ }
+
+ public void setPortRangeMin(final int portRangeMin) {
+ this.portRangeMin = portRangeMin;
+ }
+
+ public int getPortRangeMax() {
+ return portRangeMax;
+ }
+
+ public void setPortRangeMax(final int portRangeMax) {
+ this.portRangeMax = portRangeMax;
+ }
+
+ public String getProfileUuid() {
+ return profileUuid;
+ }
+
+ public void setProfileUuid(final String profileUuid) {
+ this.profileUuid = profileUuid;
+ }
+
+ @Override
+ public int getProtocol() {
+ return protocol;
+ }
+
+ @Override
+ public void setProtocol(final int protocol) {
+ this.protocol = protocol;
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 31)
+ .append(ethertype).append(ipPrefix)
+ .append(portRangeMin).append(portRangeMax)
+ .append(profileUuid).append(protocol)
+ .toHashCode();
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof SecurityRule)) {
+ return false;
+ }
+ final SecurityRule another = (SecurityRule) obj;
+ return new EqualsBuilder()
+ .append(ethertype, another.ethertype)
+ .append(ipPrefix, another.ipPrefix)
+ .append(portRangeMin, another.portRangeMin)
+ .append(portRangeMax, another.portRangeMax)
+ .append(profileUuid, another.profileUuid)
+ .append(protocol, another.protocol)
+ .isEquals();
+ }
+}
[12/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
new file mode 100644
index 0000000..5ff5819
--- /dev/null
+++ b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
@@ -0,0 +1,210 @@
+//
+// 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.commons.httpclient.contrib.ssl;
+
+import org.apache.cloudstack.utils.security.SSLUtils;
+import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.HttpClientError;
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.UnknownHostException;
+
+/**
+ * <p>
+ * EasySSLProtocolSocketFactory can be used to create SSL {@link Socket}s
+ * that accept self-signed certificates.
+ * </p>
+ * <p>
+ * This socket factory SHOULD NOT be used for productive systems
+ * due to security reasons, unless it is a concious decision and
+ * you are perfectly aware of security implications of accepting
+ * self-signed certificates
+ * </p>
+ *
+ * <p>
+ * Example of using custom protocol socket factory for a specific host:
+ * <pre>
+ * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
+ *
+ * URI uri = new URI("https://localhost/", true);
+ * // use relative url only
+ * GetMethod httpget = new GetMethod(uri.getPathQuery());
+ * HostConfiguration hc = new HostConfiguration();
+ * hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
+ * HttpClient client = new HttpClient();
+ * client.executeMethod(hc, httpget);
+ * </pre>
+ * </p>
+ * <p>
+ * Example of using custom protocol socket factory per default instead of the standard one:
+ * <pre>
+ * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
+ * Protocol.registerProtocol("https", easyhttps);
+ *
+ * HttpClient client = new HttpClient();
+ * GetMethod httpget = new GetMethod("https://localhost/");
+ * client.executeMethod(httpget);
+ * </pre>
+ * </p>
+ *
+ * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
+ *
+ * <p>
+ * DISCLAIMER: HttpClient developers DO NOT actively support this component.
+ * The component is provided as a reference material, which may be inappropriate
+ * for use without additional customization.
+ * </p>
+ */
+
+public class EasySSLProtocolSocketFactory implements ProtocolSocketFactory {
+
+ /** Log object for this class. */
+ private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class);
+
+ private SSLContext sslcontext = null;
+
+ /**
+ * Constructor for EasySSLProtocolSocketFactory.
+ */
+ public EasySSLProtocolSocketFactory() {
+ super();
+ }
+
+ private static SSLContext createEasySSLContext() {
+ try {
+ SSLContext context = SSLUtils.getSSLContext();
+ context.init(null, new TrustManager[] {new EasyX509TrustManager(null)}, null);
+ return context;
+ } catch (Exception e) {
+ LOG.error(e.getMessage(), e);
+ throw new HttpClientError(e.toString());
+ }
+ }
+
+ private SSLContext getSSLContext() {
+ if (sslcontext == null) {
+ sslcontext = createEasySSLContext();
+ }
+ return sslcontext;
+ }
+
+ /**
+ * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
+ */
+ @Override
+ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
+ Socket socket = getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ /**
+ * Attempts to get a new socket connection to the given host within the given time limit.
+ * <p>
+ * To circumvent the limitations of older JREs that do not support connect timeout a
+ * controller thread is executed. The controller thread attempts to create a new socket
+ * within the given limit of time. If socket constructor does not return until the
+ * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
+ * </p>
+ *
+ * @param host the host name/IP
+ * @param port the port on the host
+ * @param localAddress the local host name/IP to bind the socket to
+ * @param localPort the port on the local machine
+ * @param params {@link HttpConnectionParams Http connection parameters}
+ *
+ * @return Socket a new socket
+ *
+ * @throws IOException if an I/O error occurs while creating the socket
+ * @throws UnknownHostException if the IP address of the host cannot be
+ * determined
+ */
+ @Override
+ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
+ throws IOException, UnknownHostException, ConnectTimeoutException {
+ if (params == null) {
+ throw new IllegalArgumentException("Parameters may not be null");
+ }
+ int timeout = params.getConnectionTimeout();
+ SocketFactory socketfactory = getSSLContext().getSocketFactory();
+ if (timeout == 0) {
+ Socket socket = socketfactory.createSocket(host, port, localAddress, localPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ } else {
+ Socket socket = socketfactory.createSocket();
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
+ SocketAddress remoteaddr = new InetSocketAddress(host, port);
+ socket.bind(localaddr);
+ socket.connect(remoteaddr, timeout);
+ return socket;
+ }
+ }
+
+ /**
+ * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
+ */
+ @Override
+ public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
+ Socket socket = (Socket) getSSLContext().getSocketFactory().createSocket(host, port);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
+ Socket s = getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
+ if (s instanceof SSLSocket) {
+ ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
+ }
+ return s;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class));
+ }
+
+ @Override
+ public int hashCode() {
+ return EasySSLProtocolSocketFactory.class.hashCode();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
new file mode 100644
index 0000000..eb23eb2
--- /dev/null
+++ b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
@@ -0,0 +1,110 @@
+//
+// 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.commons.httpclient.contrib.ssl;
+
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * <p>
+ * EasyX509TrustManager unlike default {@link X509TrustManager} accepts
+ * self-signed certificates.
+ * </p>
+ * <p>
+ * This trust manager SHOULD NOT be used for productive systems
+ * due to security reasons, unless it is a concious decision and
+ * you are perfectly aware of security implications of accepting
+ * self-signed certificates
+ * </p>
+ *
+ * @author <a href="mailto:adrian.sutton@ephox.com">Adrian Sutton</a>
+ * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ *
+ * <p>
+ * DISCLAIMER: HttpClient developers DO NOT actively support this component.
+ * The component is provided as a reference material, which may be inappropriate
+ * for use without additional customization.
+ * </p>
+ */
+
+public class EasyX509TrustManager implements X509TrustManager {
+ private X509TrustManager standardTrustManager = null;
+
+ /** Log object for this class. */
+ private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class);
+
+ /**
+ * Constructor for EasyX509TrustManager.
+ */
+ public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
+ super();
+ TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ factory.init(keystore);
+ TrustManager[] trustmanagers = factory.getTrustManagers();
+ if (trustmanagers.length == 0) {
+ throw new NoSuchAlgorithmException("no trust manager found");
+ }
+ standardTrustManager = (X509TrustManager)trustmanagers[0];
+ }
+
+ /**
+ * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
+ */
+ @Override
+ public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
+ standardTrustManager.checkClientTrusted(certificates, authType);
+ }
+
+ /**
+ * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
+ */
+ @Override
+ public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
+ if ((certificates != null) && LOG.isDebugEnabled()) {
+ LOG.debug("Server certificate chain:");
+ for (int i = 0; i < certificates.length; i++) {
+ LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
+ }
+ }
+ if ((certificates != null) && (certificates.length == 1)) {
+ certificates[0].checkValidity();
+ } else {
+ standardTrustManager.checkServerTrusted(certificates, authType);
+ }
+ }
+
+ /**
+ * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
+ */
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return standardTrustManager.getAcceptedIssuers();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/resources/cloud.keystore
----------------------------------------------------------------------
diff --git a/utils/src/main/resources/cloud.keystore b/utils/src/main/resources/cloud.keystore
new file mode 100644
index 0000000..33d7777
Binary files /dev/null and b/utils/src/main/resources/cloud.keystore differ
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java b/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java
deleted file mode 100644
index 85704a5..0000000
--- a/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java
+++ /dev/null
@@ -1,24 +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.utils.baremetal;
-
-public class BaremetalUtils {
- public static final String BAREMETAL_SYSTEM_ACCOUNT_NAME = "baremetal-system-account";
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java
deleted file mode 100644
index 4143f09..0000000
--- a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java
+++ /dev/null
@@ -1,123 +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.utils.graphite;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.HashMap;
-import java.util.Map;
-
-public class GraphiteClient {
-
- private String graphiteHost;
- private int graphitePort;
-
- /**
- * Create a new Graphite client
- *
- * @param graphiteHost Hostname of the Graphite host
- * @param graphitePort UDP port of the Graphite host
- */
- public GraphiteClient(String graphiteHost, int graphitePort) {
- this.graphiteHost = graphiteHost;
- this.graphitePort = graphitePort;
- }
-
- /**
- * Create a new Graphite client
- *
- * @param graphiteHost Hostname of the Graphite host. Will default to port 2003
- */
- public GraphiteClient(String graphiteHost) {
- this.graphiteHost = graphiteHost;
- graphitePort = 2003;
- }
-
- /**
- * Get the current system timestamp to pass to Graphite
- *
- * @return Seconds passed since epoch (01-01-1970)
- */
- protected long getCurrentSystemTime() {
- return System.currentTimeMillis() / 1000;
- }
-
- /**
- * Send a array of metrics to graphite.
- *
- * @param metrics the metrics as key-value-pairs
- */
- public void sendMetrics(Map<String, Integer> metrics) {
- sendMetrics(metrics, getCurrentSystemTime());
- }
-
- /**
- * Send a array of metrics with a given timestamp to graphite.
- *
- * @param metrics the metrics as key-value-pairs
- * @param timeStamp the timestamp
- */
- public void sendMetrics(Map<String, Integer> metrics, long timeStamp) {
- try (DatagramSocket sock = new DatagramSocket()){
- java.security.Security.setProperty("networkaddress.cache.ttl", "0");
- InetAddress addr = InetAddress.getByName(this.graphiteHost);
-
- for (Map.Entry<String, Integer> metric: metrics.entrySet()) {
- byte[] message = new String(metric.getKey() + " " + metric.getValue() + " " + timeStamp + "\n").getBytes();
- DatagramPacket packet = new DatagramPacket(message, message.length, addr, graphitePort);
- sock.send(packet);
- }
- } catch (UnknownHostException e) {
- throw new GraphiteException("Unknown host: " + graphiteHost);
- } catch (IOException e) {
- throw new GraphiteException("Error while writing to graphite: " + e.getMessage(), e);
- }
- }
-
- /**
- * Send a single metric with the current time as timestamp to graphite.
- *
- * @param key The metric key
- * @param value the metric value
- *
- * @throws GraphiteException if sending data to graphite failed
- */
- public void sendMetric(String key, int value) {
- sendMetric(key, value, getCurrentSystemTime());
- }
-
- /**
- * Send a single metric with a given timestamp to graphite.
- *
- * @param key The metric key
- * @param value The metric value
- * @param timeStamp the timestamp to use
- *
- * @throws GraphiteException if sending data to graphite failed
- */
- public void sendMetric(final String key, final int value, long timeStamp) {
- HashMap metrics = new HashMap<String, Integer>();
- metrics.put(key, value);
- sendMetrics(metrics, timeStamp);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java
deleted file mode 100644
index 9148764..0000000
--- a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java
+++ /dev/null
@@ -1,31 +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.utils.graphite;
-
-public class GraphiteException extends RuntimeException {
-
- public GraphiteException(String message) {
- super(message);
- }
-
- public GraphiteException(String message, Throwable cause) {
- super(message, cause);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java
deleted file mode 100644
index fdd80f7..0000000
--- a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java
+++ /dev/null
@@ -1,63 +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.utils.identity;
-
-import javax.ejb.Local;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.component.AdapterBase;
-import com.cloud.utils.component.ComponentLifecycle;
-import com.cloud.utils.component.SystemIntegrityChecker;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.net.MacAddress;
-
-@Local(value = {SystemIntegrityChecker.class})
-public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker {
- private static final Logger s_logger = Logger.getLogger(ManagementServerNode.class);
-
- private static final long s_nodeId = MacAddress.getMacAddress().toLong();
-
- public ManagementServerNode() {
- setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP);
- }
-
- @Override
- public void check() {
- if (s_nodeId <= 0) {
- throw new CloudRuntimeException("Unable to get the management server node id");
- }
- }
-
- public static long getManagementServerId() {
- return s_nodeId;
- }
-
- @Override
- public boolean start() {
- try {
- check();
- } catch (Exception e) {
- s_logger.error("System integrity check exception", e);
- System.exit(1);
- }
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java b/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java
deleted file mode 100644
index ed13360..0000000
--- a/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java
+++ /dev/null
@@ -1,110 +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.utils.imagestore;
-
-import com.cloud.utils.script.Script;
-import org.apache.commons.lang.StringUtils;
-import org.apache.log4j.Logger;
-
-public class ImageStoreUtil {
- public static final Logger s_logger = Logger.getLogger(ImageStoreUtil.class.getName());
-
- public static String generatePostUploadUrl(String ssvmUrlDomain, String ipAddress, String uuid) {
- String hostname = ipAddress;
-
- //if ssvm url domain is present, use it to construct hostname in the format 1-2-3-4.domain
- // if the domain name is not present, ssl validation fails and has to be ignored
- if(StringUtils.isNotBlank(ssvmUrlDomain)) {
- hostname = ipAddress.replace(".", "-");
- hostname = hostname + ssvmUrlDomain.substring(1);
- }
-
- //only https works with postupload and url format is fixed
- return "https://" + hostname + "/upload/" + uuid;
- }
-
- // given a path, returns empty if path is supported image, and the file type if unsupported
- // this is meant to catch things like accidental upload of ASCII text .vmdk descriptor
- public static String checkTemplateFormat(String path, String uripath) {
- // note 'path' was generated by us so it should be safe on the cmdline, be wary of 'url'
- String command = "file ";
- if (isCompressedExtension(uripath)) {
- command = "file -z ";
- }
- String output = Script.runSimpleBashScript(command + path + " | cut -d: -f2", 60000);
-
- // vmdk
- if ((output.contains("VMware") || output.contains("data")) && isCorrectExtension(uripath, "vmdk")) {
- s_logger.debug("File at path " + path + " looks like a vmware image :" + output);
- return "";
- }
- // raw
- if ((output.contains("x86 boot") || output.contains("data")) && (isCorrectExtension(uripath, "raw") || isCorrectExtension(uripath, "img"))) {
- s_logger.debug("File at path " + path + " looks like a raw image :" + output);
- return "";
- }
- // qcow2
- if (output.contains("QEMU QCOW") && isCorrectExtension(uripath, "qcow2")) {
- s_logger.debug("File at path " + path + " looks like QCOW2 : " + output);
- return "";
- }
- // vhd
- if (output.contains("Microsoft Disk Image") && (isCorrectExtension(uripath, "vhd") || isCorrectExtension(uripath, "vhdx"))) {
- s_logger.debug("File at path " + path + " looks like vhd : " + output);
- return "";
- }
- // ova
- if (output.contains("POSIX tar") && isCorrectExtension(uripath, "ova")) {
- s_logger.debug("File at path " + path + " looks like ova : " + output);
- return "";
- }
-
- //lxc
- if (output.contains("POSIX tar") && isCorrectExtension(uripath, "tar")) {
- s_logger.debug("File at path " + path + " looks like just tar : " + output);
- return "";
- }
-
- if (output.contains("ISO 9660") && isCorrectExtension(uripath, "iso")) {
- s_logger.debug("File at path " + path + " looks like an iso : " + output);
- return "";
- }
- return output;
- }
-
- private static boolean isCorrectExtension(String path, String ext) {
- if (path.toLowerCase().endsWith(ext)
- || path.toLowerCase().endsWith(ext + ".gz")
- || path.toLowerCase().endsWith(ext + ".bz2")
- || path.toLowerCase().endsWith(ext + ".zip")) {
- return true;
- }
- return false;
- }
-
- private static boolean isCompressedExtension(String path) {
- if (path.toLowerCase().endsWith(".gz")
- || path.toLowerCase().endsWith(".bz2")
- || path.toLowerCase().endsWith(".zip")) {
- return true;
- }
- return false;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java b/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java
deleted file mode 100644
index c1fc2d6..0000000
--- a/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java
+++ /dev/null
@@ -1,58 +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.utils.security;
-
-import org.apache.log4j.Logger;
-
-import javax.net.ssl.SSLContext;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-public class SSLUtils {
- public static final Logger s_logger = Logger.getLogger(SSLUtils.class);
-
- public static String[] getSupportedProtocols(String[] protocols) {
- Set<String> set = new HashSet<String>();
- for (String s : protocols) {
- if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
- continue;
- }
- set.add(s);
- }
- return (String[]) set.toArray(new String[set.size()]);
- }
-
- public static String[] getSupportedCiphers() throws NoSuchAlgorithmException {
- String[] availableCiphers = getSSLContext().getSocketFactory().getSupportedCipherSuites();
- Arrays.sort(availableCiphers);
- return availableCiphers;
- }
-
- public static SSLContext getSSLContext() throws NoSuchAlgorithmException {
- return SSLContext.getInstance("TLSv1");
- }
-
- public static SSLContext getSSLContext(String provider) throws NoSuchAlgorithmException, NoSuchProviderException {
- return SSLContext.getInstance("TLSv1", provider);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java b/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java
deleted file mode 100644
index fa9d492..0000000
--- a/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java
+++ /dev/null
@@ -1,124 +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.utils.security;
-
-import org.apache.log4j.Logger;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-
-public class SecureSSLSocketFactory extends SSLSocketFactory {
-
- public static final Logger s_logger = Logger.getLogger(SecureSSLSocketFactory.class);
- private SSLContext _sslContext;
-
- public SecureSSLSocketFactory() throws NoSuchAlgorithmException {
- _sslContext = SSLUtils.getSSLContext();
- }
-
- public SecureSSLSocketFactory(SSLContext sslContext) throws NoSuchAlgorithmException {
- if (sslContext != null) {
- _sslContext = sslContext;
- } else {
- _sslContext = SSLUtils.getSSLContext();
- }
- }
-
- public SecureSSLSocketFactory(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException, IOException {
- _sslContext = SSLUtils.getSSLContext();
- _sslContext.init(km, tm, random);
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return getSupportedCipherSuites();
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- String[] ciphers = null;
- try {
- ciphers = SSLUtils.getSupportedCiphers();
- } catch (NoSuchAlgorithmException e) {
- s_logger.error("SecureSSLSocketFactory::getDefaultCipherSuites found no cipher suites");
- }
- return ciphers;
- }
-
- @Override
- public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
- SSLSocketFactory factory = _sslContext.getSocketFactory();
- Socket socket = factory.createSocket(s, host, port, autoClose);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- SSLSocketFactory factory = _sslContext.getSocketFactory();
- Socket socket = factory.createSocket(host, port);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress inetAddress, int localPort) throws IOException, UnknownHostException {
- SSLSocketFactory factory = _sslContext.getSocketFactory();
- Socket socket = factory.createSocket(host, port, inetAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- @Override
- public Socket createSocket(InetAddress inetAddress, int localPort) throws IOException {
- SSLSocketFactory factory = _sslContext.getSocketFactory();
- Socket socket = factory.createSocket(inetAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
- SSLSocketFactory factory = this._sslContext.getSocketFactory();
- Socket socket = factory.createSocket(address, port, localAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java b/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java
deleted file mode 100644
index a97aed1..0000000
--- a/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java
+++ /dev/null
@@ -1,24 +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.utils.usage;
-
-public class UsageUtils {
- public static final int USAGE_AGGREGATION_RANGE_MIN = 1;
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java b/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
deleted file mode 100644
index 5ff5819..0000000
--- a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
+++ /dev/null
@@ -1,210 +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.commons.httpclient.contrib.ssl;
-
-import org.apache.cloudstack.utils.security.SSLUtils;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.HttpClientError;
-import org.apache.commons.httpclient.params.HttpConnectionParams;
-import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import javax.net.SocketFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.TrustManager;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.UnknownHostException;
-
-/**
- * <p>
- * EasySSLProtocolSocketFactory can be used to create SSL {@link Socket}s
- * that accept self-signed certificates.
- * </p>
- * <p>
- * This socket factory SHOULD NOT be used for productive systems
- * due to security reasons, unless it is a concious decision and
- * you are perfectly aware of security implications of accepting
- * self-signed certificates
- * </p>
- *
- * <p>
- * Example of using custom protocol socket factory for a specific host:
- * <pre>
- * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- *
- * URI uri = new URI("https://localhost/", true);
- * // use relative url only
- * GetMethod httpget = new GetMethod(uri.getPathQuery());
- * HostConfiguration hc = new HostConfiguration();
- * hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
- * HttpClient client = new HttpClient();
- * client.executeMethod(hc, httpget);
- * </pre>
- * </p>
- * <p>
- * Example of using custom protocol socket factory per default instead of the standard one:
- * <pre>
- * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- * Protocol.registerProtocol("https", easyhttps);
- *
- * HttpClient client = new HttpClient();
- * GetMethod httpget = new GetMethod("https://localhost/");
- * client.executeMethod(httpget);
- * </pre>
- * </p>
- *
- * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
- *
- * <p>
- * DISCLAIMER: HttpClient developers DO NOT actively support this component.
- * The component is provided as a reference material, which may be inappropriate
- * for use without additional customization.
- * </p>
- */
-
-public class EasySSLProtocolSocketFactory implements ProtocolSocketFactory {
-
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class);
-
- private SSLContext sslcontext = null;
-
- /**
- * Constructor for EasySSLProtocolSocketFactory.
- */
- public EasySSLProtocolSocketFactory() {
- super();
- }
-
- private static SSLContext createEasySSLContext() {
- try {
- SSLContext context = SSLUtils.getSSLContext();
- context.init(null, new TrustManager[] {new EasyX509TrustManager(null)}, null);
- return context;
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- throw new HttpClientError(e.toString());
- }
- }
-
- private SSLContext getSSLContext() {
- if (sslcontext == null) {
- sslcontext = createEasySSLContext();
- }
- return sslcontext;
- }
-
- /**
- * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
- */
- @Override
- public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
- Socket socket = getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- /**
- * Attempts to get a new socket connection to the given host within the given time limit.
- * <p>
- * To circumvent the limitations of older JREs that do not support connect timeout a
- * controller thread is executed. The controller thread attempts to create a new socket
- * within the given limit of time. If socket constructor does not return until the
- * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
- * </p>
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param params {@link HttpConnectionParams Http connection parameters}
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- */
- @Override
- public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
- throws IOException, UnknownHostException, ConnectTimeoutException {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- int timeout = params.getConnectionTimeout();
- SocketFactory socketfactory = getSSLContext().getSocketFactory();
- if (timeout == 0) {
- Socket socket = socketfactory.createSocket(host, port, localAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- } else {
- Socket socket = socketfactory.createSocket();
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
- SocketAddress remoteaddr = new InetSocketAddress(host, port);
- socket.bind(localaddr);
- socket.connect(remoteaddr, timeout);
- return socket;
- }
- }
-
- /**
- * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
- */
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- Socket socket = (Socket) getSSLContext().getSocketFactory().createSocket(host, port);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
- Socket s = getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
- if (s instanceof SSLSocket) {
- ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
- }
- return s;
- }
-
- @Override
- public boolean equals(Object obj) {
- return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class));
- }
-
- @Override
- public int hashCode() {
- return EasySSLProtocolSocketFactory.class.hashCode();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java b/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
deleted file mode 100644
index eb23eb2..0000000
--- a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
+++ /dev/null
@@ -1,110 +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.commons.httpclient.contrib.ssl;
-
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509TrustManager;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * <p>
- * EasyX509TrustManager unlike default {@link X509TrustManager} accepts
- * self-signed certificates.
- * </p>
- * <p>
- * This trust manager SHOULD NOT be used for productive systems
- * due to security reasons, unless it is a concious decision and
- * you are perfectly aware of security implications of accepting
- * self-signed certificates
- * </p>
- *
- * @author <a href="mailto:adrian.sutton@ephox.com">Adrian Sutton</a>
- * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
- *
- * <p>
- * DISCLAIMER: HttpClient developers DO NOT actively support this component.
- * The component is provided as a reference material, which may be inappropriate
- * for use without additional customization.
- * </p>
- */
-
-public class EasyX509TrustManager implements X509TrustManager {
- private X509TrustManager standardTrustManager = null;
-
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class);
-
- /**
- * Constructor for EasyX509TrustManager.
- */
- public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
- super();
- TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
- factory.init(keystore);
- TrustManager[] trustmanagers = factory.getTrustManagers();
- if (trustmanagers.length == 0) {
- throw new NoSuchAlgorithmException("no trust manager found");
- }
- standardTrustManager = (X509TrustManager)trustmanagers[0];
- }
-
- /**
- * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
- */
- @Override
- public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
- standardTrustManager.checkClientTrusted(certificates, authType);
- }
-
- /**
- * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
- */
- @Override
- public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
- if ((certificates != null) && LOG.isDebugEnabled()) {
- LOG.debug("Server certificate chain:");
- for (int i = 0; i < certificates.length; i++) {
- LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
- }
- }
- if ((certificates != null) && (certificates.length == 1)) {
- certificates[0].checkValidity();
- } else {
- standardTrustManager.checkServerTrusted(certificates, authType);
- }
- }
-
- /**
- * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
- */
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return standardTrustManager.getAcceptedIssuers();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DateUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/DateUtilTest.java b/utils/src/test/java/com/cloud/utils/DateUtilTest.java
new file mode 100644
index 0000000..ba88505
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/DateUtilTest.java
@@ -0,0 +1,60 @@
+//
+// 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 com.cloud.utils;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+
+import com.cloud.utils.DateUtil.IntervalType;
+
+
+public class DateUtilTest {
+
+ // command line test tool
+ public static void main(String[] args) {
+ TimeZone localTimezone = Calendar.getInstance().getTimeZone();
+ TimeZone gmtTimezone = TimeZone.getTimeZone("GMT");
+ TimeZone estTimezone = TimeZone.getTimeZone("EST");
+
+ Date time = new Date();
+ System.out.println("local time :" + DateUtil.getDateDisplayString(localTimezone, time));
+ System.out.println("GMT time :" + DateUtil.getDateDisplayString(gmtTimezone, time));
+ System.out.println("EST time :" + DateUtil.getDateDisplayString(estTimezone, time));
+ //Test next run time. Expects interval and schedule as arguments
+ if (args.length == 2) {
+ System.out.println("Next run time: " + DateUtil.getNextRunTime(IntervalType.getIntervalType(args[0]), args[1], "GMT", time).toString());
+ }
+
+ time = new Date();
+ DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z");
+ String str = dfDate.format(time);
+ System.out.println("Formated TZ time string : " + str);
+ try {
+ Date dtParsed = DateUtil.parseTZDateString(str);
+ System.out.println("Parsed TZ time string : " + dtParsed.toString());
+ } catch (ParseException e) {
+ System.err.println("Parsing failed\n string : " + str + "\nexception :" + e.getLocalizedMessage());
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DummyImpl.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/DummyImpl.java b/utils/src/test/java/com/cloud/utils/DummyImpl.java
new file mode 100644
index 0000000..e2360c0
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/DummyImpl.java
@@ -0,0 +1,31 @@
+//
+// 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 com.cloud.utils;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class DummyImpl implements DummyInterface {
+
+ @Override
+ public void foo() {
+ System.out.println("Basic foo implementation");
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DummyInterface.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/DummyInterface.java b/utils/src/test/java/com/cloud/utils/DummyInterface.java
new file mode 100644
index 0000000..4f6a777
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/DummyInterface.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.utils;
+
+public interface DummyInterface {
+ void foo();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java b/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java
new file mode 100644
index 0000000..9c71368
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java
@@ -0,0 +1,28 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+public class DummyPremiumImpl implements DummyInterface {
+
+ @Override
+ public void foo() {
+ System.out.println("Premium foo implementation");
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java b/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java
new file mode 100644
index 0000000..e10a5a3
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java
@@ -0,0 +1,94 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import org.junit.Test;
+import org.springframework.mock.web.MockHttpSession;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpSession;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class HttpUtilsTest {
+
+ @Test
+ public void findCookieTest() {
+ Cookie[] cookies = null;
+ String cookieName = null;
+
+ // null test
+ assertNull(HttpUtils.findCookie(cookies, cookieName));
+ cookieName = "";
+ assertNull(HttpUtils.findCookie(cookies, cookieName));
+
+ // value test
+ cookieName = "daakuBandar";
+ cookies = new Cookie[]{new Cookie(cookieName, "someValue")};
+ assertNull(HttpUtils.findCookie(cookies, "aalasiLangur"));
+ assertNotNull(HttpUtils.findCookie(cookies, cookieName));
+ }
+
+ @Test
+ public void validateSessionKeyTest() {
+ HttpSession session = null;
+ Map<String, Object[]> params = null;
+ String sessionKeyString = null;
+ Cookie[] cookies = null;
+ final String sessionKeyValue = "randomUniqueSessionID";
+
+ // session and sessionKeyString null test
+ assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+ sessionKeyString = "sessionkey";
+ assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+
+ // param and cookie null test
+ session = new MockHttpSession();
+ session.setAttribute(sessionKeyString, sessionKeyValue);
+ assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+
+ // param null, cookies not null test
+ params = null;
+ cookies = new Cookie[]{new Cookie(sessionKeyString, sessionKeyValue)};
+ assertFalse(HttpUtils.validateSessionKey(session, params, cookies, "randomString"));
+ assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+
+ // param not null, cookies null test
+ params = new HashMap<String, Object[]>();
+ params.put(sessionKeyString, new String[]{"randomString"});
+ cookies = null;
+ assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+ params.put(sessionKeyString, new String[]{sessionKeyValue});
+ assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+
+ // both param and cookies not null test
+ params = new HashMap<String, Object[]>();
+ cookies = new Cookie[]{new Cookie(sessionKeyString, sessionKeyValue)};
+ params.put(sessionKeyString, new String[]{"incorrectValue"});
+ assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+ params.put(sessionKeyString, new String[]{sessionKeyValue});
+ assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java
new file mode 100644
index 0000000..82b2305
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java
@@ -0,0 +1,47 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Locale;
+
+import org.junit.Test;
+
+public class NumbersUtilTest {
+
+ @Test
+ public void toReadableSize() {
+ Locale.setDefault(Locale.US); // Fixed locale for the test
+ assertEquals("1.0000 TB", NumbersUtil.toReadableSize((1024l * 1024l * 1024l * 1024l)));
+ assertEquals("1.00 GB", NumbersUtil.toReadableSize(1024 * 1024 * 1024));
+ assertEquals("1.00 MB", NumbersUtil.toReadableSize(1024 * 1024));
+ assertEquals("1.00 KB", NumbersUtil.toReadableSize((1024)));
+ assertEquals("1023 bytes", NumbersUtil.toReadableSize((1023)));
+ }
+
+ @Test
+ public void bytesToLong() {
+ assertEquals(0, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 0}));
+ assertEquals(1, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 1}));
+ assertEquals(257, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 1, 1}));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java b/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java
new file mode 100644
index 0000000..413b866
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java
@@ -0,0 +1,42 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class PasswordGeneratorTest {
+ @Test
+ public void generateRandomPassword() {
+ // actual length is requested length, minimum length is 3
+ Assert.assertTrue(PasswordGenerator.generateRandomPassword(0).length() == 3);
+ Assert.assertTrue(PasswordGenerator.generateRandomPassword(1).length() == 3);
+ Assert.assertTrue(PasswordGenerator.generateRandomPassword(5).length() == 5);
+ String password = PasswordGenerator.generateRandomPassword(8);
+ // TODO: this might give more help to bruteforcing than desired
+ // the actual behavior is that the first character is a random lowercase
+ // char
+ Assert.assertTrue(Character.isLowerCase(password.charAt(0)));
+ // the second character is a random upper case char
+ Assert.assertTrue(Character.isUpperCase(password.charAt(1)));
+ // and the third is a digit
+ Assert.assertTrue(Character.isDigit(password.charAt(2)));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java b/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java
new file mode 100644
index 0000000..38e25a3
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java
@@ -0,0 +1,76 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.io.IOException;
+
+import javax.naming.ConfigurationException;
+
+import junit.framework.Assert;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.SystemUtils;
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ProcessUtilTest {
+
+ File pidFile;
+
+ @Before
+ public void setup() throws IOException {
+ pidFile = File.createTempFile("test", ".pid");
+ }
+
+ @After
+ public void cleanup() {
+ FileUtils.deleteQuietly(pidFile);
+ }
+
+ @Test
+ public void pidCheck() throws ConfigurationException, IOException {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ FileUtils.writeStringToFile(pidFile, "123456\n");
+ ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
+ String pidStr = FileUtils.readFileToString(pidFile);
+ Assert.assertFalse("pid can not be blank", pidStr.isEmpty());
+ int pid = Integer.parseInt(pidStr.trim());
+ int maxPid = Integer.parseInt(FileUtils.readFileToString(new File("/proc/sys/kernel/pid_max")).trim());
+ Assert.assertTrue(pid <= maxPid);
+ }
+
+ @Test(expected = ConfigurationException.class)
+ public void pidCheckBadPid() throws ConfigurationException, IOException {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ FileUtils.writeStringToFile(pidFile, "intentionally not number");
+ ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
+ }
+
+ @Test(expected = ConfigurationException.class)
+ public void pidCheckEmptyPid() throws ConfigurationException, IOException {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ FileUtils.writeStringToFile(pidFile, "intentionally not number");
+ ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java b/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java
new file mode 100644
index 0000000..e20d7bf
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java
@@ -0,0 +1,64 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class PropertiesUtilsTest {
+ @Test
+ public void findConfigFile() {
+ File configFile = PropertiesUtil.findConfigFile("notexistingresource");
+ Assert.assertNull(configFile);
+ }
+
+ @Test
+ public void loadFromFile() throws IOException {
+ File file = File.createTempFile("test", ".properties");
+ FileUtils.writeStringToFile(file, "a=b\nc=d\n");
+ Properties properties = new Properties();
+ PropertiesUtil.loadFromFile(properties, file);
+ Assert.assertEquals("b", properties.get("a"));
+ }
+
+ @Test
+ public void loadPropertiesFromFile() throws IOException {
+ File file = File.createTempFile("test", ".properties");
+ FileUtils.writeStringToFile(file, "a=b\nc=d\n");
+ Properties properties = PropertiesUtil.loadFromFile(file);
+ Assert.assertEquals("b", properties.get("a"));
+ }
+
+ @Test
+ public void processConfigFile() throws IOException {
+ File tempFile = File.createTempFile("temp", ".properties");
+ FileUtils.writeStringToFile(tempFile, "a=b\nc=d\n");
+ Map<String, String> config = PropertiesUtil.processConfigFile(new String[] {tempFile.getAbsolutePath()});
+ Assert.assertEquals("b", config.get("a"));
+ Assert.assertEquals("d", config.get("c"));
+ tempFile.delete();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java b/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java
new file mode 100644
index 0000000..c024a2e
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java
@@ -0,0 +1,148 @@
+//
+// 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 com.cloud.utils;
+
+import static com.cloud.utils.ReflectUtil.flattenProperties;
+import static com.google.common.collect.Lists.newArrayList;
+import static java.lang.Boolean.TRUE;
+import static java.util.Collections.emptyList;
+import static org.junit.Assert.assertEquals;
+
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public final class ReflectUtilTest {
+
+ @Test
+ public void testFlattenNonNullProperties() throws Exception {
+
+ final List<String> expectedResult = newArrayList("booleanProperty", TRUE.toString(), "intProperty", "1", "stringProperty", "foo");
+
+ final Bean bean = new Bean(1, true, "foo");
+
+ assertEquals(expectedResult, flattenProperties(bean, Bean.class));
+
+ }
+
+ @Test
+ public void testFlattenNullProperties() throws Exception {
+
+ final List<String> expectedResult = newArrayList("booleanProperty", TRUE.toString(), "intProperty", "1", "stringProperty", "null");
+
+ final Bean bean = new Bean(1, true, null);
+
+ assertEquals(expectedResult, flattenProperties(bean, Bean.class));
+
+ }
+
+ @Test
+ public void testFlattenPropertiesNullTarget() throws Exception {
+ assertEquals(emptyList(), flattenProperties(null, Bean.class));
+ }
+
+ public static final class Bean {
+
+ private final int intProperty;
+ private final boolean booleanProperty;
+ private final String stringProperty;
+
+ private Bean(final int intProperty, final boolean booleanProperty, final String stringProperty) {
+
+ super();
+
+ this.intProperty = intProperty;
+ this.booleanProperty = booleanProperty;
+ this.stringProperty = stringProperty;
+
+ }
+
+ public int getIntProperty() {
+ return intProperty;
+ }
+
+ public boolean isBooleanProperty() {
+ return booleanProperty;
+ }
+
+ public String getStringProperty() {
+ return stringProperty;
+ }
+
+ }
+
+ static class Empty {
+ }
+
+ static class Foo {
+ String fooField;
+ int fooIntField;
+ }
+
+ static class Bar extends Foo {
+ String barField;
+ int barIntField;
+ }
+
+ static class Baz extends Foo {
+ String bazField;
+ int bazIntField;
+ }
+
+ @Test
+ public void getAllFieldsForClassWithFoo() throws NoSuchFieldException, SecurityException {
+ Set<Field> fooFields = ReflectUtil.getAllFieldsForClass(Foo.class, new Class<?>[] {});
+ Assert.assertNotNull(fooFields);
+ Assert.assertTrue(fooFields.contains(Foo.class.getDeclaredField("fooField")));
+ Assert.assertTrue(fooFields.contains(Foo.class.getDeclaredField("fooIntField")));
+ }
+
+ @Test
+ public void getAllFieldsForClassWithBar() throws NoSuchFieldException, SecurityException {
+ Set<Field> barFields = ReflectUtil.getAllFieldsForClass(Bar.class, new Class<?>[] {});
+ Assert.assertNotNull(barFields);
+ Assert.assertTrue(barFields.contains(Foo.class.getDeclaredField("fooField")));
+ Assert.assertTrue(barFields.contains(Foo.class.getDeclaredField("fooIntField")));
+ Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barField")));
+ Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barIntField")));
+ }
+
+ @Test
+ public void getAllFieldsForClassWithBarWithoutFoo() throws NoSuchFieldException, SecurityException {
+ Set<Field> barFields = ReflectUtil.getAllFieldsForClass(Bar.class, new Class<?>[] {Foo.class});
+ Assert.assertNotNull(barFields);
+ Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barField")));
+ Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barIntField")));
+ }
+
+ @Test
+ public void getAllFieldsForClassWithBazWithoutBar() throws NoSuchFieldException, SecurityException {
+ Set<Field> bazFields = ReflectUtil.getAllFieldsForClass(Baz.class, new Class<?>[] {Bar.class});
+ Assert.assertNotNull(bazFields);
+ Assert.assertTrue(bazFields.contains(Foo.class.getDeclaredField("fooField")));
+ Assert.assertTrue(bazFields.contains(Foo.class.getDeclaredField("fooIntField")));
+ Assert.assertTrue(bazFields.contains(Baz.class.getDeclaredField("bazField")));
+ Assert.assertTrue(bazFields.contains(Baz.class.getDeclaredField("bazIntField")));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ScriptTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/ScriptTest.java b/utils/src/test/java/com/cloud/utils/ScriptTest.java
new file mode 100644
index 0000000..99059bf
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/ScriptTest.java
@@ -0,0 +1,135 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+
+import org.apache.commons.lang.SystemUtils;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+
+import com.cloud.utils.script.OutputInterpreter;
+import com.cloud.utils.script.Script;
+
+public class ScriptTest {
+ @Test
+ public void testEcho() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Script script = new Script("/bin/echo");
+ script.add("bar");
+ OutputInterpreter.AllLinesParser resultParser = new OutputInterpreter.AllLinesParser();
+ String result = script.execute(resultParser);
+ // With allLinesParser, result is not comming from the return value
+ Assert.assertNull(result);
+ Assert.assertEquals("bar\n", resultParser.getLines());
+ }
+
+ @Test
+ public void testLogger() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Logger mock = Mockito.mock(Logger.class);
+ Mockito.doNothing().when(mock).debug(Matchers.any());
+ Script script = new Script("/bin/echo", mock);
+ script.execute();
+ }
+
+ @Test
+ public void testToString() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Script script = new Script("/bin/echo");
+ script.add("foo");
+ Assert.assertEquals("/bin/echo foo ", script.toString());
+ }
+
+ @Test
+ public void testSet() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Script script = new Script("/bin/echo");
+ script.add("foo");
+ script.add("bar", "baz");
+ script.set("blah", "blah");
+ Assert.assertEquals("/bin/echo foo bar baz blah blah ",
+ script.toString());
+ }
+
+ @Test
+ @Ignore
+ public void testExecute() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Logger mock = Mockito.mock(Logger.class);
+ Mockito.doNothing().when(mock).debug(Matchers.any());
+ for (int i = 0; i < 100000; i++) {
+ Script script = new Script("/bin/false", mock);
+ script.execute();
+ }
+ }
+
+ @Test
+ public void testRunSimpleBashScript() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Assert.assertEquals("hello world!",
+ Script.runSimpleBashScript("echo 'hello world!'"));
+ }
+
+ @Test
+ public void executeWithOutputInterpreter() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Script script = new Script("/bin/bash");
+ script.add("-c");
+ script.add("echo 'hello world!'");
+ String value = script.execute(new OutputInterpreter() {
+
+ @Override
+ public String interpret(BufferedReader reader) throws IOException {
+ throw new IllegalArgumentException();
+ }
+ });
+ // it is a stack trace in this case as string
+ Assert.assertNotNull(value);
+ }
+
+ @Test
+ public void runSimpleBashScriptNotExisting() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ String output = Script.runSimpleBashScript("/not/existing/scripts/"
+ + System.currentTimeMillis());
+ Assert.assertNull(output);
+ }
+
+ @Test
+ public void testRunSimpleBashScriptWithTimeout() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ Assert.assertEquals("hello world!",
+ Script.runSimpleBashScript("echo 'hello world!'", 1000));
+ }
+
+ @Test
+ public void testFindScript() {
+ Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
+ String script = Script.findScript("/bin", "pwd");
+ Assert.assertNotNull("/bin/pwd shoud be there on linux", script);
+ }
+}
[26/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
deleted file mode 100644
index 447e21b..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
+++ /dev/null
@@ -1,999 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import java.util.List;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.DOMImplementation;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.ls.DOMImplementationLS;
-import org.w3c.dom.ls.LSSerializer;
-
-import com.cloud.utils.Pair;
-
-public class VsmCommand {
-
- private static final Logger s_logger = Logger.getLogger(VsmCommand.class);
- private static final String s_namespace = "urn:ietf:params:xml:ns:netconf:base:1.0";
- private static final String s_ciscons = "http://www.cisco.com/nxos:1.0:ppm";
- private static final String s_configuremode = "__XML__MODE__exec_configure";
- private static final String s_portprofmode = "__XML__MODE_port-prof";
- private static final String s_policymapmode = "__XML__MODE_policy-map";
- private static final String s_classtypemode = "__XML__MODE_policy-map_class_type";
- private static final String s_paramvalue = "__XML__PARAM_value";
-
- public enum PortProfileType {
- none, vethernet, ethernet;
- }
-
- public enum BindingType {
- none, portbindingstatic, portbindingdynamic, portbindingephermal;
- }
-
- public enum SwitchPortMode {
- none, access, trunk, privatevlanhost, privatevlanpromiscuous
- }
-
- public enum OperationType {
- addvlanid, removevlanid
- }
-
- public static String getAddPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(configPortProfileDetails(doc, name, type, binding, mode, vlanid, vdc, espName));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating add port profile message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating add port profile message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getAddPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(configPortProfileDetails(doc, name, type, binding, mode, vlanid));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating add port profile message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating add port profile message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getUpdatePortProfile(String name, SwitchPortMode mode, List<Pair<VsmCommand.OperationType, String>> params) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to update the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(configPortProfileDetails(doc, name, mode, params));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating update port profile message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating update port profile message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getDeletePortProfile(String portName) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(deletePortProfileDetails(doc, portName));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating delete port profile message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating delete port profile message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getAddPolicyMap(String name, int averageRate, int maxRate, int burstRate) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(policyMapDetails(doc, name, averageRate, maxRate, burstRate));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating policy map message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating policy map message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getDeletePolicyMap(String name) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(deletePolicyMapDetails(doc, name));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating delete policy map message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating delete policy map message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getServicePolicy(String policyMap, String portProfile, boolean attach) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(serviceDetails(doc, policyMap, portProfile, attach));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating attach/detach service policy message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating attach/detach service policy message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getPortProfile(String name) {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- Element get = doc.createElement("nf:get");
- doc.getDocumentElement().appendChild(get);
-
- Element filter = doc.createElement("nf:filter");
- filter.setAttribute("type", "subtree");
- get.appendChild(filter);
-
- // Create the show port-profile name <profile-name> command.
- Element show = doc.createElement("show");
- filter.appendChild(show);
- Element portProfile = doc.createElement("port-profile");
- show.appendChild(portProfile);
- Element nameNode = doc.createElement("name");
- portProfile.appendChild(nameNode);
-
- // Profile name
- Element profileName = doc.createElement("profile_name");
- profileName.setTextContent(name);
- nameNode.appendChild(profileName);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating the message to get port profile details: " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating the message to get port profile details: " + e.getMessage());
- return null;
- }
- }
-
- public static String getPolicyMap(String name) {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- Element get = doc.createElement("nf:get");
- doc.getDocumentElement().appendChild(get);
-
- Element filter = doc.createElement("nf:filter");
- filter.setAttribute("type", "subtree");
- get.appendChild(filter);
-
- // Create the show port-profile name <profile-name> command.
- Element show = doc.createElement("show");
- filter.appendChild(show);
- Element policyMap = doc.createElement("policy-map");
- show.appendChild(policyMap);
- Element nameNode = doc.createElement("name");
- nameNode.setTextContent(name);
- policyMap.appendChild(nameNode);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating the message to get policy map details : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating the message to get policy map details : " + e.getMessage());
- return null;
- }
- }
-
- public static String getHello() {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
-
- // Root elements.
- Document doc = domImpl.createDocument(s_namespace, "nc:hello", null);
-
- // Client capacity. We are only supporting basic capacity.
- Element capabilities = doc.createElement("nc:capabilities");
- Element capability = doc.createElement("nc:capability");
- capability.setTextContent("urn:ietf:params:xml:ns:netconf:base:1.0");
-
- capabilities.appendChild(capability);
- doc.getDocumentElement().appendChild(capabilities);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while creating hello message : " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while creating hello message : " + e.getMessage());
- return null;
- }
- }
-
- public static String getVServiceNode(String vlanId, String ipAddr) {
- try {
- // Create the document and root element.
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementation domImpl = docBuilder.getDOMImplementation();
- Document doc = createDocument(domImpl);
-
- // Edit configuration command.
- Element editConfig = doc.createElement("nf:edit-config");
- doc.getDocumentElement().appendChild(editConfig);
-
- // Command to get into exec configure mode.
- Element target = doc.createElement("nf:target");
- Element running = doc.createElement("nf:running");
- target.appendChild(running);
- editConfig.appendChild(target);
-
- // Command to create the port profile with the desired configuration.
- Element config = doc.createElement("nf:config");
- config.appendChild(configVServiceNodeDetails(doc, vlanId, ipAddr));
- editConfig.appendChild(config);
-
- return serialize(domImpl, doc);
- } catch (ParserConfigurationException e) {
- s_logger.error("Error while adding vservice node for vlan " + vlanId + ", " + e.getMessage());
- return null;
- } catch (DOMException e) {
- s_logger.error("Error while adding vservice node for vlan " + vlanId + ", " + e.getMessage());
- return null;
- }
- }
-
- private static Element configVServiceNodeDetails(Document doc, String vlanId, String ipAddr) {
- // In mode, exec_configure.
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // vservice node %name% type asa
- Element vservice = doc.createElement("vservice");
- vservice.appendChild(doc.createElement("node"))
- .appendChild(doc.createElement("ASA_" + vlanId))
- .appendChild(doc.createElement("type"))
- .appendChild(doc.createElement("asa"));
- modeConfigure.appendChild(vservice);
-
- Element address = doc.createElement(s_paramvalue);
- address.setAttribute("isKey", "true");
- address.setTextContent(ipAddr);
-
- // ip address %ipAddr%
- modeConfigure.appendChild(doc.createElement("ip")).appendChild(doc.createElement("address")).appendChild(doc.createElement("value")).appendChild(address);
-
- Element vlan = doc.createElement(s_paramvalue);
- vlan.setAttribute("isKey", "true");
- vlan.setTextContent(vlanId);
-
- // adjacency l2 vlan %vlanId%
- modeConfigure.appendChild(doc.createElement("adjacency"))
- .appendChild(doc.createElement("l2"))
- .appendChild(doc.createElement("vlan"))
- .appendChild(doc.createElement("value"))
- .appendChild(vlan);
-
- // fail-mode close
- modeConfigure.appendChild(doc.createElement("fail-mode")).appendChild(doc.createElement("close"));
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element configPortProfileDetails(Document doc, String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc,
- String espName) {
-
- // In mode, exec_configure.
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Port profile name and type configuration.
- Element portProfile = doc.createElement("port-profile");
- modeConfigure.appendChild(portProfile);
-
- // Port profile type.
- Element portDetails = doc.createElement("name");
- switch (type) {
- case none:
- portProfile.appendChild(portDetails);
- break;
- case ethernet: {
- Element typetag = doc.createElement("type");
- Element ethernettype = doc.createElement("ethernet");
- portProfile.appendChild(typetag);
- typetag.appendChild(ethernettype);
- ethernettype.appendChild(portDetails);
- }
- break;
- case vethernet: {
- Element typetag = doc.createElement("type");
- Element ethernettype = doc.createElement("vethernet");
- portProfile.appendChild(typetag);
- typetag.appendChild(ethernettype);
- ethernettype.appendChild(portDetails);
- }
- break;
- }
-
- // Port profile name.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(name);
- portDetails.appendChild(value);
-
- // element for port prof mode.
- Element portProf = doc.createElement(s_portprofmode);
- portDetails.appendChild(portProf);
-
- // Binding type.
- if (binding != BindingType.none) {
- portProf.appendChild(getBindingType(doc, binding));
- }
-
- if (mode != SwitchPortMode.none) {
- // Switchport mode.
- portProf.appendChild(getSwitchPortMode(doc, mode));
- // Adding vlan details.
- if (vlanid > 0) {
- portProf.appendChild(getAddVlanDetails(doc, mode, Integer.toString(vlanid)));
- }
- }
-
- // Command "vmware port-group".
- Element vmware = doc.createElement("vmware");
- Element portgroup = doc.createElement("port-group");
- vmware.appendChild(portgroup);
- portProf.appendChild(vmware);
-
- // org %vdc%
- // vservice node <Node Name> profile <Edge Security Profile Name in VNMC>
- Element vdcValue = doc.createElement(s_paramvalue);
- vdcValue.setAttribute("isKey", "true");
- vdcValue.setTextContent(vdc);
-
- Element org = doc.createElement("org");
- org.appendChild(doc.createElement("orgname")).appendChild(vdcValue);
- portProf.appendChild(org);
-
- String asaNodeName = "ASA_" + vlanid;
- Element vservice = doc.createElement("vservice");
- vservice.appendChild(doc.createElement("node"))
- .appendChild(doc.createElement(asaNodeName))
- .appendChild(doc.createElement("profile"))
- .appendChild(doc.createElement(espName));
- portProf.appendChild(vservice);
-
- // no shutdown.
- Element no = doc.createElement("no");
- Element shutdown = doc.createElement("shutdown");
- no.appendChild(shutdown);
- portProf.appendChild(no);
-
- // Enable the port profile.
- Element state = doc.createElement("state");
- Element enabled = doc.createElement("enabled");
- state.appendChild(enabled);
- portProf.appendChild(state);
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element configPortProfileDetails(Document doc, String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) {
-
- // In mode, exec_configure.
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Port profile name and type configuration.
- Element portProfile = doc.createElement("port-profile");
- modeConfigure.appendChild(portProfile);
-
- // Port profile type.
- Element portDetails = doc.createElement("name");
- switch (type) {
- case none:
- portProfile.appendChild(portDetails);
- break;
- case ethernet: {
- Element typetag = doc.createElement("type");
- Element ethernettype = doc.createElement("ethernet");
- portProfile.appendChild(typetag);
- typetag.appendChild(ethernettype);
- ethernettype.appendChild(portDetails);
- }
- break;
- case vethernet: {
- Element typetag = doc.createElement("type");
- Element ethernettype = doc.createElement("vethernet");
- portProfile.appendChild(typetag);
- typetag.appendChild(ethernettype);
- ethernettype.appendChild(portDetails);
- }
- break;
- }
-
- // Port profile name.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(name);
- portDetails.appendChild(value);
-
- // element for port prof mode.
- Element portProf = doc.createElement(s_portprofmode);
- portDetails.appendChild(portProf);
-
- // Binding type.
- if (binding != BindingType.none) {
- portProf.appendChild(getBindingType(doc, binding));
- }
-
- if (mode != SwitchPortMode.none) {
- // Switchport mode.
- portProf.appendChild(getSwitchPortMode(doc, mode));
- // Adding vlan details.
- if (vlanid > 0) {
- portProf.appendChild(getAddVlanDetails(doc, mode, Integer.toString(vlanid)));
- }
- }
-
- // Command "vmware port-group".
- Element vmware = doc.createElement("vmware");
- Element portgroup = doc.createElement("port-group");
- vmware.appendChild(portgroup);
- portProf.appendChild(vmware);
-
- // no shutdown.
- Element no = doc.createElement("no");
- Element shutdown = doc.createElement("shutdown");
- no.appendChild(shutdown);
- portProf.appendChild(no);
-
- // Enable the port profile.
- Element state = doc.createElement("state");
- Element enabled = doc.createElement("enabled");
- state.appendChild(enabled);
- portProf.appendChild(state);
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element configPortProfileDetails(Document doc, String name, SwitchPortMode mode, List<Pair<VsmCommand.OperationType, String>> params) {
-
- // In mode, exec_configure.
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Port profile name and type configuration.
- Element portProfile = doc.createElement("port-profile");
- modeConfigure.appendChild(portProfile);
-
- // Port profile type.
- Element portDetails = doc.createElement("name");
- portProfile.appendChild(portDetails);
-
- // Name of the profile to update.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(name);
- portDetails.appendChild(value);
-
- // element for port prof mode.
- Element portProfMode = doc.createElement(s_portprofmode);
- portDetails.appendChild(portProfMode);
-
- for (Pair<VsmCommand.OperationType, String> item : params) {
- if (item.first() == OperationType.addvlanid) {
- // Set the access mode configuration or the list
- // of allowed vlans on the trunking interface.
- portProfMode.appendChild(getAddVlanDetails(doc, mode, item.second()));
- } else if (item.first() == OperationType.removevlanid) {
- portProfMode.appendChild(getDeleteVlanDetails(doc, mode, item.second()));
- }
- }
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element deletePortProfileDetails(Document doc, String name) {
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Command and name for the port profile to be deleted.
- Element deletePortProfile = doc.createElement("no");
- modeConfigure.appendChild(deletePortProfile);
-
- Element portProfile = doc.createElement("port-profile");
- deletePortProfile.appendChild(portProfile);
-
- Element portDetails = doc.createElement("name");
- portProfile.appendChild(portDetails);
-
- // Name of the profile to delete.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(name);
- portDetails.appendChild(value);
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element policyMapDetails(Document doc, String name, int averageRate, int maxRate, int burstRate) {
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Policy map details
- Element policyMap = doc.createElement("policy-map");
- modeConfigure.appendChild(policyMap);
-
- Element policyDetails = doc.createElement("name");
- policyMap.appendChild(policyDetails);
-
- // Name of the policy to create/update.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(name);
- policyDetails.appendChild(value);
-
- Element policyMapMode = doc.createElement(s_policymapmode);
- policyDetails.appendChild(policyMapMode);
-
- // Create the default class to match all traffic.
- Element classRoot = doc.createElement("class");
- Element classDefault = doc.createElement("class-default");
- policyMapMode.appendChild(classRoot);
- classRoot.appendChild(classDefault);
-
- Element classMode = doc.createElement(s_classtypemode);
- classDefault.appendChild(classMode);
-
- // Set the average, max and burst rate.
- // TODO: Add handling for max and burst.
- Element police = doc.createElement("police");
- classMode.appendChild(police);
-
- // Set the committed information rate and its value in mbps.
- Element cir = doc.createElement("cir");
- police.appendChild(cir);
- Element cirValue = doc.createElement("cir-val");
- cir.appendChild(cirValue);
- Element value2 = doc.createElement(s_paramvalue);
- Element mbps = doc.createElement("mbps");
- value2.setTextContent(Integer.toString(averageRate));
- cirValue.appendChild(value2);
- cirValue.appendChild(mbps);
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element deletePolicyMapDetails(Document doc, String name) {
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Delete Policy map details
- Element deletePolicyMap = doc.createElement("no");
- Element policyMap = doc.createElement("policy-map");
- deletePolicyMap.appendChild(policyMap);
- modeConfigure.appendChild(deletePolicyMap);
-
- Element policyDetails = doc.createElement("name");
- policyMap.appendChild(policyDetails);
-
- // Name of the policy to create/update.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(name);
- policyDetails.appendChild(value);
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element serviceDetails(Document doc, String policyMap, String portProfile, boolean attach) {
- // In mode, exec_configure.
- Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
- Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
- configure.appendChild(modeConfigure);
-
- // Port profile name and type configuration.
- Element profile = doc.createElement("port-profile");
- modeConfigure.appendChild(profile);
-
- // Port profile type.
- Element portDetails = doc.createElement("name");
- profile.appendChild(portDetails);
-
- // Name of the profile to update.
- Element value = doc.createElement(s_paramvalue);
- value.setAttribute("isKey", "true");
- value.setTextContent(portProfile);
- portDetails.appendChild(value);
-
- // element for port prof mode.
- Element portProfMode = doc.createElement(s_portprofmode);
- portDetails.appendChild(portProfMode);
-
- // Associate/Remove the policy for input.
- if (attach) {
- portProfMode.appendChild(getServicePolicyCmd(doc, policyMap, "input"));
- } else {
- Element detach = doc.createElement("no");
- portProfMode.appendChild(detach);
- detach.appendChild(getServicePolicyCmd(doc, policyMap, "input"));
- }
-
- // Associate/Remove the policy for output.
- if (attach) {
- portProfMode.appendChild(getServicePolicyCmd(doc, policyMap, "output"));
- } else {
- Element detach = doc.createElement("no");
- portProfMode.appendChild(detach);
- detach.appendChild(getServicePolicyCmd(doc, policyMap, "output"));
- }
-
- // Persist the configuration across reboots.
- modeConfigure.appendChild(persistConfiguration(doc));
-
- return configure;
- }
-
- private static Element persistConfiguration(Document doc) {
- Element copy = doc.createElement("copy");
- Element running = doc.createElement("running-config");
- Element startup = doc.createElement("startup-config");
- copy.appendChild(running);
- running.appendChild(startup);
- return copy;
- }
-
- private static Element getAddVlanDetails(Document doc, SwitchPortMode mode, String vlanid) {
- Element switchport = doc.createElement("switchport");
-
- // Details of the vlanid to add.
- Element vlancreate = doc.createElement("vlan-id-create-delete");
- Element value = doc.createElement(s_paramvalue);
- value.setTextContent(vlanid);
- vlancreate.appendChild(value);
-
- // Handling is there only for 'access' and 'trunk allowed' mode command.
- if (mode == SwitchPortMode.access) {
- Element access = doc.createElement("access");
- switchport.appendChild(access);
-
- Element vlan = doc.createElement("vlan");
- access.appendChild(vlan);
-
- vlan.appendChild(vlancreate);
- } else if (mode == SwitchPortMode.trunk) {
- Element trunk = doc.createElement("trunk");
- switchport.appendChild(trunk);
-
- Element allowed = doc.createElement("allowed");
- trunk.appendChild(allowed);
-
- Element vlan = doc.createElement("vlan");
- allowed.appendChild(vlan);
-
- Element add = doc.createElement("add");
- vlan.appendChild(add);
-
- add.appendChild(vlancreate);
- }
-
- return switchport;
- }
-
- private static Node getDeleteVlanDetails(Document doc, SwitchPortMode mode, String vlanid) {
- Node parentNode = null;
- Element switchport = doc.createElement("switchport");
-
- // Handling is there only for 'access' and 'trunk allowed' mode command.
- if (mode == SwitchPortMode.access) {
- Element no = doc.createElement("no");
- no.appendChild(switchport);
- parentNode = no;
-
- Element access = doc.createElement("access");
- switchport.appendChild(access);
-
- Element vlan = doc.createElement("vlan");
- access.appendChild(vlan);
- } else if (mode == SwitchPortMode.trunk) {
- parentNode = switchport;
-
- Element trunk = doc.createElement("trunk");
- switchport.appendChild(trunk);
-
- Element allowed = doc.createElement("allowed");
- trunk.appendChild(allowed);
-
- Element vlan = doc.createElement("vlan");
- allowed.appendChild(vlan);
-
- Element remove = doc.createElement("remove");
- vlan.appendChild(remove);
-
- // Details of the vlanid to add.
- Element vlancreate = doc.createElement("vlan-id-create-delete");
- Element value = doc.createElement(s_paramvalue);
- value.setTextContent(vlanid);
- vlancreate.appendChild(value);
-
- remove.appendChild(vlancreate);
- }
-
- return parentNode;
- }
-
- private static Element getBindingType(Document doc, BindingType binding) {
- Element portBinding = doc.createElement("port-binding");
-
- // We only have handling for access or trunk mode. Handling for private-vlan
- // host/promiscuous command will have to be added.
- if (binding == BindingType.portbindingstatic) {
- Element type = doc.createElement("static");
- portBinding.appendChild(type);
- } else if (binding == BindingType.portbindingdynamic) {
- Element type = doc.createElement("dynamic");
- portBinding.appendChild(type);
- } else if (binding == BindingType.portbindingephermal) {
- Element type = doc.createElement("ephemeral");
- portBinding.appendChild(type);
- }
-
- return portBinding;
- }
-
- private static Element getSwitchPortMode(Document doc, SwitchPortMode mode) {
- Element switchport = doc.createElement("switchport");
- Element accessmode = doc.createElement("mode");
- switchport.appendChild(accessmode);
-
- // We only have handling for access or trunk mode. Handling for private-vlan
- // host/promiscuous command will have to be added.
- if (mode == SwitchPortMode.access) {
- Element access = doc.createElement("access");
- accessmode.appendChild(access);
- } else if (mode == SwitchPortMode.trunk) {
- Element trunk = doc.createElement("trunk");
- accessmode.appendChild(trunk);
- }
-
- return switchport;
- }
-
- private static Element getServicePolicyCmd(Document doc, String policyMap, String type) {
- Element service = doc.createElement("service-policy");
- Element input = doc.createElement(type);
- service.appendChild(input);
-
- Element name = doc.createElement("name");
- input.appendChild(name);
-
- Element policyValue = doc.createElement(s_paramvalue);
- policyValue.setTextContent(policyMap);
- name.appendChild(policyValue);
-
- return service;
- }
-
- private static Document createDocument(DOMImplementation dom) {
- Document doc = dom.createDocument(s_namespace, "nf:rpc", null);
- doc.getDocumentElement().setAttribute("message-id", "101");
- doc.getDocumentElement().setAttributeNS(s_ciscons, "portprofile", "true");
- return doc;
- }
-
- private static String serialize(DOMImplementation domImpl, Document document) {
- DOMImplementationLS ls = (DOMImplementationLS)domImpl;
- LSSerializer lss = ls.createLSSerializer();
- return lss.writeToString(document);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java
deleted file mode 100644
index 8c56b22..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java
+++ /dev/null
@@ -1,44 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-public class VsmOkResponse extends VsmResponse {
-
- VsmOkResponse(String response) {
- super(response);
- initialize();
- }
-
- @Override
- protected void parse(Element root) {
- NodeList list = root.getElementsByTagName("nf:rpc-error");
- if (list.getLength() == 0) {
- // No rpc-error tag; means response was ok.
- assert (root.getElementsByTagName("nf:ok").getLength() > 0);
- _responseOk = true;
- } else {
- parseError(list.item(0));
- _responseOk = false;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java
deleted file mode 100644
index c0ed6ee..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java
+++ /dev/null
@@ -1,84 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-public class VsmPolicyMapResponse extends VsmResponse {
- private static final Logger s_logger = Logger.getLogger(VsmPolicyMapResponse.class);
- private static final String s_policyMapDetails = "__XML__OPT_Cmd_show_policy-map___readonly__";
-
- private PolicyMap _policyMap = new PolicyMap();
-
- VsmPolicyMapResponse(String response) {
- super(response);
- initialize();
- }
-
- public PolicyMap getPolicyMap() {
- return _policyMap;
- }
-
- @Override
- protected void parse(Element root) {
- NodeList list = root.getElementsByTagName("nf:rpc-error");
- if (list.getLength() == 0) {
- // No rpc-error tag; means response was ok.
- NodeList dataList = root.getElementsByTagName("nf:data");
- if (dataList.getLength() > 0) {
- parseData(dataList.item(0));
- _responseOk = true;
- }
- } else {
- super.parseError(list.item(0));
- _responseOk = false;
- }
- }
-
- protected void parseData(Node data) {
- try {
- NodeList list = ((Element)data).getElementsByTagName(s_policyMapDetails);
- if (list.getLength() > 0) {
- NodeList readOnlyList = ((Element)list.item(0)).getElementsByTagName("__readonly__");
- Element readOnly = (Element)readOnlyList.item(0);
-
- for (Node node = readOnly.getFirstChild(); node != null; node = node.getNextSibling()) {
- String currentNode = node.getNodeName();
- String value = node.getTextContent();
- if ("pmap-name-out".equalsIgnoreCase(currentNode)) {
- _policyMap.policyMapName = value;
- } else if ("cir".equalsIgnoreCase(currentNode)) {
- _policyMap.committedRate = Integer.parseInt(value.trim());
- } else if ("bc".equalsIgnoreCase(currentNode)) {
- _policyMap.burstRate = Integer.parseInt(value.trim());
- } else if ("pir".equalsIgnoreCase(currentNode)) {
- _policyMap.peakRate = Integer.parseInt(value.trim());
- }
- }
- }
- } catch (DOMException e) {
- s_logger.error("Error parsing the response : " + e.toString());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java
deleted file mode 100644
index 0a3de18..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java
+++ /dev/null
@@ -1,166 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import java.util.StringTokenizer;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
-
-public class VsmPortProfileResponse extends VsmResponse {
- private static final Logger s_logger = Logger.getLogger(VsmPortProfileResponse.class);
- private static final String s_portProfileDetails = "__XML__OPT_Cmd_show_port_profile___readonly__";
-
- private PortProfile _portProfile = new PortProfile();
-
- VsmPortProfileResponse(String response) {
- super(response);
- initialize();
- }
-
- public PortProfile getPortProfile() {
- return _portProfile;
- }
-
- @Override
- protected void parse(Element root) {
- NodeList list = root.getElementsByTagName("nf:rpc-error");
- if (list.getLength() == 0) {
- // No rpc-error tag; means response was ok.
- NodeList dataList = root.getElementsByTagName("nf:data");
- if (dataList.getLength() > 0) {
- parseData(dataList.item(0));
- _responseOk = true;
- }
- } else {
- super.parseError(list.item(0));
- _responseOk = false;
- }
- }
-
- protected void parseData(Node data) {
- try {
- NodeList list = ((Element)data).getElementsByTagName(s_portProfileDetails);
- if (list.getLength() > 0) {
- NodeList readOnlyList = ((Element)list.item(0)).getElementsByTagName("__readonly__");
- Element readOnly = (Element)readOnlyList.item(0);
-
- for (Node node = readOnly.getFirstChild(); node != null; node = node.getNextSibling()) {
- String currentNode = node.getNodeName();
- String value = node.getTextContent();
- if ("port_binding".equalsIgnoreCase(currentNode)) {
- setPortBinding(value);
- } else if ("profile_name".equalsIgnoreCase(currentNode)) {
- // Set the port profile name.
- _portProfile.profileName = value;
- } else if ("profile_cfg".equalsIgnoreCase(currentNode)) {
- setProfileConfiguration(value);
- } else if ("type".equalsIgnoreCase(currentNode)) {
- setPortType(value);
- } else if ("status".equalsIgnoreCase(currentNode)) {
- // Has the profile been enabled.
- if (value.equalsIgnoreCase("1")) {
- _portProfile.status = true;
- }
- } else if ("max_ports".equalsIgnoreCase(currentNode)) {
- // Has the profile been enabled.
- _portProfile.maxPorts = Integer.parseInt(value.trim());
- }
- }
- }
- } catch (DOMException e) {
- s_logger.error("Error parsing the response : " + e.toString());
- }
- }
-
- private void setProfileConfiguration(String value) {
- StringTokenizer tokens = new StringTokenizer(value.trim());
- if (tokens.hasMoreTokens()) {
- String currentToken = tokens.nextToken();
- if ("switchport".equalsIgnoreCase(currentToken)) {
- parseProfileMode(tokens);
- } else if ("service-policy".equalsIgnoreCase(currentToken)) {
- String ioType = tokens.nextToken();
- if ("input".equalsIgnoreCase(ioType)) {
- _portProfile.inputPolicyMap = tokens.nextToken();
- } else if ("output".equalsIgnoreCase(ioType)) {
- _portProfile.outputPolicyMap = tokens.nextToken();
- }
- }
- }
- }
-
- private void parseProfileMode(StringTokenizer tokens) {
- if (tokens.hasMoreTokens()) {
- String firstToken = tokens.nextToken();
- if ("mode".equalsIgnoreCase(firstToken)) {
- setPortMode(tokens.nextToken());
- } else if ("access".equalsIgnoreCase(firstToken)) {
- if (tokens.hasMoreTokens()) {
- String secondToken = tokens.nextToken();
- assert ("vlan".equalsIgnoreCase(secondToken));
- if (tokens.hasMoreTokens()) {
- _portProfile.vlan = tokens.nextToken();
- }
- }
- }
- }
- }
-
- private void setPortMode(String value) {
- // Set the mode for port profile.
- if ("access".equalsIgnoreCase(value)) {
- _portProfile.mode = SwitchPortMode.access;
- } else if ("trunk".equalsIgnoreCase(value)) {
- _portProfile.mode = SwitchPortMode.trunk;
- } else if ("privatevlanhost".equalsIgnoreCase(value)) {
- _portProfile.mode = SwitchPortMode.privatevlanhost;
- } else if ("privatevlanpromiscuous".equalsIgnoreCase(value)) {
- _portProfile.mode = SwitchPortMode.privatevlanpromiscuous;
- }
- }
-
- private void setPortBinding(String value) {
- // Set the binding type for the port profile.
- if ("static".equalsIgnoreCase(value)) {
- _portProfile.binding = BindingType.portbindingstatic;
- } else if ("dynamic".equalsIgnoreCase(value)) {
- _portProfile.binding = BindingType.portbindingdynamic;
- } else if ("ephermal".equalsIgnoreCase(value)) {
- _portProfile.binding = BindingType.portbindingephermal;
- }
- }
-
- private void setPortType(String value) {
- // Set the type field (vethernet/ethernet).
- if ("vethernet".equalsIgnoreCase(value)) {
- _portProfile.type = PortProfileType.vethernet;
- } else if ("ethernet".equalsIgnoreCase(value)) {
- _portProfile.type = PortProfileType.ethernet;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java
deleted file mode 100644
index d82b0dc..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java
+++ /dev/null
@@ -1,222 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import java.io.IOException;
-import java.io.StringReader;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.ls.DOMImplementationLS;
-import org.w3c.dom.ls.LSSerializer;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-public abstract class VsmResponse {
-
- // Following error tags, error types and severity have been taken from RFC 4741.
- public enum ErrorTag {
- InUse, // in-use
- InvalidValue, // invalid-value
- TooBig, // too-big
- MissingAttribute, // missing-attribute
- BadAttribute, // bad-attribute
- UnknownAttribute, // unknown-attribute
- MissingElement, // missing-element
- BadElement, // bad-element
- UnknownElement, // unknown-element
- UnknownNamespace, // unknown-namespace
- AccessDenied, // access-denied
- LockDenied, // lock-denied
- ResourceDenied, // resource-denied
- RollbackFailed, // rollback-failed
- DataExists, // data-exists
- DataMissing, // data-missing
- OperationNotSupported, // operation-not-supported
- OperationFailed, // operation-failed
- PartialOperation, // partial-operation
- }
-
- public enum ErrorType {
- transport, rpc, protocol, application;
- }
-
- public enum ErrorSeverity {
- error, warning;
- }
-
- private static final Logger s_logger = Logger.getLogger(VsmResponse.class);
-
- protected String _xmlResponse;
- protected Document _docResponse;
- protected boolean _responseOk;
-
- protected ErrorTag _tag;
- protected ErrorType _type;
- protected ErrorSeverity _severity;
- protected String _path;
- protected String _message;
- protected String _info;
-
- VsmResponse(String response) {
- _xmlResponse = response;
- _responseOk = false;
- _tag = ErrorTag.InUse;
- _type = ErrorType.rpc;
- _severity = ErrorSeverity.error;
- _docResponse = null;
- }
-
- protected void initialize() {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- docFactory.setNamespaceAware(true);
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- _docResponse = docBuilder.parse(new InputSource(new StringReader(_xmlResponse)));
- if (_docResponse != null) {
- parse(_docResponse.getDocumentElement());
- }
- } catch (ParserConfigurationException e) {
- s_logger.error("Error parsing the response : " + e.toString());
- } catch (SAXException e) {
- s_logger.error("Error parsing the response : " + e.toString());
- } catch (IOException e) {
- s_logger.error("Error parsing the response : " + e.toString());
- }
- }
-
- public boolean isResponseOk() {
- return _responseOk;
- }
-
- @Override
- public String toString() {
- StringBuffer error = new StringBuffer("");
-
- error.append(" Severity: " + _severity).append(", Error code: " + _tag).append(", Error type: " + _type);
-
- if (_message != null) {
- error.append(", Error Message: " + _message);
- }
-
- if (_info != null) {
- error.append(", Error info: " + _info);
- }
-
- if (_path != null) {
- error.append(", Path: " + _path);
- }
-
- return error.toString();
- }
-
- protected abstract void parse(Element root);
-
- protected void parseError(Node element) {
- Element rpcError = (Element)element;
-
- try {
- assert (rpcError.getNodeName().equalsIgnoreCase("nf:rpc-error"));
- for (Node node = rpcError.getFirstChild(); node != null; node = node.getNextSibling()) {
- if (node.getNodeName().equalsIgnoreCase("nf:error-type")) {
- _type = ErrorType.valueOf(node.getTextContent().trim());
- } else if (node.getNodeName().equalsIgnoreCase("nf:error-tag")) {
- _tag = getErrorTag(node.getTextContent().trim());
- } else if (node.getNodeName().equalsIgnoreCase("nf:error-severity")) {
- _severity = ErrorSeverity.valueOf(node.getTextContent().trim());
- } else if (node.getNodeName().equalsIgnoreCase("nf:error-path")) {
- _path = node.getTextContent();
- } else if (node.getNodeName().equalsIgnoreCase("nf:error-message")) {
- _message = node.getTextContent();
- } else if (node.getNodeName().equalsIgnoreCase("nf:error-info")) {
- _info = node.getTextContent();
- }
- }
- } catch (DOMException e) {
- s_logger.error("Error parsing the response : " + e.toString());
- }
- }
-
- protected ErrorTag getErrorTag(String tagText) {
- ErrorTag tag = ErrorTag.InUse;
-
- if (tagText.equals("in-use")) {
- tag = ErrorTag.InUse;
- } else if (tagText.equals("invalid-value")) {
- tag = ErrorTag.InvalidValue;
- } else if (tagText.equals("too-big")) {
- tag = ErrorTag.TooBig;
- } else if (tagText.equals("missing-attribute")) {
- tag = ErrorTag.MissingAttribute;
- } else if (tagText.equals("bad-attribute")) {
- tag = ErrorTag.BadAttribute;
- } else if (tagText.equals("unknown-attribute")) {
- tag = ErrorTag.UnknownAttribute;
- } else if (tagText.equals("missing-element")) {
- tag = ErrorTag.MissingElement;
- } else if (tagText.equals("bad-element")) {
- tag = ErrorTag.BadElement;
- } else if (tagText.equals("unknown-element")) {
- tag = ErrorTag.UnknownElement;
- } else if (tagText.equals("unknown-namespace")) {
- tag = ErrorTag.UnknownNamespace;
- } else if (tagText.equals("access-denied")) {
- tag = ErrorTag.AccessDenied;
- } else if (tagText.equals("lock-denied")) {
- tag = ErrorTag.LockDenied;
- } else if (tagText.equals("resource-denied")) {
- tag = ErrorTag.ResourceDenied;
- } else if (tagText.equals("rollback-failed")) {
- tag = ErrorTag.RollbackFailed;
- } else if (tagText.equals("data-exists")) {
- tag = ErrorTag.DataExists;
- } else if (tagText.equals("data-missing")) {
- tag = ErrorTag.DataMissing;
- } else if (tagText.equals("operation-not-supported")) {
- tag = ErrorTag.OperationNotSupported;
- } else if (tagText.equals("operation-failed")) {
- tag = ErrorTag.OperationFailed;
- } else if (tagText.equals("partial-operation")) {
- tag = ErrorTag.PartialOperation;
- }
-
- return tag;
- }
-
- // Helper routine to check for the response received.
- protected void printResponse() {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- DOMImplementationLS ls = (DOMImplementationLS)docBuilder.getDOMImplementation();
- LSSerializer lss = ls.createLSSerializer();
- System.out.println(lss.writeToString(_docResponse));
- } catch (ParserConfigurationException e) {
- s_logger.error("Error parsing the repsonse : " + e.toString());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/Adapter.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/Adapter.java b/utils/src/com/cloud/utils/component/Adapter.java
deleted file mode 100644
index d50b8d9..0000000
--- a/utils/src/com/cloud/utils/component/Adapter.java
+++ /dev/null
@@ -1,27 +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 com.cloud.utils.component;
-
-/**
- * Adapter defines methods for pluggable code within the Cloud Stack. An
- * Adapters are a departure from regular structured programming.
- */
-public interface Adapter extends ComponentLifecycle {
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/AdapterBase.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/AdapterBase.java b/utils/src/com/cloud/utils/component/AdapterBase.java
deleted file mode 100644
index 703b532..0000000
--- a/utils/src/com/cloud/utils/component/AdapterBase.java
+++ /dev/null
@@ -1,40 +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 com.cloud.utils.component;
-
-import java.util.List;
-
-// Typical Adapter implementation.
-public class AdapterBase extends ComponentLifecycleBase implements Adapter, ComponentMethodInterceptable {
-
- public AdapterBase() {
- super();
- // set default run level for adapter components
- setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT);
- }
-
- public static <T extends Adapter> T getAdapterByName(List<T> adapters, String name) {
- for (T adapter : adapters) {
- if (adapter.getName() != null && adapter.getName().equalsIgnoreCase(name))
- return adapter;
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/AdapterList.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/AdapterList.java b/utils/src/com/cloud/utils/component/AdapterList.java
deleted file mode 100644
index dad3391..0000000
--- a/utils/src/com/cloud/utils/component/AdapterList.java
+++ /dev/null
@@ -1,37 +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 com.cloud.utils.component;
-
-import java.util.List;
-
-public class AdapterList<T extends Adapter> {
- protected List<T> adapters;
-
- public AdapterList() {
- }
-
- public List<T> getAdapters() {
- return adapters;
- }
-
- public void setAdapters(List<T> adapters) {
- this.adapters = adapters;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentContext.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentContext.java b/utils/src/com/cloud/utils/component/ComponentContext.java
deleted file mode 100644
index 8948b27..0000000
--- a/utils/src/com/cloud/utils/component/ComponentContext.java
+++ /dev/null
@@ -1,282 +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 com.cloud.utils.component;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.naming.ConfigurationException;
-
-import org.apache.log4j.Logger;
-import org.springframework.aop.framework.Advised;
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.context.annotation.Primary;
-
-import com.cloud.utils.mgmt.JmxUtil;
-import com.cloud.utils.mgmt.ManagementBean;
-
-/**
- *
- * ComponentContext.setApplication() and ComponentContext.getApplication()
- * are not recommended to be used outside, they exist to help wire Spring Framework
- *
- */
-@SuppressWarnings("unchecked")
-public class ComponentContext implements ApplicationContextAware {
- private static final Logger s_logger = Logger.getLogger(ComponentContext.class);
-
- private static ApplicationContext s_appContext;
- private static Map<Class<?>, ApplicationContext> s_appContextDelegates;
- private static boolean s_initializeBeans = true;
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) {
- s_logger.info("Setup Spring Application context");
- s_appContext = applicationContext;
- }
-
- public static ApplicationContext getApplicationContext() {
- return s_appContext;
- }
-
- public static void initComponentsLifeCycle() {
- if (!s_initializeBeans)
- return;
-
- AutowireCapableBeanFactory beanFactory = s_appContext.getAutowireCapableBeanFactory();
-
- Map<String, ComponentMethodInterceptable> interceptableComponents = getApplicationContext().getBeansOfType(ComponentMethodInterceptable.class);
- for (Map.Entry<String, ComponentMethodInterceptable> entry : interceptableComponents.entrySet()) {
- Object bean = getTargetObject(entry.getValue());
- beanFactory.configureBean(bean, entry.getKey());
- }
-
- Map<String, ComponentLifecycle> lifecycleComponents = getApplicationContext().getBeansOfType(ComponentLifecycle.class);
-
- Map<String, ComponentLifecycle>[] classifiedComponents = new Map[ComponentLifecycle.MAX_RUN_LEVELS];
- for (int i = 0; i < ComponentLifecycle.MAX_RUN_LEVELS; i++) {
- classifiedComponents[i] = new HashMap<String, ComponentLifecycle>();
- }
-
- for (Map.Entry<String, ComponentLifecycle> entry : lifecycleComponents.entrySet()) {
- classifiedComponents[entry.getValue().getRunLevel()].put(entry.getKey(), entry.getValue());
- }
-
- // Run the SystemIntegrityCheckers first
- Map<String, SystemIntegrityChecker> integrityCheckers = getApplicationContext().getBeansOfType(SystemIntegrityChecker.class);
- for (Entry<String, SystemIntegrityChecker> entry : integrityCheckers.entrySet()) {
- s_logger.info("Running SystemIntegrityChecker " + entry.getKey());
- try {
- entry.getValue().check();
- } catch (Throwable e) {
- s_logger.error("System integrity check failed. Refuse to startup", e);
- System.exit(1);
- }
- }
-
- // configuration phase
- Map<String, String> avoidMap = new HashMap<String, String>();
- for (int i = 0; i < ComponentLifecycle.MAX_RUN_LEVELS; i++) {
- for (Map.Entry<String, ComponentLifecycle> entry : classifiedComponents[i].entrySet()) {
- ComponentLifecycle component = entry.getValue();
- String implClassName = ComponentContext.getTargetClass(component).getName();
- s_logger.info("Configuring " + implClassName);
-
- if (avoidMap.containsKey(implClassName)) {
- s_logger.info("Skip configuration of " + implClassName + " as it is already configured");
- continue;
- }
-
- try {
- component.configure(component.getName(), component.getConfigParams());
- } catch (ConfigurationException e) {
- s_logger.error("Unhandled exception", e);
- throw new RuntimeException("Unable to configure " + implClassName, e);
- }
-
- avoidMap.put(implClassName, implClassName);
- }
- }
-
- // starting phase
- avoidMap.clear();
- for (int i = 0; i < ComponentLifecycle.MAX_RUN_LEVELS; i++) {
- for (Map.Entry<String, ComponentLifecycle> entry : classifiedComponents[i].entrySet()) {
- ComponentLifecycle component = entry.getValue();
- String implClassName = ComponentContext.getTargetClass(component).getName();
- s_logger.info("Starting " + implClassName);
-
- if (avoidMap.containsKey(implClassName)) {
- s_logger.info("Skip configuration of " + implClassName + " as it is already configured");
- continue;
- }
-
- try {
- component.start();
-
- if (getTargetObject(component) instanceof ManagementBean)
- registerMBean((ManagementBean)getTargetObject(component));
- } catch (Exception e) {
- s_logger.error("Unhandled exception", e);
- throw new RuntimeException("Unable to start " + implClassName, e);
- }
-
- avoidMap.put(implClassName, implClassName);
- }
- }
- }
-
- static void registerMBean(ManagementBean mbean) {
- try {
- JmxUtil.registerMBean(mbean);
- } catch (MalformedObjectNameException e) {
- s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
- } catch (InstanceAlreadyExistsException e) {
- s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
- } catch (MBeanRegistrationException e) {
- s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
- } catch (NotCompliantMBeanException e) {
- s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
- }
- s_logger.info("Registered MBean: " + mbean.getName());
- }
-
- public static <T> T getComponent(String name) {
- assert (s_appContext != null);
- return (T)s_appContext.getBean(name);
- }
-
- public static <T> T getComponent(Class<T> beanType) {
- assert (s_appContext != null);
- Map<String, T> matchedTypes = getComponentsOfType(beanType);
- if (matchedTypes.size() > 0) {
- for (Map.Entry<String, T> entry : matchedTypes.entrySet()) {
- Primary primary = getTargetClass(entry.getValue()).getAnnotation(Primary.class);
- if (primary != null)
- return entry.getValue();
- }
-
- if (matchedTypes.size() > 1) {
- s_logger.warn("Unable to uniquely locate bean type " + beanType.getName());
- for (Map.Entry<String, T> entry : matchedTypes.entrySet()) {
- s_logger.warn("Candidate " + getTargetClass(entry.getValue()).getName());
- }
- }
-
- return (T)matchedTypes.values().toArray()[0];
- }
-
- throw new NoSuchBeanDefinitionException(beanType.getName());
- }
-
- public static <T> Map<String, T> getComponentsOfType(Class<T> beanType) {
- return s_appContext.getBeansOfType(beanType);
- }
-
- public static Class<?> getTargetClass(Object instance) {
- while (instance instanceof Advised) {
- try {
- instance = ((Advised)instance).getTargetSource().getTarget();
- } catch (Exception e) {
- return instance.getClass();
- }
- }
- return instance.getClass();
- }
-
- public static <T> T getTargetObject(Object instance) {
- while (instance instanceof Advised) {
- try {
- instance = ((Advised)instance).getTargetSource().getTarget();
- } catch (Exception e) {
- return (T)instance;
- }
- }
-
- return (T)instance;
- }
-
- public static <T> T inject(Class<T> clz) {
- T instance;
- try {
- instance = clz.newInstance();
- return inject(instance);
- } catch (InstantiationException e) {
- s_logger.error("Unhandled InstantiationException", e);
- throw new RuntimeException("Unable to instantiate object of class " + clz.getName() + ", make sure it has public constructor");
- } catch (IllegalAccessException e) {
- s_logger.error("Unhandled IllegalAccessException", e);
- throw new RuntimeException("Unable to instantiate object of class " + clz.getName() + ", make sure it has public constructor");
- }
- }
-
- public static <T> T inject(Object instance) {
- // autowire dynamically loaded object
- AutowireCapableBeanFactory beanFactory = getApplicationContext(instance).getAutowireCapableBeanFactory();
- beanFactory.autowireBean(instance);
- return (T)instance;
- }
-
- private static ApplicationContext getApplicationContext(Object instance) {
- ApplicationContext result = null;
-
- synchronized (s_appContextDelegates) {
- if (instance != null && s_appContextDelegates != null) {
- result = s_appContextDelegates.get(instance.getClass());
- }
- }
-
- return result == null ? s_appContext : result;
- }
-
- public static synchronized void addDelegateContext(Class<?> clazz, ApplicationContext context) {
- if (s_appContextDelegates == null) {
- s_appContextDelegates = new HashMap<Class<?>, ApplicationContext>();
- }
-
- s_appContextDelegates.put(clazz, context);
- }
-
- public static synchronized void removeDelegateContext(Class<?> clazz) {
- if (s_appContextDelegates != null) {
- s_appContextDelegates.remove(clazz);
- }
- }
-
- public boolean isInitializeBeans() {
- return s_initializeBeans;
- }
-
- public void setInitializeBeans(boolean initializeBeans) {
- initInitializeBeans(initializeBeans);
- }
-
- private static synchronized void initInitializeBeans(boolean initializeBeans) {
- s_initializeBeans = initializeBeans;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java b/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java
deleted file mode 100644
index 6704371..0000000
--- a/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java
+++ /dev/null
@@ -1,149 +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 com.cloud.utils.component;
-
-import java.beans.PropertyDescriptor;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import net.sf.cglib.proxy.Callback;
-import net.sf.cglib.proxy.CallbackFilter;
-import net.sf.cglib.proxy.Enhancer;
-import net.sf.cglib.proxy.MethodInterceptor;
-import net.sf.cglib.proxy.MethodProxy;
-import net.sf.cglib.proxy.NoOp;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.PropertyValues;
-import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
-
-import com.cloud.utils.Pair;
-
-public class ComponentInstantiationPostProcessor implements InstantiationAwareBeanPostProcessor {
- private static final Logger s_logger = Logger.getLogger(ComponentInstantiationPostProcessor.class);
-
- private List<ComponentMethodInterceptor> _interceptors = new ArrayList<ComponentMethodInterceptor>();
- private Callback[] _callbacks;
- private CallbackFilter _callbackFilter;
-
- public ComponentInstantiationPostProcessor() {
- _callbacks = new Callback[2];
- _callbacks[0] = NoOp.INSTANCE;
- _callbacks[1] = new InterceptorDispatcher();
-
- _callbackFilter = new InterceptorFilter();
- }
-
- public List<ComponentMethodInterceptor> getInterceptors() {
- return _interceptors;
- }
-
- public void setInterceptors(List<ComponentMethodInterceptor> interceptors) {
- _interceptors = interceptors;
- }
-
- private Callback[] getCallbacks() {
- return _callbacks;
- }
-
- private CallbackFilter getCallbackFilter() {
- return _callbackFilter;
- }
-
- @Override
- public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
- return bean;
- }
-
- @Override
- public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
- return bean;
- }
-
- @Override
- public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
- if (_interceptors != null && _interceptors.size() > 0) {
- if (ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(beanClass);
- enhancer.setCallbacks(getCallbacks());
- enhancer.setCallbackFilter(getCallbackFilter());
- enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE);
-
- Object bean = enhancer.create();
- return bean;
- }
- }
- return null;
- }
-
- @Override
- public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
- return true;
- }
-
- @Override
- public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
- return pvs;
- }
-
- protected class InterceptorDispatcher implements MethodInterceptor {
- @Override
- public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
- ArrayList<Pair<ComponentMethodInterceptor, Object>> interceptors = new ArrayList<Pair<ComponentMethodInterceptor, Object>>();
-
- for (ComponentMethodInterceptor interceptor : getInterceptors()) {
- if (interceptor.needToIntercept(method)) {
- Object objReturnedInInterceptStart = interceptor.interceptStart(method, target);
- interceptors.add(new Pair<ComponentMethodInterceptor, Object>(interceptor, objReturnedInInterceptStart));
- }
- }
- boolean success = false;
- try {
- Object obj = methodProxy.invokeSuper(target, args);
- success = true;
- return obj;
- } finally {
- for (Pair<ComponentMethodInterceptor, Object> interceptor : interceptors) {
- if (success) {
- interceptor.first().interceptComplete(method, target, interceptor.second());
- } else {
- interceptor.first().interceptException(method, target, interceptor.second());
- }
- }
- }
- }
- }
-
- protected class InterceptorFilter implements CallbackFilter {
- @Override
- public int accept(Method method) {
- for (ComponentMethodInterceptor interceptor : getInterceptors()) {
-
- if (interceptor.needToIntercept(method)) {
- return 1;
- }
- }
- return 0;
- }
- }
-}
[13/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/security/CertificateHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/security/CertificateHelper.java b/utils/src/main/java/com/cloud/utils/security/CertificateHelper.java
new file mode 100644
index 0000000..d43542f
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/security/CertificateHelper.java
@@ -0,0 +1,166 @@
+//
+// 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 com.cloud.utils.security;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.security.Key;
+import java.security.KeyFactory;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import org.apache.commons.codec.binary.Base64;
+
+import com.cloud.utils.Ternary;
+import org.bouncycastle.openssl.PEMReader;
+
+public class CertificateHelper {
+ public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
+ NoSuchAlgorithmException, InvalidKeySpecException, IOException {
+ KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword);
+
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
+ os.close();
+ return os.toByteArray();
+ }
+
+ public static byte[] buildAndSaveKeystore(List<Ternary<String, String, String>> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException,
+ CertificateException, IOException, InvalidKeySpecException {
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
+
+ //name,cert,key
+ for (Ternary<String, String, String> cert : certs) {
+ if (cert.third() == null) {
+ Certificate c = buildCertificate(cert.second());
+ ks.setCertificateEntry(cert.first(), c);
+ } else {
+ Certificate[] c = new Certificate[certs.size()];
+ int i = certs.size();
+ for (Ternary<String, String, String> ct : certs) {
+ c[i - 1] = buildCertificate(ct.second());
+ i--;
+ }
+ ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c);
+ }
+ }
+
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
+ os.close();
+ return os.toByteArray();
+ }
+
+ public static KeyStore loadKeystore(byte[] ksData, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
+ assert (ksData != null);
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(new ByteArrayInputStream(ksData), storePassword != null ? storePassword.toCharArray() : null);
+
+ return ks;
+ }
+
+ public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
+ NoSuchAlgorithmException, InvalidKeySpecException, IOException {
+
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
+ Certificate[] certs = new Certificate[1];
+ certs[0] = buildCertificate(cert);
+ ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs);
+ return ks;
+ }
+
+ public static Certificate buildCertificate(String content) throws CertificateException {
+ assert (content != null);
+
+ BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes()));
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ return cf.generateCertificate(bis);
+ }
+
+ public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedKeyContent));
+ return kf.generatePrivate(keysp);
+ }
+
+ public static 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");
+
+ return certs;
+ }
+
+ public static 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 CloudRuntimeException("Bad certificate encoding");
+ } catch (NoSuchAlgorithmException e) {
+ throw new CloudRuntimeException("Bad certificate algorithm");
+ }
+
+ return buffer.toString();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ssh/SSHCmdHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ssh/SSHCmdHelper.java b/utils/src/main/java/com/cloud/utils/ssh/SSHCmdHelper.java
new file mode 100644
index 0000000..e35a3ea
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ssh/SSHCmdHelper.java
@@ -0,0 +1,179 @@
+//
+// 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 com.cloud.utils.ssh;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.log4j.Logger;
+
+import com.trilead.ssh2.ChannelCondition;
+import com.trilead.ssh2.Session;
+
+public class SSHCmdHelper {
+ private static final Logger s_logger = Logger.getLogger(SSHCmdHelper.class);
+
+ public static com.trilead.ssh2.Connection acquireAuthorizedConnection(String ip, String username, String password) {
+ return acquireAuthorizedConnection(ip, 22, username, password);
+ }
+
+ public static com.trilead.ssh2.Connection acquireAuthorizedConnection(String ip, int port, String username, String password) {
+ com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(ip, port);
+ try {
+ sshConnection.connect(null, 60000, 60000);
+ if (!sshConnection.authenticateWithPassword(username, password)) {
+ String[] methods = sshConnection.getRemainingAuthMethods(username);
+ StringBuffer mStr = new StringBuffer();
+ for (int i = 0; i < methods.length; i++) {
+ mStr.append(methods[i]);
+ }
+ s_logger.warn("SSH authorizes failed, support authorized methods are " + mStr);
+ return null;
+ }
+ return sshConnection;
+ } catch (IOException e) {
+ s_logger.warn("Get SSH connection failed", e);
+ return null;
+ }
+ }
+
+ public static void releaseSshConnection(com.trilead.ssh2.Connection sshConnection) {
+ if (sshConnection != null) {
+ sshConnection.close();
+ }
+ }
+
+ public static boolean sshExecuteCmd(com.trilead.ssh2.Connection sshConnection, String cmd, int nTimes) {
+ for (int i = 0; i < nTimes; i++) {
+ try {
+ if (sshExecuteCmdOneShot(sshConnection, cmd))
+ return true;
+ } catch (SshException e) {
+ continue;
+ }
+ }
+ return false;
+ }
+
+ public static int sshExecuteCmdWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) {
+ return sshExecuteCmdWithExitCode(sshConnection, cmd, 3);
+ }
+
+ public static int sshExecuteCmdWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd, int nTimes) {
+ for (int i = 0; i < nTimes; i++) {
+ try {
+ return sshExecuteCmdOneShotWithExitCode(sshConnection, cmd);
+ } catch (SshException e) {
+ continue;
+ }
+ }
+ return -1;
+ }
+
+ public static boolean sshExecuteCmd(com.trilead.ssh2.Connection sshConnection, String cmd) {
+ return sshExecuteCmd(sshConnection, cmd, 3);
+ }
+
+ public static int sshExecuteCmdOneShotWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException {
+ s_logger.debug("Executing cmd: " + cmd);
+ Session sshSession = null;
+ try {
+ sshSession = sshConnection.openSession();
+ // There is a bug in Trilead library, wait a second before
+ // starting a shell and executing commands, from http://spci.st.ewi.tudelft.nl/chiron/xref/nl/tudelft/swerl/util/SSHConnection.html
+ Thread.sleep(1000);
+
+ if (sshSession == null) {
+ throw new SshException("Cannot open ssh session");
+ }
+
+ sshSession.execCommand(cmd);
+
+ InputStream stdout = sshSession.getStdout();
+ InputStream stderr = sshSession.getStderr();
+
+ byte[] buffer = new byte[8192];
+ StringBuffer sbResult = new StringBuffer();
+
+ int currentReadBytes = 0;
+ while (true) {
+ if (stdout == null || stderr == null) {
+ throw new SshException("stdout or stderr of ssh session is null");
+ }
+ if ((stdout.available() == 0) && (stderr.available() == 0)) {
+ int conditions = sshSession.waitForCondition(ChannelCondition.STDOUT_DATA
+ | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
+ 120000);
+
+ if ((conditions & ChannelCondition.TIMEOUT) != 0) {
+ String msg = "Timed out in waiting SSH execution result";
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+
+ if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
+ if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
+ break;
+ }
+ }
+
+ if ((conditions & ChannelCondition.EOF) != 0) {
+ if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
+ break;
+ }
+ }
+ }
+
+ while (stdout.available() > 0) {
+ currentReadBytes = stdout.read(buffer);
+ sbResult.append(new String(buffer, 0, currentReadBytes));
+ }
+
+ while (stderr.available() > 0) {
+ currentReadBytes = stderr.read(buffer);
+ sbResult.append(new String(buffer, 0, currentReadBytes));
+ }
+ }
+
+ String result = sbResult.toString();
+ if (result != null && !result.isEmpty())
+ s_logger.debug(cmd + " output:" + result);
+ // exit status delivery might get delayed
+ for(int i = 0 ; i<10 ; i++ ) {
+ Integer status = sshSession.getExitStatus();
+ if( status != null ) {
+ return status;
+ }
+ Thread.sleep(100);
+ }
+ return -1;
+ } catch (Exception e) {
+ s_logger.debug("Ssh executed failed", e);
+ throw new SshException("Ssh executed failed " + e.getMessage());
+ } finally {
+ if (sshSession != null)
+ sshSession.close();
+ }
+ }
+
+ public static boolean sshExecuteCmdOneShot(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException {
+ return sshExecuteCmdOneShotWithExitCode(sshConnection, cmd) == 0;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ssh/SSHKeysHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ssh/SSHKeysHelper.java b/utils/src/main/java/com/cloud/utils/ssh/SSHKeysHelper.java
new file mode 100644
index 0000000..39db5c4
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ssh/SSHKeysHelper.java
@@ -0,0 +1,115 @@
+//
+// 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 com.cloud.utils.ssh;
+
+import java.io.ByteArrayOutputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import org.apache.commons.codec.binary.Base64;
+
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.KeyPair;
+
+public class SSHKeysHelper {
+
+ private KeyPair keyPair;
+ private static final char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+ private static String toHexString(byte[] b) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < b.length; i++) {
+ sb.append(hexChars[(b[i] >> 4) & 0x0f]);
+ sb.append(hexChars[(b[i]) & 0x0f]);
+ }
+ return sb.toString();
+ }
+
+ public SSHKeysHelper() {
+ try {
+ keyPair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA);
+ } catch (JSchException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String getPublicKeyFingerPrint() {
+ return getPublicKeyFingerprint(getPublicKey());
+ }
+
+ public static String getPublicKeyFingerprint(String publicKey) {
+ String key[] = publicKey.split(" ");
+ if (key.length < 2) {
+ throw new RuntimeException("Incorrect public key is passed in");
+ }
+ byte[] keyBytes = Base64.decodeBase64(key[1]);
+
+ MessageDigest md5 = null;
+ try {
+ md5 = MessageDigest.getInstance("MD5");
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+
+ String rString = "";
+ String sumString = "";
+ if (md5 != null) {
+ sumString = toHexString(md5.digest(keyBytes));
+ }
+
+ for (int i = 2; i <= sumString.length(); i += 2) {
+ rString += sumString.substring(i - 2, i);
+ if (i != sumString.length())
+ rString += ":";
+ }
+
+ return rString;
+ }
+
+ public static String getPublicKeyFromKeyMaterial(String keyMaterial) {
+ if (!keyMaterial.contains(" "))
+ keyMaterial = new String(Base64.decodeBase64(keyMaterial.getBytes()));
+
+ if ((!keyMaterial.startsWith("ssh-rsa") && !keyMaterial.startsWith("ssh-dss")) || !keyMaterial.contains(" "))
+ return null;
+
+ String[] key = keyMaterial.split(" ");
+ if (key.length < 2)
+ return null;
+
+ return key[0].concat(" ").concat(key[1]);
+ }
+
+ public String getPublicKey() {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ keyPair.writePublicKey(baos, "");
+
+ return baos.toString();
+ }
+
+ public String getPrivateKey() {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ keyPair.writePrivateKey(baos);
+
+ return baos.toString();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ssh/SshException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ssh/SshException.java b/utils/src/main/java/com/cloud/utils/ssh/SshException.java
new file mode 100644
index 0000000..a9d9ed8
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ssh/SshException.java
@@ -0,0 +1,30 @@
+//
+// 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 com.cloud.utils.ssh;
+
+import com.cloud.utils.SerialVersionUID;
+
+public class SshException extends Exception {
+ private static final long serialVersionUID = SerialVersionUID.sshException;
+
+ public SshException(String msg) {
+ super(msg);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ssh/SshHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ssh/SshHelper.java b/utils/src/main/java/com/cloud/utils/ssh/SshHelper.java
new file mode 100644
index 0000000..3aac427
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ssh/SshHelper.java
@@ -0,0 +1,209 @@
+//
+// 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 com.cloud.utils.ssh;
+
+import java.io.File;
+import java.io.InputStream;
+
+import org.apache.log4j.Logger;
+
+import com.trilead.ssh2.ChannelCondition;
+
+import com.cloud.utils.Pair;
+
+public class SshHelper {
+ private static final int DEFAULT_CONNECT_TIMEOUT = 60000;
+ private static final int DEFAULT_KEX_TIMEOUT = 60000;
+
+ private static final Logger s_logger = Logger.getLogger(SshHelper.class);
+
+ public static Pair<Boolean, String> sshExecute(String host, int port, String user, File pemKeyFile, String password, String command) throws Exception {
+
+ return sshExecute(host, port, user, pemKeyFile, password, command, 60000, 60000, 120000);
+ }
+
+ public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, String localFile, String fileMode)
+ throws Exception {
+
+ scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, localFile, fileMode, DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT);
+ }
+
+ public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, byte[] data, String remoteFileName,
+ String fileMode) throws Exception {
+
+ scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, data, remoteFileName, fileMode, DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT);
+ }
+
+ public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, String localFile, String fileMode,
+ int connectTimeoutInMs, int kexTimeoutInMs) throws Exception {
+
+ com.trilead.ssh2.Connection conn = null;
+ com.trilead.ssh2.SCPClient scpClient = null;
+
+ try {
+ conn = new com.trilead.ssh2.Connection(host, port);
+ conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
+
+ if (pemKeyFile == null) {
+ if (!conn.authenticateWithPassword(user, password)) {
+ String msg = "Failed to authentication SSH user " + user + " on host " + host;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+ } else {
+ if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
+ String msg = "Failed to authentication SSH user " + user + " on host " + host;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+ }
+
+ scpClient = conn.createSCPClient();
+
+ if (fileMode != null)
+ scpClient.put(localFile, remoteTargetDirectory, fileMode);
+ else
+ scpClient.put(localFile, remoteTargetDirectory);
+ } finally {
+ if (conn != null)
+ conn.close();
+ }
+ }
+
+ public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, byte[] data, String remoteFileName,
+ String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception {
+
+ com.trilead.ssh2.Connection conn = null;
+ com.trilead.ssh2.SCPClient scpClient = null;
+
+ try {
+ conn = new com.trilead.ssh2.Connection(host, port);
+ conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
+
+ if (pemKeyFile == null) {
+ if (!conn.authenticateWithPassword(user, password)) {
+ String msg = "Failed to authentication SSH user " + user + " on host " + host;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+ } else {
+ if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
+ String msg = "Failed to authentication SSH user " + user + " on host " + host;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+ }
+
+ scpClient = conn.createSCPClient();
+ if (fileMode != null)
+ scpClient.put(data, remoteFileName, remoteTargetDirectory, fileMode);
+ else
+ scpClient.put(data, remoteFileName, remoteTargetDirectory);
+ } finally {
+ if (conn != null)
+ conn.close();
+ }
+ }
+
+ public static Pair<Boolean, String> sshExecute(String host, int port, String user, File pemKeyFile, String password, String command, int connectTimeoutInMs,
+ int kexTimeoutInMs, int waitResultTimeoutInMs) throws Exception {
+
+ com.trilead.ssh2.Connection conn = null;
+ com.trilead.ssh2.Session sess = null;
+ try {
+ conn = new com.trilead.ssh2.Connection(host, port);
+ conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
+
+ if (pemKeyFile == null) {
+ if (!conn.authenticateWithPassword(user, password)) {
+ String msg = "Failed to authentication SSH user " + user + " on host " + host;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+ } else {
+ if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
+ String msg = "Failed to authentication SSH user " + user + " on host " + host;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+ }
+ sess = conn.openSession();
+
+ sess.execCommand(command);
+
+ InputStream stdout = sess.getStdout();
+ InputStream stderr = sess.getStderr();
+
+ byte[] buffer = new byte[8192];
+ StringBuffer sbResult = new StringBuffer();
+
+ int currentReadBytes = 0;
+ while (true) {
+ if ((stdout.available() == 0) && (stderr.available() == 0)) {
+ int conditions =
+ sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
+ waitResultTimeoutInMs);
+
+ if ((conditions & ChannelCondition.TIMEOUT) != 0) {
+ String msg = "Timed out in waiting SSH execution result";
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
+
+ if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
+ if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
+ break;
+ }
+ }
+ }
+
+ while (stdout.available() > 0) {
+ currentReadBytes = stdout.read(buffer);
+ sbResult.append(new String(buffer, 0, currentReadBytes));
+ }
+
+ while (stderr.available() > 0) {
+ currentReadBytes = stderr.read(buffer);
+ sbResult.append(new String(buffer, 0, currentReadBytes));
+ }
+ }
+
+ String result = sbResult.toString();
+
+ if (sess.getExitStatus() == null) {
+ //Exit status is NOT available. Returning failure result.
+ return new Pair<Boolean, String>(false, result);
+ }
+
+ if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
+ s_logger.error("SSH execution of command " + command + " has an error status code in return. result output: " + result);
+ return new Pair<Boolean, String>(false, result);
+ }
+
+ return new Pair<Boolean, String>(true, result);
+ } finally {
+ if (sess != null)
+ sess.close();
+
+ if (conn != null)
+ conn.close();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataObject.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataObject.java b/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataObject.java
new file mode 100644
index 0000000..56be699
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataObject.java
@@ -0,0 +1,56 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.storage.encoding;
+
+public class DecodedDataObject {
+ private String objType;
+ private Long size;
+ private String name;
+ private String path;
+ private DecodedDataStore store;
+
+ public DecodedDataObject(String objType, Long size, String name, String path, DecodedDataStore store) {
+ this.objType = objType;
+ this.size = size;
+ this.name = name;
+ this.path = path;
+ this.store = store;
+ }
+
+ public String getObjType() {
+ return objType;
+ }
+
+ public Long getSize() {
+ return size;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public DecodedDataStore getStore() {
+ return store;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataStore.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataStore.java b/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataStore.java
new file mode 100644
index 0000000..ac8af8b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataStore.java
@@ -0,0 +1,68 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.storage.encoding;
+
+public class DecodedDataStore {
+ private final String role;
+ private final String uuid;
+ private final String providerName;
+ private final String scheme;
+ private final String url;
+ private final String server;
+ private final String path;
+
+ public DecodedDataStore(String role, String uuid, String providerName, String scheme, String url, String server, String path) {
+ this.role = role;
+ this.uuid = uuid;
+ this.providerName = providerName;
+ this.scheme = scheme;
+ this.url = url;
+ this.server = server;
+ this.path = path;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public String getProviderName() {
+ return providerName;
+ }
+
+ public String getScheme() {
+ return scheme;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getServer() {
+ return server;
+ }
+
+ public String getPath() {
+ return path;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/storage/encoding/Decoder.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/storage/encoding/Decoder.java b/utils/src/main/java/com/cloud/utils/storage/encoding/Decoder.java
new file mode 100644
index 0000000..c7c61d3
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/storage/encoding/Decoder.java
@@ -0,0 +1,66 @@
+//
+// 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 com.cloud.utils.storage.encoding;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+
+public class Decoder {
+ private static final Logger s_logger = Logger.getLogger(Decoder.class);
+
+ private static Map<String, String> getParameters(URI uri) {
+ String parameters = uri.getQuery();
+ Map<String, String> params = new HashMap<String, String>();
+ List<String> paraLists = Arrays.asList(parameters.split("&"));
+ for (String para : paraLists) {
+ String[] pair = para.split("=");
+ if (!pair[1].equalsIgnoreCase("null")) {
+ params.put(pair[0], pair[1]);
+ }
+
+ }
+ return params;
+ }
+
+ public static DecodedDataObject decode(String url) throws URISyntaxException {
+ URI uri = new URI(url);
+ Map<String, String> params = getParameters(uri);
+ DecodedDataStore store =
+ new DecodedDataStore(params.get(EncodingType.ROLE.toString()), params.get(EncodingType.STOREUUID.toString()),
+ params.get(EncodingType.PROVIDERNAME.toString()), uri.getScheme(), uri.getScheme() + uri.getHost() + uri.getPath(), uri.getHost(), uri.getPath());
+
+ Long size = null;
+ try {
+ size = Long.parseLong(params.get(EncodingType.SIZE.toString()));
+ } catch (NumberFormatException e) {
+ s_logger.info("[ignored] number not recognised",e);
+ }
+ DecodedDataObject obj =
+ new DecodedDataObject(params.get(EncodingType.OBJTYPE.toString()), size, params.get(EncodingType.NAME.toString()), params.get(EncodingType.PATH.toString()),
+ store);
+ return obj;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/storage/encoding/EncodingType.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/storage/encoding/EncodingType.java b/utils/src/main/java/com/cloud/utils/storage/encoding/EncodingType.java
new file mode 100644
index 0000000..f40f4f9
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/storage/encoding/EncodingType.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.utils.storage.encoding;
+
+public enum EncodingType {
+ //object
+ OBJTYPE,
+ SIZE,
+ NAME,
+ PATH,
+ //dataStore
+ ROLE,
+ STOREUUID,
+ PROVIDERNAME
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/time/InaccurateClock.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/time/InaccurateClock.java b/utils/src/main/java/com/cloud/utils/time/InaccurateClock.java
new file mode 100644
index 0000000..2a22853
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/time/InaccurateClock.java
@@ -0,0 +1,102 @@
+//
+// 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 com.cloud.utils.time;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import javax.management.StandardMBean;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.concurrency.NamedThreadFactory;
+import com.cloud.utils.mgmt.JmxUtil;
+
+/**
+ */
+
+public class InaccurateClock extends StandardMBean implements InaccurateClockMBean {
+ private static final Logger s_logger = Logger.getLogger(InaccurateClock.class);
+ static ScheduledExecutorService s_executor = null;
+ static final InaccurateClock s_timer = new InaccurateClock();
+ private static long time;
+
+ public InaccurateClock() {
+ super(InaccurateClockMBean.class, false);
+ time = System.currentTimeMillis();
+ restart();
+ try {
+ JmxUtil.registerMBean("InaccurateClock", "InaccurateClock", this);
+ } catch (Exception e) {
+ s_logger.warn("Unable to initialize inaccurate clock", e);
+ }
+ }
+
+ @Override
+ public long[] getCurrentTimes() {
+ long[] results = new long[2];
+ results[0] = time;
+ results[1] = System.currentTimeMillis();
+
+ return results;
+ }
+
+ @Override
+ public synchronized String restart() {
+ turnOff();
+ s_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("InaccurateClock"));
+ s_executor.scheduleAtFixedRate(new SetTimeTask(), 0, 60, TimeUnit.SECONDS);
+ return "Restarted";
+ }
+
+ @Override
+ public String turnOff() {
+ if (s_executor != null) {
+ try {
+ s_executor.shutdown();
+ } catch (Throwable th) {
+ s_logger.error("Unable to shutdown the Executor", th);
+ return "Unable to turn off check logs";
+ }
+ }
+ s_executor = null;
+ return "Off";
+ }
+
+ public static long getTime() {
+ return s_executor != null ? time : System.currentTimeMillis();
+ }
+
+ public static long getTimeInSeconds() {
+ return time / 1000;
+ }
+
+ protected class SetTimeTask implements Runnable {
+ @Override
+ public void run() {
+ try {
+ time = System.currentTimeMillis();
+ } catch (Throwable th) {
+ s_logger.error("Unable to time", th);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java b/utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java
new file mode 100644
index 0000000..acc4615
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java
@@ -0,0 +1,28 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.time;
+
+public interface InaccurateClockMBean {
+ String restart();
+
+ String turnOff();
+
+ long[] getCurrentTimes();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/xmlobject/XmlObject.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/xmlobject/XmlObject.java b/utils/src/main/java/com/cloud/utils/xmlobject/XmlObject.java
new file mode 100644
index 0000000..42af945
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/xmlobject/XmlObject.java
@@ -0,0 +1,214 @@
+//
+// 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 com.cloud.utils.xmlobject;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class XmlObject {
+ private final Logger logger = Logger.getLogger(XmlObject.class.getName());
+ private final Map<String, Object> elements = new HashMap<String, Object>();
+ private String text;
+ private String tag;
+
+ XmlObject() {
+ }
+
+ public void removeAllChildren() {
+ elements.clear();
+ }
+
+ public XmlObject(String tag) {
+ this.tag = tag;
+ }
+
+ public XmlObject putElement(String key, Object e) {
+ if (e == null) {
+ throw new IllegalArgumentException(String.format("element[%s] can not be null", key));
+ }
+ Object old = elements.get(key);
+ if (old == null) {
+ //System.out.println(String.format("no %s, add new", key));
+ elements.put(key, e);
+ } else {
+ if (old instanceof List) {
+ //System.out.println(String.format("already list %s, add", key));
+ ((List)old).add(e);
+ } else {
+ //System.out.println(String.format("not list list %s, add list", key));
+ List lst = new ArrayList();
+ lst.add(old);
+ lst.add(e);
+ elements.put(key, lst);
+ }
+ }
+
+ return this;
+ }
+
+ public void removeElement(String key) {
+ elements.remove(key);
+ }
+
+ private Object recurGet(XmlObject obj, Iterator<String> it) {
+ String key = it.next();
+ Object e = obj.elements.get(key);
+ if (e == null) {
+ return null;
+ }
+
+ if (!it.hasNext()) {
+ return e;
+ } else {
+ if (!(e instanceof XmlObject)) {
+ throw new CloudRuntimeException(String.format("%s doesn't reference to a XmlObject", it.next()));
+ }
+ return recurGet((XmlObject)e, it);
+ }
+ }
+
+ public <T> T get(String elementStr) {
+ String[] strs = elementStr.split("\\.");
+ List<String> lst = new ArrayList<String>(strs.length);
+ Collections.addAll(lst, strs);
+ return (T)recurGet(this, lst.iterator());
+ }
+
+ public <T> List<T> getAsList(String elementStr) {
+ Object e = get(elementStr);
+ if (e instanceof List) {
+ return (List<T>)e;
+ }
+
+ List lst = new ArrayList(1);
+ if (e != null) {
+ lst.add(e);
+ }
+
+ return lst;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public XmlObject setText(String text) {
+ this.text = text;
+ return this;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ public XmlObject setTag(String tag) {
+ this.tag = tag;
+ return this;
+ }
+
+ public String dump() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("<").append(tag);
+ List<XmlObject> children = new ArrayList<XmlObject>();
+ for (Map.Entry<String, Object> e : elements.entrySet()) {
+ String key = e.getKey();
+ Object val = e.getValue();
+ if (val instanceof String) {
+ sb.append(String.format(" %s=\"%s\"", key, val.toString()));
+ } else if (val instanceof XmlObject) {
+ children.add((XmlObject)val);
+ } else if (val instanceof List) {
+ children.addAll((Collection<? extends XmlObject>)val);
+ } else {
+ throw new CloudRuntimeException(String.format("unsupported element type[tag:%s, class: %s], only allowed type of [String, List<XmlObject>, Object]", key,
+ val.getClass().getName()));
+ }
+ }
+
+ if (!children.isEmpty() && text != null) {
+ logger.info(String.format("element %s cannot have both text[%s] and child elements, set text to null", tag, text));
+ text = null;
+ }
+
+ if (!children.isEmpty()) {
+ sb.append(">");
+ for (XmlObject x : children) {
+ sb.append(x.dump());
+ }
+ sb.append(String.format("</%s>", tag));
+ } else {
+ if (text != null) {
+ sb.append(">");
+ sb.append(text);
+ sb.append(String.format("</%s>", tag));
+ } else {
+ sb.append(" />");
+ }
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder("<" + tag);
+ for (Map.Entry<String, Object> e : elements.entrySet()) {
+ String key = e.getKey();
+ Object value = e.getValue();
+ if (!(value instanceof String)) {
+ continue;
+ }
+ sb.append(String.format(" %s=\"%s\"", key, value.toString()));
+ }
+
+ if (text == null || "".equals(text.trim())) {
+ sb.append(" />");
+ } else {
+ sb.append(">").append(text).append(String.format("</ %s>", tag));
+ }
+ return sb.toString();
+ }
+
+ public <T> T evaluateObject(T obj) {
+ Class<?> clazz = obj.getClass();
+ try {
+ do {
+ Field[] fs = clazz.getDeclaredFields();
+ for (Field f : fs) {
+ f.setAccessible(true);
+ Object value = get(f.getName());
+ f.set(obj, value);
+ }
+ clazz = clazz.getSuperclass();
+ } while (clazz != null && clazz != Object.class);
+ return obj;
+ } catch (Exception e) {
+ throw new CloudRuntimeException(e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/xmlobject/XmlObjectParser.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/xmlobject/XmlObjectParser.java b/utils/src/main/java/com/cloud/utils/xmlobject/XmlObjectParser.java
new file mode 100644
index 0000000..f0e8ce3
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/xmlobject/XmlObjectParser.java
@@ -0,0 +1,128 @@
+//
+// 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 com.cloud.utils.xmlobject;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.Stack;
+
+public class XmlObjectParser {
+ final private InputStream is;
+
+ private class XmlHandler extends DefaultHandler {
+ private Stack<XmlObject> stack;
+ private String currentValue;
+ private XmlObject root;
+
+ XmlHandler() {
+ stack = new Stack<XmlObject>();
+ }
+
+ @Override
+ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
+ //System.out.println(String.format("startElement: namespaceURI:%s, localName:%s, qName:%s", namespaceURI, localName, qName));
+ currentValue = null;
+ XmlObject obj = new XmlObject();
+ for (int i = 0; i < atts.getLength(); i++) {
+ obj.putElement(atts.getQName(i), atts.getValue(i));
+ }
+ obj.setTag(qName);
+ if (!stack.isEmpty()) {
+ XmlObject parent = stack.peek();
+ parent.putElement(qName, obj);
+ }
+ stack.push(obj);
+ }
+
+ @Override
+ public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
+ XmlObject currObj = stack.pop();
+ if (currentValue != null) {
+ currObj.setText(currentValue);
+ }
+
+ if (stack.isEmpty()) {
+ root = currObj;
+ }
+
+ //System.out.println(String.format("endElement: namespaceURI:%s, localName:%s, qName:%s", namespaceURI, localName, qName));
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length) throws SAXException {
+ StringBuilder str = new StringBuilder();
+ str.append(ch, start, length);
+ currentValue = str.toString();
+ //System.out.println(String.format("characters: %s", str.toString()));
+ }
+
+ XmlObject getRoot() {
+ return root;
+ }
+ }
+
+ private XmlObjectParser(InputStream is) {
+ super();
+ this.is = is;
+ }
+
+ public static XmlObject parseFromFile(String filePath) {
+ FileInputStream fs;
+ try {
+ fs = new FileInputStream(new File(filePath));
+ XmlObjectParser p = new XmlObjectParser(fs);
+ return p.parse();
+ } catch (FileNotFoundException e) {
+ throw new CloudRuntimeException(e);
+ }
+ }
+
+ public static XmlObject parseFromString(String xmlString) {
+ InputStream stream = new ByteArrayInputStream(xmlString.getBytes());
+ XmlObjectParser p = new XmlObjectParser(stream);
+ XmlObject obj = p.parse();
+ if (obj.getText() != null && obj.getText().replaceAll("\\n", "").replaceAll("\\r", "").replaceAll(" ", "").isEmpty()) {
+ obj.setText(null);
+ }
+ return obj;
+ }
+
+ private XmlObject parse() {
+ SAXParserFactory spfactory = SAXParserFactory.newInstance();
+ try {
+ SAXParser saxParser = spfactory.newSAXParser();
+ XmlHandler handler = new XmlHandler();
+ saxParser.parse(is, handler);
+ return handler.getRoot();
+ } catch (Exception e) {
+ throw new CloudRuntimeException(e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java
new file mode 100644
index 0000000..85704a5
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java
@@ -0,0 +1,24 @@
+//
+// 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.utils.baremetal;
+
+public class BaremetalUtils {
+ public static final String BAREMETAL_SYSTEM_ACCOUNT_NAME = "baremetal-system-account";
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteClient.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteClient.java b/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteClient.java
new file mode 100644
index 0000000..4143f09
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteClient.java
@@ -0,0 +1,123 @@
+//
+// 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.utils.graphite;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class GraphiteClient {
+
+ private String graphiteHost;
+ private int graphitePort;
+
+ /**
+ * Create a new Graphite client
+ *
+ * @param graphiteHost Hostname of the Graphite host
+ * @param graphitePort UDP port of the Graphite host
+ */
+ public GraphiteClient(String graphiteHost, int graphitePort) {
+ this.graphiteHost = graphiteHost;
+ this.graphitePort = graphitePort;
+ }
+
+ /**
+ * Create a new Graphite client
+ *
+ * @param graphiteHost Hostname of the Graphite host. Will default to port 2003
+ */
+ public GraphiteClient(String graphiteHost) {
+ this.graphiteHost = graphiteHost;
+ graphitePort = 2003;
+ }
+
+ /**
+ * Get the current system timestamp to pass to Graphite
+ *
+ * @return Seconds passed since epoch (01-01-1970)
+ */
+ protected long getCurrentSystemTime() {
+ return System.currentTimeMillis() / 1000;
+ }
+
+ /**
+ * Send a array of metrics to graphite.
+ *
+ * @param metrics the metrics as key-value-pairs
+ */
+ public void sendMetrics(Map<String, Integer> metrics) {
+ sendMetrics(metrics, getCurrentSystemTime());
+ }
+
+ /**
+ * Send a array of metrics with a given timestamp to graphite.
+ *
+ * @param metrics the metrics as key-value-pairs
+ * @param timeStamp the timestamp
+ */
+ public void sendMetrics(Map<String, Integer> metrics, long timeStamp) {
+ try (DatagramSocket sock = new DatagramSocket()){
+ java.security.Security.setProperty("networkaddress.cache.ttl", "0");
+ InetAddress addr = InetAddress.getByName(this.graphiteHost);
+
+ for (Map.Entry<String, Integer> metric: metrics.entrySet()) {
+ byte[] message = new String(metric.getKey() + " " + metric.getValue() + " " + timeStamp + "\n").getBytes();
+ DatagramPacket packet = new DatagramPacket(message, message.length, addr, graphitePort);
+ sock.send(packet);
+ }
+ } catch (UnknownHostException e) {
+ throw new GraphiteException("Unknown host: " + graphiteHost);
+ } catch (IOException e) {
+ throw new GraphiteException("Error while writing to graphite: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Send a single metric with the current time as timestamp to graphite.
+ *
+ * @param key The metric key
+ * @param value the metric value
+ *
+ * @throws GraphiteException if sending data to graphite failed
+ */
+ public void sendMetric(String key, int value) {
+ sendMetric(key, value, getCurrentSystemTime());
+ }
+
+ /**
+ * Send a single metric with a given timestamp to graphite.
+ *
+ * @param key The metric key
+ * @param value The metric value
+ * @param timeStamp the timestamp to use
+ *
+ * @throws GraphiteException if sending data to graphite failed
+ */
+ public void sendMetric(final String key, final int value, long timeStamp) {
+ HashMap metrics = new HashMap<String, Integer>();
+ metrics.put(key, value);
+ sendMetrics(metrics, timeStamp);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteException.java b/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteException.java
new file mode 100644
index 0000000..9148764
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteException.java
@@ -0,0 +1,31 @@
+//
+// 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.utils.graphite;
+
+public class GraphiteException extends RuntimeException {
+
+ public GraphiteException(String message) {
+ super(message);
+ }
+
+ public GraphiteException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java
new file mode 100644
index 0000000..fdd80f7
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java
@@ -0,0 +1,63 @@
+//
+// 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.utils.identity;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.component.AdapterBase;
+import com.cloud.utils.component.ComponentLifecycle;
+import com.cloud.utils.component.SystemIntegrityChecker;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.MacAddress;
+
+@Local(value = {SystemIntegrityChecker.class})
+public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker {
+ private static final Logger s_logger = Logger.getLogger(ManagementServerNode.class);
+
+ private static final long s_nodeId = MacAddress.getMacAddress().toLong();
+
+ public ManagementServerNode() {
+ setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP);
+ }
+
+ @Override
+ public void check() {
+ if (s_nodeId <= 0) {
+ throw new CloudRuntimeException("Unable to get the management server node id");
+ }
+ }
+
+ public static long getManagementServerId() {
+ return s_nodeId;
+ }
+
+ @Override
+ public boolean start() {
+ try {
+ check();
+ } catch (Exception e) {
+ s_logger.error("System integrity check exception", e);
+ System.exit(1);
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java b/utils/src/main/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java
new file mode 100644
index 0000000..ed13360
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java
@@ -0,0 +1,110 @@
+/*
+ * 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.utils.imagestore;
+
+import com.cloud.utils.script.Script;
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+
+public class ImageStoreUtil {
+ public static final Logger s_logger = Logger.getLogger(ImageStoreUtil.class.getName());
+
+ public static String generatePostUploadUrl(String ssvmUrlDomain, String ipAddress, String uuid) {
+ String hostname = ipAddress;
+
+ //if ssvm url domain is present, use it to construct hostname in the format 1-2-3-4.domain
+ // if the domain name is not present, ssl validation fails and has to be ignored
+ if(StringUtils.isNotBlank(ssvmUrlDomain)) {
+ hostname = ipAddress.replace(".", "-");
+ hostname = hostname + ssvmUrlDomain.substring(1);
+ }
+
+ //only https works with postupload and url format is fixed
+ return "https://" + hostname + "/upload/" + uuid;
+ }
+
+ // given a path, returns empty if path is supported image, and the file type if unsupported
+ // this is meant to catch things like accidental upload of ASCII text .vmdk descriptor
+ public static String checkTemplateFormat(String path, String uripath) {
+ // note 'path' was generated by us so it should be safe on the cmdline, be wary of 'url'
+ String command = "file ";
+ if (isCompressedExtension(uripath)) {
+ command = "file -z ";
+ }
+ String output = Script.runSimpleBashScript(command + path + " | cut -d: -f2", 60000);
+
+ // vmdk
+ if ((output.contains("VMware") || output.contains("data")) && isCorrectExtension(uripath, "vmdk")) {
+ s_logger.debug("File at path " + path + " looks like a vmware image :" + output);
+ return "";
+ }
+ // raw
+ if ((output.contains("x86 boot") || output.contains("data")) && (isCorrectExtension(uripath, "raw") || isCorrectExtension(uripath, "img"))) {
+ s_logger.debug("File at path " + path + " looks like a raw image :" + output);
+ return "";
+ }
+ // qcow2
+ if (output.contains("QEMU QCOW") && isCorrectExtension(uripath, "qcow2")) {
+ s_logger.debug("File at path " + path + " looks like QCOW2 : " + output);
+ return "";
+ }
+ // vhd
+ if (output.contains("Microsoft Disk Image") && (isCorrectExtension(uripath, "vhd") || isCorrectExtension(uripath, "vhdx"))) {
+ s_logger.debug("File at path " + path + " looks like vhd : " + output);
+ return "";
+ }
+ // ova
+ if (output.contains("POSIX tar") && isCorrectExtension(uripath, "ova")) {
+ s_logger.debug("File at path " + path + " looks like ova : " + output);
+ return "";
+ }
+
+ //lxc
+ if (output.contains("POSIX tar") && isCorrectExtension(uripath, "tar")) {
+ s_logger.debug("File at path " + path + " looks like just tar : " + output);
+ return "";
+ }
+
+ if (output.contains("ISO 9660") && isCorrectExtension(uripath, "iso")) {
+ s_logger.debug("File at path " + path + " looks like an iso : " + output);
+ return "";
+ }
+ return output;
+ }
+
+ private static boolean isCorrectExtension(String path, String ext) {
+ if (path.toLowerCase().endsWith(ext)
+ || path.toLowerCase().endsWith(ext + ".gz")
+ || path.toLowerCase().endsWith(ext + ".bz2")
+ || path.toLowerCase().endsWith(ext + ".zip")) {
+ return true;
+ }
+ return false;
+ }
+
+ private static boolean isCompressedExtension(String path) {
+ if (path.toLowerCase().endsWith(".gz")
+ || path.toLowerCase().endsWith(".bz2")
+ || path.toLowerCase().endsWith(".zip")) {
+ return true;
+ }
+ return false;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/security/SSLUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/security/SSLUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/security/SSLUtils.java
new file mode 100644
index 0000000..c1fc2d6
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/security/SSLUtils.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package org.apache.cloudstack.utils.security;
+
+import org.apache.log4j.Logger;
+
+import javax.net.ssl.SSLContext;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+public class SSLUtils {
+ public static final Logger s_logger = Logger.getLogger(SSLUtils.class);
+
+ public static String[] getSupportedProtocols(String[] protocols) {
+ Set<String> set = new HashSet<String>();
+ for (String s : protocols) {
+ if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
+ continue;
+ }
+ set.add(s);
+ }
+ return (String[]) set.toArray(new String[set.size()]);
+ }
+
+ public static String[] getSupportedCiphers() throws NoSuchAlgorithmException {
+ String[] availableCiphers = getSSLContext().getSocketFactory().getSupportedCipherSuites();
+ Arrays.sort(availableCiphers);
+ return availableCiphers;
+ }
+
+ public static SSLContext getSSLContext() throws NoSuchAlgorithmException {
+ return SSLContext.getInstance("TLSv1");
+ }
+
+ public static SSLContext getSSLContext(String provider) throws NoSuchAlgorithmException, NoSuchProviderException {
+ return SSLContext.getInstance("TLSv1", provider);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java b/utils/src/main/java/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java
new file mode 100644
index 0000000..fa9d492
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java
@@ -0,0 +1,124 @@
+//
+// 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.utils.security;
+
+import org.apache.log4j.Logger;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+
+public class SecureSSLSocketFactory extends SSLSocketFactory {
+
+ public static final Logger s_logger = Logger.getLogger(SecureSSLSocketFactory.class);
+ private SSLContext _sslContext;
+
+ public SecureSSLSocketFactory() throws NoSuchAlgorithmException {
+ _sslContext = SSLUtils.getSSLContext();
+ }
+
+ public SecureSSLSocketFactory(SSLContext sslContext) throws NoSuchAlgorithmException {
+ if (sslContext != null) {
+ _sslContext = sslContext;
+ } else {
+ _sslContext = SSLUtils.getSSLContext();
+ }
+ }
+
+ public SecureSSLSocketFactory(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException, IOException {
+ _sslContext = SSLUtils.getSSLContext();
+ _sslContext.init(km, tm, random);
+ }
+
+ @Override
+ public String[] getDefaultCipherSuites() {
+ return getSupportedCipherSuites();
+ }
+
+ @Override
+ public String[] getSupportedCipherSuites() {
+ String[] ciphers = null;
+ try {
+ ciphers = SSLUtils.getSupportedCiphers();
+ } catch (NoSuchAlgorithmException e) {
+ s_logger.error("SecureSSLSocketFactory::getDefaultCipherSuites found no cipher suites");
+ }
+ return ciphers;
+ }
+
+ @Override
+ public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
+ SSLSocketFactory factory = _sslContext.getSocketFactory();
+ Socket socket = factory.createSocket(s, host, port, autoClose);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ @Override
+ public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
+ SSLSocketFactory factory = _sslContext.getSocketFactory();
+ Socket socket = factory.createSocket(host, port);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ @Override
+ public Socket createSocket(String host, int port, InetAddress inetAddress, int localPort) throws IOException, UnknownHostException {
+ SSLSocketFactory factory = _sslContext.getSocketFactory();
+ Socket socket = factory.createSocket(host, port, inetAddress, localPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ @Override
+ public Socket createSocket(InetAddress inetAddress, int localPort) throws IOException {
+ SSLSocketFactory factory = _sslContext.getSocketFactory();
+ Socket socket = factory.createSocket(inetAddress, localPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+
+ @Override
+ public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
+ SSLSocketFactory factory = this._sslContext.getSocketFactory();
+ Socket socket = factory.createSocket(address, port, localAddress, localPort);
+ if (socket instanceof SSLSocket) {
+ ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ }
+ return socket;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java
new file mode 100644
index 0000000..a97aed1
--- /dev/null
+++ b/utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java
@@ -0,0 +1,24 @@
+//
+// 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.utils.usage;
+
+public class UsageUtils {
+ public static final int USAGE_AGGREGATION_RANGE_MIN = 1;
+}
[48/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
index 1435cc5..79546a6 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
@@ -19,321 +19,180 @@
package com.cloud.network.nicira;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.hasSize;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Matchers.any;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.params.HttpClientParams;
-import org.junit.Before;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.ProtocolVersion;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.message.BasicStatusLine;
+import org.hamcrest.Matchers;
import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import com.google.gson.Gson;
-import com.google.gson.JsonParseException;
-import com.cloud.utils.rest.RESTServiceConnector;
-import com.cloud.utils.rest.RESTValidationStrategy;
+import com.cloud.utils.rest.HttpClientHelper;
+import com.cloud.utils.rest.HttpUriRequestMethodMatcher;
+import com.cloud.utils.rest.HttpUriRequestPathMatcher;
+import com.cloud.utils.rest.HttpUriRequestQueryMatcher;
public class NiciraNvpApiTest {
+ private static final StatusLine HTTP_200_REPSONSE = new BasicStatusLine(new ProtocolVersion("HTTPS", 1, 1), HttpStatus.SC_OK, "OK");
+ private static final StatusLine HTTP_201_REPSONSE = new BasicStatusLine(new ProtocolVersion("HTTPS", 1, 1), HttpStatus.SC_CREATED, "Created");
+
protected static final String UUID = "aaaa";
protected static final String UUID2 = "bbbb";
- protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa";
+ protected static final String UUID_SEC_PROFILE_URI = NiciraConstants.SEC_PROFILE_URI_PREFIX + "/aaaa";
protected static final String SCHEMA = "myTestSchema";
protected static final String SCHEMA2 = "myTestSchema2";
protected static final String HREF = "myTestHref";
protected static final String HREF2 = "myTestHref2";
protected static final String SEC_PROFILE_JSON_RESPONSE =
- "{\"uuid\" : \"aaaa\","
- + "\"display_name\" : \"myTestName\","
- + "\"href\" : \"myTestHref\","
- + "\"schema\" : \"myTestSchema\"}";
+ "{\"uuid\" : \"aaaa\","
+ + "\"display_name\" : \"myTestName\","
+ + "\"href\" : \"myTestHref\","
+ + "\"schema\" : \"myTestSchema\"}";
protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\","
- + "\"display_name\" : \"myTestName\","
- + "\"href\" : \"myTestHref\","
- + "\"schema\" : \"myTestSchema\"},"
- + "{ \"uuid\" : \"bbbb\","
- + "\"display_name\" : \"myTestName2\","
- + "\"href\" : \"myTestHref2\","
- + "\"schema\" : \"myTestSchema2\"}],"
- + "\"result_count\": 2}";
-
- NiciraNvpApi api;
- HttpClient client = mock(HttpClient.class);
- HttpMethod method;
- String type;
- String uri;
-
- @Before
- public void setUp() {
- final HttpClientParams hmp = mock(HttpClientParams.class);
- when(client.getParams()).thenReturn(hmp);
- api = new NiciraNvpApi();
-
- api.restConnector = new RESTServiceConnector(new RESTValidationStrategy()) {
- @Override
- public HttpClient createHttpClient() {
- return client;
- }
-
- @Override
- public HttpMethod createMethod(final String newType, final String newUri) {
- type = newType;
- uri = newUri;
- return method;
- }
- };
-
- api.setAdminCredentials("admin", "adminpass");
- api.setControllerAddress("localhost");
+ + "\"display_name\" : \"myTestName\","
+ + "\"href\" : \"myTestHref\","
+ + "\"schema\" : \"myTestSchema\"},"
+ + "{ \"uuid\" : \"bbbb\","
+ + "\"display_name\" : \"myTestName2\","
+ + "\"href\" : \"myTestHref2\","
+ + "\"schema\" : \"myTestSchema2\"}],"
+ + "\"result_count\": 2}";
+
+ private static NiciraNvpApi buildApi(final CloseableHttpClient httpClient) {
+ return NiciraNvpApi.create()
+ .host("localhost")
+ .username("admin")
+ .password("adminpassword")
+ .httpClient(httpClient)
+ .build();
}
@Test
- public void testFindSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
- final NameValuePair[] queryString = new NameValuePair[]{
- new NameValuePair("fields","*")};
-
- // Execute
- final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile();
-
- // Assert
- verify(method, times(1)).releaseConnection();
- verify(method, times(1)).setQueryString(queryString);
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID, actualProfiles.getResults().get(0).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF, actualProfiles.getResults().get(0).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA, actualProfiles.getResults().get(0).getSchema());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID2, actualProfiles.getResults().get(1).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF2, actualProfiles.getResults().get(1).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA2, actualProfiles.getResults().get(1).getSchema());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- 2, actualProfiles.getResultCount());
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.GET_METHOD_TYPE, type);
+ @SuppressWarnings("unchecked")
+ public void testFindSecurityProfile() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_200_REPSONSE);
+ when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_LIST_JSON_RESPONSE));
+ final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2));
+ doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class));
+ final NiciraNvpApi api = buildApi(httpClient);
+
+ final List<SecurityProfile> actualProfiles = api.findSecurityProfile();
+
+ assertThat("Wrong number of results", actualProfiles, hasSize(2));
+ assertThat("Wrong Uuid in the newly created SecurityProfile", actualProfiles, Matchers.<SecurityProfile> contains(
+ hasProperty("uuid", equalTo(UUID)),
+ hasProperty("uuid", equalTo(UUID2))));
+ assertThat("Wrong HREF in the newly created SecurityProfile", actualProfiles, Matchers.<SecurityProfile> contains(
+ hasProperty("href", equalTo(HREF)),
+ hasProperty("href", equalTo(HREF2))));
+ assertThat("Wrong Schema in the newly created SecurityProfile", actualProfiles, Matchers.<SecurityProfile> contains(
+ hasProperty("schema", equalTo(SCHEMA)),
+ hasProperty("schema", equalTo(SCHEMA2))));
+ verify(response, times(1)).close();
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQuery("fields=*"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class));
}
@Test
- public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException {
- // Prepare
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
- final NameValuePair[] queryString = new NameValuePair[]{
- new NameValuePair("uuid", UUID),
- new NameValuePair("fields","*")
- };
- final List<NameValuePair> queryStringNvps = new ArrayList<>();
- doAnswer(new Answer<Void>() {
-
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- final NameValuePair[] arguments = (NameValuePair[]) invocation.getArguments()[0];
- queryStringNvps.addAll(Arrays.asList(arguments));
- return null;
- }}).when(method).setQueryString(any(NameValuePair[].class));
-
- // Execute
- final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertTrue(queryStringNvps.containsAll(Arrays.asList(queryString)));
- assertEquals(queryString.length, queryStringNvps.size());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID, actualProfiles.getResults().get(0).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF, actualProfiles.getResults().get(0).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA, actualProfiles.getResults().get(0).getSchema());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID2, actualProfiles.getResults().get(1).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF2, actualProfiles.getResults().get(1).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA2, actualProfiles.getResults().get(1).getSchema());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- 2, actualProfiles.getResultCount());
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
- assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
- NiciraNvpApi.GET_METHOD_TYPE, type);
+ @SuppressWarnings("unchecked")
+ public void testFindSecurityProfileByUuid() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_200_REPSONSE);
+ when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_LIST_JSON_RESPONSE));
+ final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2));
+ doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class));
+ final NiciraNvpApi api = buildApi(httpClient);
+
+ final List<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID);
+
+ assertThat("Wrong number of results", actualProfiles, hasSize(2));
+ assertThat("Wrong Uuid in the newly created SecurityProfile", actualProfiles, Matchers.<SecurityProfile> contains(
+ hasProperty("uuid", equalTo(UUID)),
+ hasProperty("uuid", equalTo(UUID2))));
+ assertThat("Wrong HREF in the newly created SecurityProfile", actualProfiles, Matchers.<SecurityProfile> contains(
+ hasProperty("href", equalTo(HREF)),
+ hasProperty("href", equalTo(HREF2))));
+ assertThat("Wrong Schema in the newly created SecurityProfile", actualProfiles, Matchers.<SecurityProfile> contains(
+ hasProperty("schema", equalTo(SCHEMA)),
+ hasProperty("schema", equalTo(SCHEMA2))));
+ verify(response, times(1)).close();
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("uuid=" + UUID), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("fields=*"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class));
}
@Test
- public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- final SecurityProfile inputSecProfile = new SecurityProfile();
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
- when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE);
-
- // Execute
- final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID, actualSecProfile.getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF, actualSecProfile.getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA, actualSecProfile.getSchema());
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
- assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
- NiciraNvpApi.POST_METHOD_TYPE, type);
+ public void testCreateSecurityProfile() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE);
+ when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE));
+ final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2));
+ doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class));
+ final NiciraNvpApi api = buildApi(httpClient);
+
+ final SecurityProfile actualSecProfile = api.createSecurityProfile(new SecurityProfile());
+
+ assertThat("Wrong Uuid in the newly created SecurityProfile", actualSecProfile, hasProperty("uuid", equalTo(UUID)));
+ assertThat("Wrong Href in the newly created SecurityProfile", actualSecProfile, hasProperty("href", equalTo(HREF)));
+ assertThat("Wrong Schema in the newly created SecurityProfile", actualSecProfile, hasProperty("schema", equalTo(SCHEMA)));
+ verify(response, times(1)).close();
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class));
}
@Test
- public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- final SecurityProfile inputSecProfile = new SecurityProfile();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
-
- // Execute
- api.updateSecurityProfile(inputSecProfile, UUID);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- UUID_SEC_PROFILE_URI, uri);
- assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
- NiciraNvpApi.PUT_METHOD_TYPE, type);
+ public void testUpdateSecurityProfile() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE);
+ when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE));
+ final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2));
+ doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class));
+ final NiciraNvpApi api = buildApi(httpClient);
+
+ api.updateSecurityProfile(new SecurityProfile(), UUID);
+
+ verify(response, times(1)).close();
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX + "/" + UUID), any(HttpClientContext.class));
}
@Test
- public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ public void testDeleteSecurityProfile() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE);
+ when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE));
+ final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2));
+ doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class));
+ final NiciraNvpApi api = buildApi(httpClient);
- // Execute
api.deleteSecurityProfile(UUID);
- // Assert
- verify(method, times(1)).releaseConnection();
- assertEquals("Wrong URI for SecurityProfile deletion REST service", UUID_SEC_PROFILE_URI, uri);
- assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", NiciraNvpApi.DELETE_METHOD_TYPE, type);
- }
-
- @Test(expected = JsonParseException.class)
- public void testRoutingConfigAdapterNoType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{}", RoutingConfig.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test(expected = JsonParseException.class)
- public void testRoutingConfigAdapterWrongType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test()
- public void testRoutingConfigAdapter() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig =
- (SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class);
-
- // Assert: JsonParseException should be thrown
- assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass());
- }
-
- @Test(expected = JsonParseException.class)
- public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test(expected = JsonParseException.class)
- public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{type : \"WrongType\"}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test()
- public void testRoutingConfigAdapterWithSourceNatRule() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- final SourceNatRule sourceNatRule =
- (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- assertEquals("", SourceNatRule.class, sourceNatRule.getClass());
- }
-
- @Test()
- public void testRoutingConfigAdapterWithDestinationNatRule() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- final DestinationNatRule destinationNatRule =
- (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- assertEquals("", DestinationNatRule.class, destinationNatRule.getClass());
+ verify(response, times(1)).close();
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("DELETE"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX + "/" + UUID), any(HttpClientContext.class));
}
}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
index 25157a1..beb4059 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -45,7 +45,6 @@ import com.cloud.network.nicira.LogicalRouterPort;
import com.cloud.network.nicira.LogicalSwitch;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.nicira.VifAttachment;
public class NiciraNvpRequestWrapperTest {
@@ -144,10 +143,6 @@ public class NiciraNvpRequestWrapperTest {
final List<LogicalRouterPort> listPorts = new ArrayList<LogicalRouterPort>();
listPorts.add(port1);
- final NiciraNvpList<LogicalRouterPort> ports = new NiciraNvpList<LogicalRouterPort>();
- ports.setResults(listPorts);
- ports.setResultCount(1);
-
final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
final List<String> publicCidrs = new ArrayList<String>();
@@ -158,7 +153,7 @@ public class NiciraNvpRequestWrapperTest {
when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
try {
- when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(ports);
+ when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(listPorts);
doNothing().when(niciraNvpApi).updateLogicalRouterPort(command.getLogicalRouterUuid(), port1);
} catch (final NiciraNvpApiException e) {
fail(e.getMessage());
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
index 67d1a96..c0dedd2 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -83,7 +83,6 @@ import com.cloud.network.nicira.LogicalSwitchPort;
import com.cloud.network.nicira.NatRule;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.nicira.SourceNatRule;
import com.cloud.network.utils.CommandRetryUtility;
@@ -95,10 +94,10 @@ public class NiciraNvpResourceTest {
private CommandRetryUtility retryUtility;
@Before
- public void setUp() throws ConfigurationException {
+ public void setUp() {
resource = new NiciraNvpResource() {
@Override
- protected NiciraNvpApi createNiciraNvpApi() {
+ protected NiciraNvpApi createNiciraNvpApi(final String host, final String username, final String password) {
return nvpApi;
}
};
@@ -121,20 +120,6 @@ public class NiciraNvpResourceTest {
}
@Test
- public void resourceConfigure() throws ConfigurationException {
- resource.configure("NiciraNvpResource", parameters);
-
- verify(nvpApi).setAdminCredentials("adminuser", "adminpass");
- verify(nvpApi).setControllerAddress("127.0.0.1");
- assertTrue("Incorrect resource name", "nvptestdevice".equals(resource.getName()));
-
- /* Pretty lame test, but here to assure this plugin fails
- * if the type name ever changes from L2Networking
- */
- assertTrue("Incorrect resource type", resource.getType() == Host.Type.L2Networking);
- }
-
- @Test
public void testInitialization() throws ConfigurationException {
resource.configure("NiciraNvpResource", parameters);
@@ -309,10 +294,7 @@ public class NiciraNvpResourceTest {
public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
- when(lspl.getResultCount()).thenReturn(1);
+ final List<LogicalSwitchPort> lspl = Arrays.asList(new LogicalSwitchPort());
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
@@ -324,9 +306,7 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters);
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
- when(lspl.getResultCount()).thenReturn(0);
+ final List<LogicalSwitchPort> lspl = Collections.EMPTY_LIST;
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
@@ -427,8 +407,7 @@ public class NiciraNvpResourceTest {
final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<LogicalRouterPort> list = mock(NiciraNvpList.class);
+ final List<LogicalRouterPort> list = Collections.EMPTY_LIST;
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
@@ -472,8 +451,7 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ final List<NatRule> storedRules = Collections.EMPTY_LIST;
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
@@ -522,11 +500,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ final List<NatRule> storedRules = Arrays.asList(rulepair);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
@@ -571,11 +545,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ final List<NatRule> storedRules = Arrays.asList(rulepair);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
@@ -616,9 +586,7 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(0);
+ final List<NatRule> storedRules = Collections.EMPTY_LIST;
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
@@ -644,8 +612,7 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ final List<NatRule> storedRules = Collections.EMPTY_LIST;
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
@@ -694,11 +661,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ final List<NatRule> storedRules = Arrays.asList(rulepair);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
@@ -743,11 +706,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ final List<NatRule> storedRules = Arrays.asList(rulepair);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
@@ -788,9 +747,7 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(0);
+ final List<NatRule> storedRules = Collections.EMPTY_LIST;
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
@@ -816,8 +773,7 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ final List<NatRule> storedRules = Collections.EMPTY_LIST;
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java
new file mode 100644
index 0000000..948e9f6
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java
@@ -0,0 +1,43 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.rest;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.mockito.Matchers.argThat;
+
+import org.apache.http.client.methods.HttpUriRequest;
+import org.hamcrest.FeatureMatcher;
+import org.hamcrest.Matcher;
+
+public class HttpUriRequestPathMatcher extends FeatureMatcher<HttpUriRequest, String> {
+
+ public static HttpUriRequest aPath(final String path) {
+ return argThat(new HttpUriRequestPathMatcher(equalTo(path), "path", "path"));
+ }
+
+ public HttpUriRequestPathMatcher(final Matcher<? super String> subMatcher, final String featureDescription, final String featureName) {
+ super(subMatcher, featureDescription, featureName);
+ }
+
+ @Override
+ protected String featureValueOf(final HttpUriRequest actual) {
+ return actual.getURI().getPath();
+ }
+}
[11/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/StringUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/StringUtilsTest.java b/utils/src/test/java/com/cloud/utils/StringUtilsTest.java
new file mode 100644
index 0000000..3619ede
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/StringUtilsTest.java
@@ -0,0 +1,253 @@
+//
+// 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 com.cloud.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.junit.Test;
+
+public class StringUtilsTest {
+
+ @Test
+ public void testGetPreferredCharset() {
+ final boolean ifUtf8Supported = StringUtils.isUtf8Supported();
+ if (ifUtf8Supported) {
+ assertEquals(StringUtils.getPreferredCharset(), Charset.forName("UTF-8"));
+ } else {
+ assertNotEquals(StringUtils.getPreferredCharset(), Charset.forName("UTF-8"));
+ }
+ }
+
+ @Test
+ public void testGetDefaultCharset() {
+ // Is this test irrelevant? Is wrapping the Charset.defaultCharset() too much?
+ // This test was added in order to cover the new StringUtils.getDefaultCharset().
+ // One cannot be sure that StringUtils.getPreferredCharset() will always be
+ // equals to Charset.defaultCharset()
+ assertEquals(StringUtils.getDefaultCharset(), Charset.defaultCharset());
+ }
+
+ @Test
+ public void testCleanPasswordFromJsonObjectAtEnd() {
+ final String input = "{\"foo\":\"bar\",\"password\":\"test\"}";
+ //TODO: It would be nice to clean up the regex in question to not
+ //have to return the trailing comma in the expected string below
+ final String expected = "{\"foo\":\"bar\",}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromJsonObjectInMiddle() {
+ final String input = "{\"foo\":\"bar\",\"password\":\"test\",\"test\":\"blah\"}";
+ final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromJsonObjectAlone() {
+ final String input = "{\"password\":\"test\"}";
+ final String expected = "{}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromJsonObjectAtStart() {
+ final String input = "{\"password\":\"test\",\"test\":\"blah\"}";
+ final String expected = "{\"test\":\"blah\"}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromJsonObjectWithMultiplePasswords() {
+ final String input = "{\"description\":\"foo\"}],\"password\":\"bar\",\"nic\":[{\"password\":\"bar2\",\"id\":\"1\"}]}";
+ final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromRequestString() {
+ final String input = "username=foo&password=bar&url=foobar";
+ final String expected = "username=foo&url=foobar";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromEncodedRequestString() {
+ final String input = "name=SS1&provider=SMB&zoneid=5a60af2b-3025-4f2a-9ecc-8e33bf2b94e3&url=cifs%3A%2F%2F10.102.192.150%2FSMB-Share%2Fsowmya%2Fsecondary%3Fuser%3Dsowmya%26password%3DXXXXX%40123%26domain%3DBLR";
+ final String expected = "name=SS1&provider=SMB&zoneid=5a60af2b-3025-4f2a-9ecc-8e33bf2b94e3&url=cifs%3A%2F%2F10.102.192.150%2FSMB-Share%2Fsowmya%2Fsecondary%3Fuser%3Dsowmya%26domain%3DBLR";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromRequestStringWithMultiplePasswords() {
+ final String input = "username=foo&password=bar&url=foobar&password=bar2&test=4";
+ final String expected = "username=foo&url=foobar&test=4";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromRequestStringMatchedAtEndSingleQuote() {
+ final String input = "'username=foo&password=bar'";
+ final String expected = "'username=foo'";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromRequestStringMatchedAtEndDoubleQuote() {
+ final String input = "\"username=foo&password=bar\"";
+ final String expected = "\"username=foo\"";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanPasswordFromRequestStringMatchedAtMiddleDoubleQuote() {
+ final String input = "\"username=foo&password=bar&goo=sdf\"";
+ final String expected = "\"username=foo&goo=sdf\"";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testJoin() {
+ assertEquals("a-b-c", StringUtils.join("-", "a", "b", "c"));
+ assertEquals("", StringUtils.join("-"));
+ }
+
+ @Test
+ public void testCleanSecretkeyFromJsonObjectAtEnd() {
+ final String input = "{\"foo\":\"bar\",\"secretkey\":\"test\"}";
+ // TODO: It would be nice to clean up the regex in question to not
+ // have to return the trailing comma in the expected string below
+ final String expected = "{\"foo\":\"bar\",}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanSecretkeyFromJsonObjectInMiddle() {
+ final String input = "{\"foo\":\"bar\",\"secretkey\":\"test\",\"test\":\"blah\"}";
+ final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanSecretkeyFromJsonObjectAlone() {
+ final String input = "{\"secretkey\":\"test\"}";
+ final String expected = "{}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanSecretkeyFromJsonObjectAtStart() {
+ final String input = "{\"secretkey\":\"test\",\"test\":\"blah\"}";
+ final String expected = "{\"test\":\"blah\"}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanSecretkeyFromJsonObjectWithMultiplePasswords() {
+ final String input = "{\"description\":\"foo\"}],\"secretkey\":\"bar\",\"nic\":[{\"secretkey\":\"bar2\",\"id\":\"1\"}]}";
+ final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanAccesskeyFromJsonObjectAtEnd() {
+ final String input = "{\"foo\":\"bar\",\"accesskey\":\"test\"}";
+ // TODO: It would be nice to clean up the regex in question to not
+ // have to return the trailing comma in the expected string below
+ final String expected = "{\"foo\":\"bar\",}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanAccesskeyFromJsonObjectInMiddle() {
+ final String input = "{\"foo\":\"bar\",\"accesskey\":\"test\",\"test\":\"blah\"}";
+ final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanAccesskeyFromJsonObjectAlone() {
+ final String input = "{\"accesskey\":\"test\"}";
+ final String expected = "{}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanAccesskeyFromJsonObjectAtStart() {
+ final String input = "{\"accesskey\":\"test\",\"test\":\"blah\"}";
+ final String expected = "{\"test\":\"blah\"}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanAccesskeyFromJsonObjectWithMultiplePasswords() {
+ final String input = "{\"description\":\"foo\"}],\"accesskey\":\"bar\",\"nic\":[{\"accesskey\":\"bar2\",\"id\":\"1\"}]}";
+ final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanAccesskeyFromRequestString() {
+ final String input = "username=foo&accesskey=bar&url=foobar";
+ final String expected = "username=foo&url=foobar";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void testCleanSecretkeyFromRequestString() {
+ final String input = "username=foo&secretkey=bar&url=foobar";
+ final String expected = "username=foo&url=foobar";
+ final String result = StringUtils.cleanString(input);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void listToCsvTags() {
+ assertEquals("a,b,c", StringUtils.listToCsvTags(Arrays.asList("a","b", "c")));
+ assertEquals("", StringUtils.listToCsvTags(new ArrayList<String>()));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/TernaryTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/TernaryTest.java b/utils/src/test/java/com/cloud/utils/TernaryTest.java
new file mode 100644
index 0000000..cacbecb
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/TernaryTest.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class TernaryTest {
+ @Test
+ public void testEquals() {
+ Assert.assertEquals(new Ternary<String, String, String>("a", "b", "c"), new Ternary<String, String, String>("a", "b", "c"));
+ Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(new Ternary<String, String, String>("a", "b", "d")));
+ Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(""));
+ Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(null));
+ Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(new Pair<String, String>("a", "b")));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/TestProfiler.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/TestProfiler.java b/utils/src/test/java/com/cloud/utils/TestProfiler.java
new file mode 100644
index 0000000..2306cd7
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/TestProfiler.java
@@ -0,0 +1,116 @@
+//
+// 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 com.cloud.utils;
+
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.cloud.utils.testcase.Log4jEnabledTestCase;
+
+public class TestProfiler extends Log4jEnabledTestCase {
+ protected final static Logger s_logger = Logger.getLogger(TestProfiler.class);
+
+ private static final long ONE_SECOND = 1000l;
+ private static final long MILLIS_FACTOR = 1000l;
+ private static final int MARGIN = 100;
+ private static final double EXPONENT = 3d;
+
+ @Test
+ public void testProfilerInMillis() {
+ s_logger.info("testProfiler() started");
+
+ final Profiler pf = new Profiler();
+ pf.start();
+ try {
+ Thread.sleep(ONE_SECOND);
+ } catch (final InterruptedException e) {
+ }
+ pf.stop();
+
+ final long durationInMillis = pf.getDurationInMillis();
+ s_logger.info("Duration in Millis: " + durationInMillis);
+
+ // An error margin in order to cover the time taken by the star/stop calls.
+ // 100 milliseconds margin seems too much, but it will avoid assertion error
+ // and also fail in case a duration in nanoseconds is used instead.
+ Assert.assertTrue(durationInMillis >= MILLIS_FACTOR && durationInMillis <= MILLIS_FACTOR + MARGIN);
+
+ s_logger.info("testProfiler() stopped");
+ }
+
+ @Test
+ public void testProfilerInNano() {
+ final Profiler pf = new Profiler();
+ pf.start();
+ try {
+ Thread.sleep(ONE_SECOND);
+ } catch (final InterruptedException e) {
+ }
+ pf.stop();
+
+ final long duration = pf.getDuration();
+ s_logger.info("Duration in Nano: " + duration);
+ Assert.assertTrue(duration >= Math.pow(MILLIS_FACTOR, EXPONENT));
+ }
+
+ @Test
+ public void testProfilerNoStart() {
+ final Profiler pf = new Profiler();
+ try {
+ Thread.sleep(20);
+ } catch (final InterruptedException e) {
+ }
+ pf.stop();
+
+ Assert.assertTrue(pf.getDurationInMillis() == -1);
+ Assert.assertFalse(pf.isStarted());
+ }
+
+ @Test
+ public void testProfilerNoStop() {
+ final Profiler pf = new Profiler();
+ pf.start();
+ try {
+ Thread.sleep(20);
+ } catch (final InterruptedException e) {
+ }
+
+ Assert.assertTrue(pf.getDurationInMillis() == -1);
+ Assert.assertFalse(pf.isStopped());
+ }
+
+ @Test
+ public void testResolution() {
+ long nanoTime1 = 0l;
+ long nanoTime2 = 0l;
+ nanoTime1 = System.nanoTime();
+ nanoTime2 = System.nanoTime();
+
+ // Using sysout here because is faster than the logger and we don't want to
+ // waste time.
+ System.out.println("Nano time 1: " + nanoTime1);
+ System.out.println("Nano time 2: " + nanoTime2);
+
+ // We are measuring the elapsed time in 2 consecutive calls of System.nanoTime()
+ // That's the same as 0.002 milliseconds or 2000 nanoseconds.
+ Assert.assertTrue("Expected exactly 2 but it took more than 3 microseconds between 2 consecutive calls to System.nanoTime().", nanoTime2 - nanoTime1 <= 3000);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/UriUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/UriUtilsTest.java b/utils/src/test/java/com/cloud/utils/UriUtilsTest.java
new file mode 100644
index 0000000..d2fd997
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/UriUtilsTest.java
@@ -0,0 +1,60 @@
+//
+// 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 com.cloud.utils;
+
+import junit.framework.Assert;
+
+import org.junit.Test;
+
+public class UriUtilsTest {
+ @Test
+ public void encodeURIComponent() {
+ Assert.assertEquals("http://localhost",
+ UriUtils.encodeURIComponent("http://localhost"));
+ Assert.assertEquals("http://localhost/",
+ UriUtils.encodeURIComponent("http://localhost/"));
+ Assert.assertEquals("http://localhost/foo/bar",
+ UriUtils.encodeURIComponent("http://localhost/foo/bar"));
+ }
+
+ @Test
+ public void getUpdateUri() {
+ // no password param, no request for encryption
+ Assert.assertEquals("http://localhost/foo/bar?param=true", UriUtils
+ .getUpdateUri("http://localhost/foo/bar?param=true", false));
+ // there is password param but still no request for encryption, should
+ // be unchanged
+ Assert.assertEquals("http://localhost/foo/bar?password=1234", UriUtils
+ .getUpdateUri("http://localhost/foo/bar?password=1234", false));
+ // if there is password param and encryption is requested then it may or
+ // may not be changed depending on how the EncrytionUtils is setup, but
+ // at least it needs to start with the same url
+ Assert.assertTrue(UriUtils.getUpdateUri(
+ "http://localhost/foo/bar?password=1234", true).startsWith(
+ "http://localhost/foo/bar"));
+
+ //just to see if it is still ok with multiple parameters
+ Assert.assertEquals("http://localhost/foo/bar?param1=true¶m2=12345", UriUtils
+ .getUpdateUri("http://localhost/foo/bar?param1=true¶m2=12345", false));
+
+ //XXX: Interesting cases not covered:
+ // * port is ignored and left out from the return value
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java b/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java
new file mode 100644
index 0000000..2ef6bbd
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java
@@ -0,0 +1,42 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class UuidUtilsTest {
+
+ @Test
+ public void testValidateUUIDPass() throws Exception {
+ String serviceUuid = "f81a9aa3-1f7d-466f-b04b-f2b101486bae";
+
+ assertTrue(UuidUtils.validateUUID(serviceUuid));
+ }
+
+ @Test
+ public void testValidateUUIDFail() throws Exception {
+ String serviceUuid = "6fc6ce7-d503-4f95-9e68-c9cd281b13df";
+
+ assertFalse(UuidUtils.validateUUID(serviceUuid));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java b/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java
new file mode 100644
index 0000000..d397511
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java
@@ -0,0 +1,112 @@
+//
+// 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 com.cloud.utils.backoff.impl;
+
+import java.util.HashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ConstantTimeBackoffTest {
+ final static private Log LOG = LogFactory.getLog(ConstantTimeBackoffTest.class);
+
+ @Test
+ public void waitBeforeRetryWithInterrupt() throws InterruptedException {
+ final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
+ backoff.setTimeToWait(10);
+ Assert.assertTrue(backoff.getWaiters().isEmpty());
+ Thread waitThread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ backoff.waitBeforeRetry();
+ }
+ });
+ waitThread.start();
+ Thread.sleep(100);
+ Assert.assertFalse(backoff.getWaiters().isEmpty());
+ waitThread.interrupt();
+ Thread.sleep(100);
+ Assert.assertTrue(backoff.getWaiters().isEmpty());
+ }
+
+ @Test
+ public void waitBeforeRetry() throws InterruptedException {
+ final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
+ // let's not wait too much in a test
+ backoff.setTimeToWait(0);
+ // check if the list of waiters is empty
+ Assert.assertTrue(backoff.getWaiters().isEmpty());
+ // call the waitBeforeRetry which will wait 0 ms and return
+ backoff.waitBeforeRetry();
+ // on normal exit the list of waiters should be cleared
+ Assert.assertTrue(backoff.getWaiters().isEmpty());
+ }
+
+ @Test
+ public void configureEmpty() {
+ // at this point this is the only way rhe configure method gets invoked,
+ // therefore have to make sure it works correctly
+ final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
+ backoff.configure("foo", new HashMap<String, Object>());
+ Assert.assertEquals(5000, backoff.getTimeToWait());
+ }
+
+ @Test
+ public void configureWithValue() {
+ final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
+ HashMap<String, Object> params = new HashMap<String, Object>();
+ params.put("seconds", "100");
+ backoff.configure("foo", params);
+ Assert.assertEquals(100000, backoff.getTimeToWait());
+ }
+
+ /**
+ * Test that wakeup returns false when trying to wake a non existing thread.
+ */
+ @Test
+ public void wakeupNotExisting() {
+ final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
+ Assert.assertFalse(backoff.wakeup("NOT EXISTING THREAD"));
+ }
+
+ /**
+ * Test that wakeup will return true if the thread is waiting.
+ */
+ @Test
+ public void wakeupExisting() throws InterruptedException {
+ final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
+ backoff.setTimeToWait(10);
+ Thread thread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ LOG.debug("before");
+ backoff.waitBeforeRetry();
+ LOG.debug("after");
+ }
+ });
+ thread.start();
+ LOG.debug("thread started");
+ Thread.sleep(100);
+ LOG.debug("testing wakeup");
+ Assert.assertTrue(backoff.wakeup(thread.getName()));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java b/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java
new file mode 100644
index 0000000..0f3f058
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java
@@ -0,0 +1,45 @@
+//
+// 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 com.cloud.utils.crypto;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.Properties;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.cloud.utils.crypt.EncryptionSecretKeyChecker;
+import com.cloud.utils.db.DbProperties;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class EncryptionSecretKeyCheckerTest {
+
+ private EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker();
+
+ @Test(expected = CloudRuntimeException.class)
+ public void testKeyFileDoesNotExists() throws IOException, URISyntaxException {
+ Assert.assertNotNull(checker);
+ Properties properties = DbProperties.getDbProperties();
+ properties.setProperty("db.cloud.encryption.type", "file");
+ checker.check(properties);
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java b/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java
new file mode 100644
index 0000000..27d9d50
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java
@@ -0,0 +1,54 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.crypto;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Test;
+
+import com.cloud.utils.crypt.RSAHelper;
+
+public class RSAHelperTest {
+ @Test
+ public void testEncryptWithRSA() {
+ String rsaKey =
+ "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW"
+ + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk"
+ + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P"
+ + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX";
+ String encryptedString = RSAHelper.encryptWithSSHPublicKey(rsaKey, "content");
+ assertNotNull(encryptedString);
+ }
+
+ @Test
+ public void testEncryptWithDSA() {
+ String dssKey =
+ "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV"
+ + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO"
+ + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA"
+ + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF"
+ + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD"
+ + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR"
+ + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ==";
+ String encryptedString = RSAHelper.encryptWithSSHPublicKey(dssKey, "content");
+ assertNull(encryptedString);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java b/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java
new file mode 100644
index 0000000..3d4dfc9
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java
@@ -0,0 +1,33 @@
+//
+// 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 com.cloud.utils.encoding;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UrlEncoderTest {
+ @Test
+ public void encode() {
+ Assert.assertEquals("%2Ftmp%2F", new URLEncoder().encode("/tmp/"));
+ Assert.assertEquals("%20", new URLEncoder().encode(" "));
+ Assert.assertEquals("%5F", new URLEncoder().encode("_"));
+ Assert.assertEquals("%25", new URLEncoder().encode("%"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java b/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java
new file mode 100644
index 0000000..9e1948e
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java
@@ -0,0 +1,52 @@
+//
+// 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 com.cloud.utils.exception;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import org.junit.Test;
+
+public class ExceptionUtilTest {
+
+ @Test
+ public void test() throws Exception {
+ FileNotFoundException fnfe = new FileNotFoundException();
+ try {
+ ExceptionUtil.rethrow(fnfe, IOException.class);
+ fail();
+ } catch (IOException e) {
+ assertTrue("we won !?!", true);
+ }
+
+ ExceptionUtil.rethrow(fnfe, ClassNotFoundException.class);
+
+ try {
+ ExceptionUtil.rethrow(fnfe, FileNotFoundException.class);
+ fail();
+ } catch (FileNotFoundException e) {
+ assertTrue("we won !?!", true);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java b/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java
new file mode 100644
index 0000000..79ff238
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java
@@ -0,0 +1,40 @@
+// 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 com.cloud.utils.net;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.testing.EqualsTester;
+
+public class Ip4AddressTest {
+
+ @Test
+ public void testEquals() throws Exception {
+ new EqualsTester()
+ .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:02"), new Ip4Address(1L, 2L))
+ .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:00"), new Ip4Address(1L, 0L), new Ip4Address(1L, 0L), new Ip4Address(1L), new Ip4Address("0.0.0.1"))
+ .testEquals();
+ }
+
+ @Test
+ public void testIsSameAddressAs() {
+ Assert.assertTrue("1 and one should be considdered the same address", new Ip4Address(1L, 5L).isSameAddressAs("0.0.0.1"));
+ Assert.assertFalse("zero and 0L should be considdered the same address but a Long won't be accepted", new Ip4Address("0.0.0.0", "00:00:00:00:00:08").isSameAddressAs(0L));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/IpTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/net/IpTest.java b/utils/src/test/java/com/cloud/utils/net/IpTest.java
new file mode 100644
index 0000000..89608f1
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/net/IpTest.java
@@ -0,0 +1,63 @@
+//
+// 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 com.cloud.utils.net;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.testing.EqualsTester;
+
+public class IpTest {
+
+ @Test
+ public void testUltimate() {
+ Ip max = new Ip(2L * Integer.MAX_VALUE +1 );
+ assertEquals("Maximal address not created", "255.255.255.255", max.addr());
+ }
+ @Test
+ public void testTurningOfTheCentury() {
+ Ip eve = new Ip(Integer.MAX_VALUE);
+ assertEquals("Minimal address not created", "127.255.255.255", eve.addr());
+ Ip dawn = new Ip(Integer.MAX_VALUE + 1L);
+ assertEquals("Minimal address not created", "128.0.0.0", dawn.addr());
+ }
+ @Test
+ public void testStart() {
+ Ip min = new Ip(0);
+ assertEquals("Minimal address not created", "0.0.0.0", min.addr());
+ }
+
+ @Test
+ public void testEquals() {
+ new EqualsTester()
+ .addEqualityGroup(new Ip("0.0.0.1"), new Ip(1L))
+ .addEqualityGroup(new Ip("0.0.0.0"), new Ip(0L))
+ .testEquals();
+ }
+
+ @Test
+ public void testIsSameAddressAs() {
+ Assert.assertTrue("1 and one should be considdered the same address", new Ip(1L).isSameAddressAs("0.0.0.1"));
+ Assert.assertTrue("zero and 0L should be considdered the same address", new Ip("0.0.0.0").isSameAddressAs(0L));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java b/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java
new file mode 100644
index 0000000..845a435
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java
@@ -0,0 +1,60 @@
+//
+// 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 com.cloud.utils.net;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class MacAddressTest {
+
+ @Test
+ public final void testMacAddress() throws Exception {
+ MacAddress mac = new MacAddress();
+ assertEquals(0L,mac.toLong());
+ }
+
+ @Test
+ public final void testMacAddressLong() throws Exception {
+ MacAddress mac = new MacAddress(1L);
+ assertEquals(1L,mac.toLong());
+ }
+
+ @Test
+ public final void testMacAddressToLong() throws Exception {
+ // TODO this test should fail this address is beyond the acceptable range for macaddresses
+ MacAddress mac = new MacAddress(Long.MAX_VALUE);
+ assertEquals(Long.MAX_VALUE,mac.toLong());
+ System.out.println(mac.toString());
+ }
+
+ // TODO public final void testToLong() throws Exception {
+ // TODO public final void testToByteArray() throws Exception {
+ // TODO public final void testToStringString() throws Exception {
+ // TODO public final void testToString() throws Exception {
+ // TODO public final void testGetMacAddress() throws Exception {
+ // TODO public final void testParse() throws Exception {
+ // TODO public final void testMain() throws Exception {
+ // TODO public final void testParseLong() throws Exception {
+ // TODO public final void testParseInt() throws Exception {
+ // TODO public final void testParseShort() throws Exception {
+ // TODO public final void testParseByte() throws Exception {
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java
new file mode 100644
index 0000000..1ab4459
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java
@@ -0,0 +1,421 @@
+//
+// 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 com.cloud.utils.net;
+
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import java.math.BigInteger;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.apache.log4j.Logger;
+import org.junit.Test;
+
+import com.googlecode.ipv6.IPv6Address;
+
+public class NetUtilsTest {
+
+ private static final Logger s_logger = Logger.getLogger(NetUtilsTest.class);
+
+ @Test
+ public void testGetRandomIpFromCidrWithSize24() throws Exception {
+ final String cidr = "192.168.124.1";
+ final int size = 24;
+ final int netCharacters = 12;
+
+ final long ip = NetUtils.getRandomIpFromCidr(cidr, size, new TreeSet<Long>());
+
+ assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip)
+ .substring(0, netCharacters)));
+ }
+
+ @Test
+ public void testGetRandomIpFromCidrWithSize16() throws Exception {
+ final String cidr = "192.168.124.1";
+ final int size = 16;
+ final int netCharacters = 8;
+
+ final long ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>());
+
+ assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip)
+ .substring(0, netCharacters)));
+ }
+
+ @Test
+ public void testGetRandomIpFromCidrWithSize8() throws Exception {
+ final String cidr = "192.168.124.1";
+ final int size = 8;
+ final int netCharacters = 4;
+
+ final long ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>());
+
+ assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip)
+ .substring(0, netCharacters)));
+ }
+
+ @Test
+ public void testGetRandomIpFromCidrUsignAvoid() throws Exception {
+ final String cidr = "192.168.124.1";
+ final int size = 30;
+
+ final SortedSet<Long> avoid = new TreeSet<Long>();
+ long ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
+ assertThat("We should be able to retrieve an ip on the first call.", ip, not(equalTo(-1L)));
+ avoid.add(ip);
+ ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
+ assertThat("We should be able to retrieve an ip on the second call.", ip, not(equalTo(-1L)));
+ assertThat("ip returned is not in the avoid list", avoid, not(contains(ip)));
+ avoid.add(ip);
+ ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
+ assertThat("We should be able to retrieve an ip on the third call.", ip, not(equalTo(-1L)));
+ assertThat("ip returned is not in the avoid list", avoid, not(contains(ip)));
+ avoid.add(ip);
+ ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid);
+ assertEquals("This should be -1 because we ran out of ip addresses: " + ip, ip, -1);
+ }
+
+ @Test
+ public void testIsValidS2SVpnPolicy() {
+ assertTrue(NetUtils.isValidS2SVpnPolicy("aes128-sha1"));
+ assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1"));
+ assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1,aes256-sha1"));
+ assertTrue(NetUtils.isValidS2SVpnPolicy("3des-md5;modp1024"));
+ assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1,aes128-sha1;modp1536"));
+ assertFalse(NetUtils.isValidS2SVpnPolicy("des-md5;modp1024,aes128-sha1;modp1536"));
+ assertFalse(NetUtils.isValidS2SVpnPolicy("des-sha1"));
+ assertFalse(NetUtils.isValidS2SVpnPolicy("abc-123,ase-sha1"));
+ assertFalse(NetUtils.isValidS2SVpnPolicy("de-sh,aes-sha1"));
+ assertFalse(NetUtils.isValidS2SVpnPolicy(""));
+ assertFalse(NetUtils.isValidS2SVpnPolicy(";modp1536"));
+ assertFalse(NetUtils.isValidS2SVpnPolicy(",aes;modp1536,,,"));
+ }
+
+ @Test
+ public void testGetIp6FromRange() {
+ assertEquals(NetUtils.getIp6FromRange("1234:5678::1-1234:5678::1"), "1234:5678::1");
+ for (int i = 0; i < 5; i++) {
+ final String ip = NetUtils.getIp6FromRange("1234:5678::1-1234:5678::2");
+ assertThat(ip, anyOf(equalTo("1234:5678::1"), equalTo("1234:5678::2")));
+ s_logger.info("IP is " + ip);
+ }
+ String ipString = null;
+ final IPv6Address ipStart = IPv6Address.fromString("1234:5678::1");
+ final IPv6Address ipEnd = IPv6Address.fromString("1234:5678::ffff:ffff:ffff:ffff");
+ for (int i = 0; i < 10; i++) {
+ ipString = NetUtils.getIp6FromRange(ipStart.toString() + "-" + ipEnd.toString());
+ s_logger.info("IP is " + ipString);
+ final IPv6Address ip = IPv6Address.fromString(ipString);
+ assertThat(ip, greaterThanOrEqualTo(ipStart));
+ assertThat(ip, lessThanOrEqualTo(ipEnd));
+ }
+ }
+
+ @Test
+ public void testCountIp6InRange() {
+ assertEquals(new BigInteger("2"), NetUtils.countIp6InRange("1234:5678::1-1234:5678::2"));
+ }
+
+ @Test
+ public void testCountIp6InRangeWithInvalidRange() {
+ assertEquals(null, NetUtils.countIp6InRange("1234:5678::2-1234:5678::0"));
+ }
+
+ @Test
+ public void testCountIp6InRangeWithNullStart() {
+ assertEquals(null, NetUtils.countIp6InRange("-1234:5678::0"));
+ }
+
+ @Test
+ public void testCountIp6InRangeWithNoEnd() {
+ assertEquals(new BigInteger("1"), NetUtils.countIp6InRange("1234:5678::2"));
+ }
+
+ @Test
+ public void testGetIp6CidrSize() {
+ assertEquals(NetUtils.getIp6CidrSize("1234:5678::1/32"), 32);
+ assertEquals(NetUtils.getIp6CidrSize("1234:5678::1"), 0);
+ }
+
+ @Test
+ public void testIsValidIp6Cidr() {
+ assertTrue(NetUtils.isValidIp6Cidr("1234:5678::1/64"));
+ assertFalse(NetUtils.isValidIp6Cidr("1234:5678::1"));
+ }
+
+ @Test
+ public void testIsValidIpv6() {
+ assertTrue(NetUtils.isValidIpv6("fc00::1"));
+ assertFalse(NetUtils.isValidIpv6(""));
+ assertFalse(NetUtils.isValidIpv6(null));
+ assertFalse(NetUtils.isValidIpv6("1234:5678::1/64"));
+ }
+
+ @Test
+ public void testIsIp6InRange() {
+ assertTrue(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678:abcd::1-1234:5678:abcd::1"));
+ assertFalse(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678:abcd::2-1234:5678:abcd::1"));
+ assertFalse(NetUtils.isIp6InRange("1234:5678:abcd::1", null));
+ assertTrue(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678::1-1234:5679::1"));
+ }
+
+ @Test
+ public void testIsIp6InNetwork() {
+ assertFalse(NetUtils.isIp6InNetwork("1234:5678:abcd::1", "1234:5678::/64"));
+ assertTrue(NetUtils.isIp6InNetwork("1234:5678::1", "1234:5678::/64"));
+ assertTrue(NetUtils.isIp6InNetwork("1234:5678::ffff:ffff:ffff:ffff", "1234:5678::/64"));
+ assertTrue(NetUtils.isIp6InNetwork("1234:5678::", "1234:5678::/64"));
+ }
+
+ @Test
+ public void testGetNextIp6InRange() {
+ String range = "1234:5678::1-1234:5678::8000:0000";
+ assertEquals(NetUtils.getNextIp6InRange("1234:5678::8000:0", range), "1234:5678::1");
+ assertEquals(NetUtils.getNextIp6InRange("1234:5678::7fff:ffff", range), "1234:5678::8000:0");
+ assertEquals(NetUtils.getNextIp6InRange("1234:5678::1", range), "1234:5678::2");
+ range = "1234:5678::1-1234:5678::ffff:ffff:ffff:ffff";
+ assertEquals(NetUtils.getNextIp6InRange("1234:5678::ffff:ffff:ffff:ffff", range), "1234:5678::1");
+ }
+
+ @Test
+ public void testIsIp6RangeOverlap() {
+ assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::1-1234:5678::ffff", "1234:5678:1::1-1234:5678:1::ffff"));
+ assertTrue(NetUtils.isIp6RangeOverlap("1234:5678::1-1234:5678::ffff", "1234:5678::2-1234:5678::f"));
+ assertTrue(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::ffff", "1234:5678::2-1234:5678::f"));
+ assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::ffff", "1234:5678::2-1234:5678::e"));
+ assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::f", "1234:5678::2-1234:5678::e"));
+ }
+
+ @Test
+ public void testStandardizeIp6Address() {
+ assertEquals(NetUtils.standardizeIp6Address("1234:0000:0000:5678:0000:0000:ABCD:0001"), "1234::5678:0:0:abcd:1");
+ assertEquals(NetUtils.standardizeIp6Cidr("1234:0000:0000:5678:0000:0000:ABCD:0001/64"), "1234:0:0:5678::/64");
+ }
+
+ @Test
+ public void testGenerateUriForPvlan() {
+ assertEquals("pvlan://123-i456", NetUtils.generateUriForPvlan("123", "456").toString());
+ }
+
+ @Test
+ public void testGetPrimaryPvlanFromUri() {
+ assertEquals("123", NetUtils.getPrimaryPvlanFromUri(NetUtils.generateUriForPvlan("123", "456")));
+ }
+
+ @Test
+ public void testGetIsolatedPvlanFromUri() {
+ assertEquals("456", NetUtils.getIsolatedPvlanFromUri(NetUtils.generateUriForPvlan("123", "456")));
+ }
+
+ @Test
+ public void testIsValidCIDR() throws Exception {
+ //Test to check IP Range of 2 CIDR
+ final String cidrFirst = "10.0.144.0/20";
+ final String cidrSecond = "10.0.151.0/20";
+ final String cidrThird = "10.0.144.0/21";
+
+ assertTrue(NetUtils.isValidCIDR(cidrFirst));
+ assertTrue(NetUtils.isValidCIDR(cidrSecond));
+ assertTrue(NetUtils.isValidCIDR(cidrThird));
+ }
+
+ @Test
+ public void testIsValidCidrList() throws Exception {
+ final String cidrFirst = "10.0.144.0/20,1.2.3.4/32,5.6.7.8/24";
+ final String cidrSecond = "10.0.151.0/20,129.0.0.0/4";
+ final String cidrThird = "10.0.144.0/21";
+
+ assertTrue(NetUtils.isValidCidrList(cidrFirst));
+ assertTrue(NetUtils.isValidCidrList(cidrSecond));
+ assertTrue(NetUtils.isValidCidrList(cidrThird));
+ }
+
+ @Test
+ public void testIsSameIpRange() {
+ final String cidrFirst = "10.0.144.0/20";
+ final String cidrSecond = "10.0.151.0/20";
+ final String cidrThird = "10.0.144.0/21";
+
+ //Check for exactly same CIDRs
+ assertTrue(NetUtils.isSameIpRange(cidrFirst, cidrFirst));
+ //Check for 2 different CIDRs, but same IP Range
+ assertTrue(NetUtils.isSameIpRange(cidrFirst, cidrSecond));
+ //Check for 2 different CIDRs and different IP Range
+ assertFalse(NetUtils.isSameIpRange(cidrFirst, cidrThird));
+ //Check for Incorrect format of CIDR
+ assertFalse(NetUtils.isSameIpRange(cidrFirst, "10.3.6.5/50"));
+ }
+
+ @Test
+ public void testGenerateMacOnIncrease() {
+ String mac = "06:01:23:00:45:67";
+ assertEquals("06:01:25:00:45:67", NetUtils.generateMacOnIncrease(mac, 2));
+ assertEquals("06:01:33:00:45:67", NetUtils.generateMacOnIncrease(mac, 16));
+ mac = "06:ff:ff:00:45:67";
+ assertEquals("06:00:00:00:45:67", NetUtils.generateMacOnIncrease(mac, 1));
+ assertEquals("06:00:0f:00:45:67", NetUtils.generateMacOnIncrease(mac, 16));
+ }
+
+ @Test
+ public void testGetLocalIPString() {
+ assertNotNull(NetUtils.getLocalIPString());
+ }
+
+ @Test
+ public void testSameIsolationId() {
+ assertTrue(NetUtils.isSameIsolationId("1", "vlan://1"));
+ assertTrue(NetUtils.isSameIsolationId("", null));
+ assertTrue(NetUtils.isSameIsolationId("UnTagged", "vlan://uNtAGGED"));
+ assertFalse(NetUtils.isSameIsolationId("2", "vlan://uNtAGGED"));
+ assertFalse(NetUtils.isSameIsolationId("2", "vlan://3"));
+ assertFalse(NetUtils.isSameIsolationId("bla", null));
+ }
+
+ @Test
+ public void testValidateGuestCidr() throws Exception {
+ final String guestCidr = "192.168.1.0/24";
+
+ assertTrue(NetUtils.validateGuestCidr(guestCidr));
+ }
+
+ @Test
+ public void testMac2Long() {
+ assertEquals(0l, NetUtils.mac2Long("00:00:00:00:00:00"));
+ assertEquals(1l, NetUtils.mac2Long("00:00:00:00:00:01"));
+ assertEquals(0xFFl, NetUtils.mac2Long("00:00:00:00:00:FF"));
+ assertEquals(0xFFAAl, NetUtils.mac2Long("00:00:00:00:FF:AA"));
+ assertEquals(0x11FFAAl, NetUtils.mac2Long("00:00:00:11:FF:AA"));
+ assertEquals(0x12345678l, NetUtils.mac2Long("00:00:12:34:56:78"));
+ assertEquals(0x123456789Al, NetUtils.mac2Long("00:12:34:56:78:9A"));
+ assertEquals(0x123456789ABCl, NetUtils.mac2Long("12:34:56:78:9A:BC"));
+ }
+
+ @Test
+ public void testLong2Mac() {
+ assertEquals("00:00:00:00:00:00", NetUtils.long2Mac(0l));
+ assertEquals("00:00:00:00:00:01", NetUtils.long2Mac(1l));
+ assertEquals("00:00:00:00:00:ff", NetUtils.long2Mac(0xFFl));
+ assertEquals("00:00:00:00:ff:aa", NetUtils.long2Mac(0xFFAAl));
+ assertEquals("00:00:00:11:ff:aa", NetUtils.long2Mac(0x11FFAAl));
+ assertEquals("00:00:12:34:56:78", NetUtils.long2Mac(0x12345678l));
+ assertEquals("00:12:34:56:78:9a", NetUtils.long2Mac(0x123456789Al));
+ assertEquals("12:34:56:78:9a:bc", NetUtils.long2Mac(0x123456789ABCl));
+ }
+
+ @Test
+ public void testIp2Long() {
+ assertEquals(0x7f000001l, NetUtils.ip2Long("127.0.0.1"));
+ assertEquals(0xc0a80001l, NetUtils.ip2Long("192.168.0.1"));
+ assertEquals(0x08080808l, NetUtils.ip2Long("8.8.8.8"));
+ }
+
+ @Test
+ public void testLong2Ip() {
+ assertEquals("127.0.0.1", NetUtils.long2Ip(0x7f000001l));
+ assertEquals("192.168.0.1", NetUtils.long2Ip(0xc0a80001l));
+ assertEquals("8.8.8.8", NetUtils.long2Ip(0x08080808l));
+ }
+
+ @Test
+ public void test31BitPrefixStart() {
+ final String ipAddress = "192.168.0.0";
+ final String cidr = "192.168.0.0/31";
+
+ final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr);
+
+ assertTrue("Check if the subnetUtils.setInclusiveHostCount(true) has been called.", isInRange);
+ }
+
+ @Test
+ public void test31BitPrefixEnd() {
+ final String ipAddress = "192.168.0.1";
+ final String cidr = "192.168.0.0/31";
+
+ final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr);
+
+ assertTrue("Check if the subnetUtils.setInclusiveHostCount(true) has been called.", isInRange);
+ }
+
+ @Test
+ public void test31BitPrefixFail() {
+ final String ipAddress = "192.168.0.2";
+ final String cidr = "192.168.0.0/31";
+
+ final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr);
+
+ assertFalse("Out of the range. Why did it return true?", isInRange);
+ }
+
+ @Test
+ public void test31BitPrefixIpRangesOverlapd() {
+ final String gw = "192.168.0.0";
+ String ip1;
+ String ip2;
+
+ for (int i = 1, j = 2; i <= 254; i++, j++) {
+ ip1 = "192.168.0." + i;
+ ip2 = "192.168.0." + j;
+
+ final boolean doesOverlap = NetUtils.ipRangesOverlap(ip1, ip2, gw, gw);
+ assertFalse("It should overlap, but it's a 31-bit ip", doesOverlap);
+ }
+ }
+
+ @Test
+ public void test31BitPrefixIpRangesOverlapdFail() {
+ String gw;
+ String ip1;
+ String ip2;
+
+ for (int i = 10, j = 12; i <= 254; i++, j++) {
+ gw = "192.168.0." + i;
+ ip1 = "192.168.0." + i;
+ ip2 = "192.168.0." + j;
+
+ final boolean doesOverlap = NetUtils.ipRangesOverlap(ip1, ip2, gw, gw);
+ assertTrue("It overlaps!", doesOverlap);
+ }
+ }
+
+ @Test
+ public void testIs31PrefixCidrFail() {
+ final String cidr = "10.10.0.0/32";
+ final boolean is31PrefixCidr = NetUtils.is31PrefixCidr(cidr);
+
+ assertFalse("It should fail! 32 bit prefix.", is31PrefixCidr);
+ }
+
+ @Test
+ public void testIs31PrefixCidr() {
+ final String cidr = "10.10.0.0/31";
+ final boolean is31PrefixCidr = NetUtils.is31PrefixCidr(cidr);
+
+ assertTrue("It should pass! 31 bit prefix.", is31PrefixCidr);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
new file mode 100644
index 0000000..6d58b5b
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
@@ -0,0 +1,395 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.Collections;
+
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.params.HttpClientParams;
+import org.apache.http.HttpStatus;
+import org.junit.Before;
+import org.junit.Test;
+
+public class RESTServiceConnectorTest {
+ protected static final String UUID = "aaaa";
+ protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}";
+
+ RESTServiceConnector connector;
+ HttpClient client = mock(HttpClient.class);
+ HttpMethod method;
+ String type;
+ String uri;
+
+ @Before
+ public void setUp() {
+ final HttpClientParams hmp = mock(HttpClientParams.class);
+ when(client.getParams()).thenReturn(hmp);
+ connector = new RESTServiceConnector(null) {
+ @Override
+ public HttpClient createHttpClient() {
+ return client;
+ }
+
+ @Override
+ public HttpMethod createMethod(final String newType, final String newUri) {
+ type = newType;
+ uri = newUri;
+ return method;
+ }
+ };
+
+ connector.validation = new RESTValidationStrategy();
+ connector.setAdminCredentials("admin", "adminpass");
+ connector.setControllerAddress("localhost");
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteLoginWithoutHostname() throws CloudstackRESTException {
+ connector.setControllerAddress(null);
+ connector.validation.login(RESTServiceConnector.protocol, client);
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteLoginWithoutCredentials() throws CloudstackRESTException {
+ method = mock(PutMethod.class);
+ connector.setAdminCredentials(null, null);
+ connector.validation.login(RESTServiceConnector.protocol, client);
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteUpdateObjectWithoutHostname() throws CloudstackRESTException {
+ method = mock(PutMethod.class);
+ connector.setControllerAddress(null);
+ connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteUpdateObjectWithoutCredentials() throws CloudstackRESTException {
+ method = mock(PutMethod.class);
+ connector.setAdminCredentials(null, null);
+ connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteCreateObjectWithoutHostname() throws CloudstackRESTException {
+ method = mock(PostMethod.class);
+ connector.setControllerAddress(null);
+ connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteCreateObjectWithoutCredentials() throws CloudstackRESTException {
+ method = mock(PostMethod.class);
+ connector.setAdminCredentials(null, null);
+ connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteDeleteObjectWithoutHostname() throws CloudstackRESTException {
+ method = mock(DeleteMethod.class);
+ connector.setControllerAddress(null);
+ connector.executeDeleteObject("/");
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteDeleteObjectWithoutCredentials() throws CloudstackRESTException {
+ method = mock(DeleteMethod.class);
+ connector.setAdminCredentials(null, null);
+ connector.executeDeleteObject("/");
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteRetrieveObjectWithoutHostname() throws CloudstackRESTException {
+ method = mock(GetMethod.class);
+ connector.setControllerAddress(null);
+ connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteRetrieveObjectWithoutCredentials() throws CloudstackRESTException {
+ method = mock(GetMethod.class);
+ connector.setAdminCredentials(null, null);
+ connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
+ }
+
+ @Test
+ public void testExecuteMethod() throws CloudstackRESTException {
+ final GetMethod gm = mock(GetMethod.class);
+
+ when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ connector.executeMethod(gm);
+ verify(gm, times(1)).getStatusCode();
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException {
+ final GetMethod gm = mock(GetMethod.class);
+ when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
+ connector.executeMethod(gm);
+ verify(gm, times(1)).getStatusCode();
+ }
+
+ /* Bit of a roundabout way to ensure that login is called after an un authorized result
+ * It not possible to properly mock login()
+ */
+ public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException, HttpException, IOException {
+ // Prepare
+ final GetMethod gm = mock(GetMethod.class);
+ when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
+
+ final RESTValidationStrategy previousValidationStrategy = connector.validation;
+ connector.validation = new RESTValidationStrategy(){
+ @Override
+ protected void login(final String protocol, final HttpClient client)
+ throws CloudstackRESTException {
+ // Do nothing
+ }
+ };
+ connector.setAdminCredentials("admin", "adminpass");
+ connector.setControllerAddress("localhost");
+
+ // Execute
+ connector.executeMethod(gm);
+ // Leave mock object as is was
+ connector.validation = previousValidationStrategy;
+
+ // Assert/verify
+ verify(gm, times(2)).getStatusCode();
+ }
+
+ @Test
+ public void testExecuteCreateObject() throws CloudstackRESTException, IOException {
+ JsonEntity ls = new JsonEntity();
+ method = mock(PostMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
+ when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
+ ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
+ assertTrue(UUID.equals(ls.getUuid()));
+ verify(method, times(1)).releaseConnection();
+
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteCreateObjectFailure() throws CloudstackRESTException, IOException {
+ JsonEntity ls = new JsonEntity();
+ method = mock(PostMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ final Header header = mock(Header.class);
+ when(header.getValue()).thenReturn("text/html");
+ when(method.getResponseHeader("Content-Type")).thenReturn(header);
+ when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
+ when(method.isRequestSent()).thenReturn(true);
+ try {
+ ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteCreateObjectException() throws CloudstackRESTException, IOException {
+ JsonEntity ls = new JsonEntity();
+ when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ method = mock(PostMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ final Header header = mock(Header.class);
+ when(header.getValue()).thenReturn("text/html");
+ when(method.getResponseHeader("Content-Type")).thenReturn(header);
+ when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
+ try {
+ ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test
+ public void testExecuteUpdateObject() throws CloudstackRESTException, IOException {
+ final JsonEntity ls = new JsonEntity();
+ method = mock(PutMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
+ verify(method, times(1)).releaseConnection();
+ verify(client, times(1)).executeMethod(method);
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteUpdateObjectFailure() throws CloudstackRESTException, IOException {
+ final JsonEntity ls = new JsonEntity();
+ method = mock(PutMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ final Header header = mock(Header.class);
+ when(header.getValue()).thenReturn("text/html");
+ when(method.getResponseHeader("Content-Type")).thenReturn(header);
+ when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
+ when(method.isRequestSent()).thenReturn(true);
+ try {
+ connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteUpdateObjectException() throws CloudstackRESTException, IOException {
+ final JsonEntity ls = new JsonEntity();
+ method = mock(PutMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException());
+ try {
+ connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test
+ public void testExecuteDeleteObject() throws CloudstackRESTException, IOException {
+ method = mock(DeleteMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ connector.executeDeleteObject("/");
+ verify(method, times(1)).releaseConnection();
+ verify(client, times(1)).executeMethod(method);
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteDeleteObjectFailure() throws CloudstackRESTException, IOException {
+ method = mock(DeleteMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ final Header header = mock(Header.class);
+ when(header.getValue()).thenReturn("text/html");
+ when(method.getResponseHeader("Content-Type")).thenReturn(header);
+ when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
+ when(method.isRequestSent()).thenReturn(true);
+ try {
+ connector.executeDeleteObject("/");
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteDeleteObjectException() throws CloudstackRESTException, IOException {
+ method = mock(DeleteMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ try {
+ connector.executeDeleteObject("/");
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test
+ public void testExecuteRetrieveObject() throws CloudstackRESTException, IOException {
+ method = mock(GetMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
+ connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
+ verify(method, times(1)).releaseConnection();
+ verify(client, times(1)).executeMethod(method);
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteRetrieveObjectFailure() throws CloudstackRESTException, IOException {
+ method = mock(GetMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
+ final Header header = mock(Header.class);
+ when(header.getValue()).thenReturn("text/html");
+ when(method.getResponseHeader("Content-Type")).thenReturn(header);
+ when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
+ when(method.isRequestSent()).thenReturn(true);
+ try {
+ connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteRetrieveObjectException() throws CloudstackRESTException, IOException {
+ method = mock(GetMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
+ when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ try {
+ connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
+ } finally {
+ verify(method, times(1)).releaseConnection();
+ }
+ }
+
+}
+
+class JsonEntity {
+ private String displayName;
+ private String uuid;
+ private String href;
+ private String schema;
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public void setDisplayName(final String displayName) {
+ this.displayName = displayName;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(final String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getHref() {
+ return href;
+ }
+
+ public void setHref(final String href) {
+ this.href = href;
+ }
+
+ public String getSchema() {
+ return schema;
+ }
+
+ public void setSchema(final String schema) {
+ this.schema = schema;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java b/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java
new file mode 100644
index 0000000..a3daf91
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java
@@ -0,0 +1,73 @@
+//
+// 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 com.cloud.utils.ssh;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class SSHKeysHelperTest {
+ @Test
+ public void rsaKeyTest() {
+ String rsaKey =
+ "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW"
+ + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk"
+ + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P"
+ + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6"
+ + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX test@testkey";
+ String storedRsaKey =
+ "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW"
+ + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk"
+ + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P"
+ + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX";
+ String parsedKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(rsaKey);
+ String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(parsedKey);
+
+ assertTrue(storedRsaKey.equals(parsedKey));
+ assertTrue("f6:96:3f:f4:78:f7:80:11:6c:f8:e3:2b:40:20:f1:14".equals(fingerprint));
+
+ }
+
+ @Test
+ public void dsaKeyTest() {
+ String dssKey =
+ "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV"
+ + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO"
+ + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA"
+ + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF"
+ + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD"
+ + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR"
+ + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ== test key";
+ String storedDssKey =
+ "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV"
+ + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO"
+ + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA"
+ + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF"
+ + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD"
+ + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR"
+ + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ==";
+ String parsedKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(dssKey);
+ String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(parsedKey);
+
+ assertTrue(storedDssKey.equals(parsedKey));
+ assertTrue("fc:6e:ef:31:93:f8:92:2b:a9:03:c7:06:90:f5:ec:bb".equals(fingerprint));
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java b/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java
new file mode 100644
index 0000000..51cde2c
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.testcase;
+
+import java.io.File;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.Random;
+
+import junit.framework.TestCase;
+
+import org.apache.log4j.xml.DOMConfigurator;
+
+public class Log4jEnabledTestCase extends TestCase {
+ @Override
+ protected void setUp() {
+ URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
+ if (configUrl != null) {
+ System.out.println("Configure log4j using log4j-cloud.xml");
+
+ try {
+ File file = new File(configUrl.toURI());
+
+ System.out.println("Log4j configuration from : " + file.getAbsolutePath());
+ DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
+ } catch (URISyntaxException e) {
+ System.out.println("Unable to convert log4j configuration Url to URI");
+ }
+ } else {
+ System.out.println("Configure log4j with default properties");
+ }
+ }
+
+ public static int getRandomMilliseconds(int rangeLo, int rangeHi) {
+ int i = new Random().nextInt();
+
+ long pos = (long)i - (long)Integer.MIN_VALUE;
+ long iRange = (long)Integer.MAX_VALUE - (long)Integer.MIN_VALUE;
+ return rangeLo + (int)((rangeHi - rangeLo) * pos / iRange);
+ }
+}
[08/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Fix unit-test library dependencies
- XML formatting
- Fix license header
- Reorder hamcrest, junit, mockito and powermock dependencies
* Since several libraries include a subset of hamcrest classes,
hamcrest should be declared first in the pom, inorder for its
classes to be loaded first by the JVM
- Depdend on hamcrest-all and exclude hamcrest classes from other
libraries
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/3d27e9ed
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3d27e9ed
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3d27e9ed
Branch: refs/heads/deploy-from-snapshot
Commit: 3d27e9ed1206e0ff8cef5fa850e7b012427a56ef
Parents: 98dd771
Author: Miguel Ferreira <mi...@me.com>
Authored: Sun Aug 23 16:11:06 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 14:50:31 2015 +0200
----------------------------------------------------------------------
pom.xml | 165 ++++++++++++++++++++++++++++++++++-------------------------
1 file changed, 94 insertions(+), 71 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3d27e9ed/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index f5f4e61..95b90db 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,12 +1,23 @@
-<!-- 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. -->
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -32,7 +43,7 @@
<system>jira</system>
<url>https://issues.apache.org/jira/browse/CLOUDSTACK</url>
</issueManagement>
-
+
<prerequisites>
<maven>3.0.4</maven>
</prerequisites>
@@ -424,14 +435,8 @@
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${cs.junit.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-library</artifactId>
+ <artifactId>hamcrest-all</artifactId>
<version>${cs.hamcrest.version}</version>
<scope>test</scope>
</dependency>
@@ -440,17 +445,35 @@
<artifactId>mockito-all</artifactId>
<version>${cs.mockito.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>hamcrest-core</artifactId>
+ <groupId>org.hamcrest</groupId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <version>${cs.powermock.version}</version>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${cs.junit.version}</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>hamcrest-core</artifactId>
+ <groupId>org.hamcrest</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4</artifactId>
+ <version>${cs.powermock.version}</version>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <version>${cs.powermock.version}</version>
- <scope>test</scope>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito</artifactId>
+ <version>${cs.powermock.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@@ -485,13 +508,13 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>cloudstack-checkstyle</id>
- <phase>none</phase>
- <inherited>false</inherited>
- </execution>
- </executions>
+ <executions>
+ <execution>
+ <id>cloudstack-checkstyle</id>
+ <phase>none</phase>
+ <inherited>false</inherited>
+ </execution>
+ </executions>
</plugin>
<plugin>
<groupId>com.mycila</groupId>
@@ -570,9 +593,9 @@
<aggregate>true</aggregate>
<header>LICENSE.header</header>
<mapping>
- <xml>XML_STYLE</xml>
- � � <java>DOUBLESLASH_STYLE</java>
- � � <clj>SEMICOLON_STYLE</clj>
+ <xml>XML_STYLE</xml>
+ <java>DOUBLESLASH_STYLE</java>
+ <clj>SEMICOLON_STYLE</clj>
</mapping>
<useDefaultExcludes>false</useDefaultExcludes>
<excludes>
@@ -627,8 +650,8 @@
</execution>
</executions>
</plugin>
- <!--This plugin's configuration is used to store Eclipse m2e settings only.
- It has no influence on the Maven build itself. -->
+ <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build
+ itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
@@ -646,7 +669,7 @@
</goals>
</pluginExecutionFilter>
<action>
- <ignore />
+ <ignore/>
</action>
</pluginExecution>
<pluginExecution>
@@ -659,7 +682,7 @@
</goals>
</pluginExecutionFilter>
<action>
- <ignore />
+ <ignore/>
</action>
</pluginExecution>
<pluginExecution>
@@ -682,12 +705,12 @@
<artifactId>gmaven-plugin</artifactId>
<versionRange>[1.3,)</versionRange>
<goals>
- <goal>compile</goal>
- <goal>testCompile</goal>
+ <goal>compile</goal>
+ <goal>testCompile</goal>
</goals>
</pluginExecutionFilter>
<action>
- <ignore></ignore>
+ <ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
@@ -841,7 +864,7 @@
<exclude>tools/ngui/static/js/lib/*</exclude>
<exclude>**/.checkstyle</exclude>
<exclude>scripts/installer/windows/acs_license.rtf</exclude>
- <exclude>**/*.md</exclude>
+ <exclude>**/*.md</exclude>
</excludes>
</configuration>
</plugin>
@@ -943,9 +966,9 @@
</dependencies>
<configuration>
<failOnViolation>false</failOnViolation>
- <rulesets>
- <ruleset>cloud-pmd.xml</ruleset>
- </rulesets>
+ <rulesets>
+ <ruleset>cloud-pmd.xml</ruleset>
+ </rulesets>
</configuration>
<executions>
<execution>
@@ -986,18 +1009,18 @@
</configuration>
</plugin>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>${cs.javadoc.version}</version>
- <configuration>
- <minmemory>128m</minmemory>
- <maxmemory>1g</maxmemory>
- </configuration>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>${cs.javadoc.version}</version>
+ <configuration>
+ <minmemory>128m</minmemory>
+ <maxmemory>1g</maxmemory>
+ </configuration>
</plugin>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-project-info-reports-plugin</artifactId>
- <version>2.7</version>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-project-info-reports-plugin</artifactId>
+ <version>2.7</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
@@ -1072,17 +1095,17 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>cloudstack-checkstyle</id>
- <phase>none</phase>
- <inherited>true</inherited>
- </execution>
- </executions>
+ <executions>
+ <execution>
+ <id>cloudstack-checkstyle</id>
+ <phase>none</phase>
+ <inherited>true</inherited>
+ </execution>
+ </executions>
</plugin>
</plugins>
</build>
- </profile>
+ </profile>
<profile>
<id>enablefindbugs</id>
<build>
@@ -1090,17 +1113,17 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>cloudstack-findbugs</id>
- <phase>process-classes</phase>
- <inherited>true</inherited>
- </execution>
- </executions>
+ <executions>
+ <execution>
+ <id>cloudstack-findbugs</id>
+ <phase>process-classes</phase>
+ <inherited>true</inherited>
+ </execution>
+ </executions>
</plugin>
</plugins>
</build>
- </profile>
+ </profile>
<profile>
<id>buildw</id>
<activation>
[38/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java
deleted file mode 100644
index e23593c..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java
+++ /dev/null
@@ -1,138 +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 com.cloud.network.nicira;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-
-@SuppressWarnings("serial")
-public class SecurityRule extends AccessRule {
-
- protected String ipPrefix;
-
- protected int portRangeMin;
-
- protected int portRangeMax;
-
- protected String profileUuid;
-
-
- /**
- * Default constructor
- */
- public SecurityRule() {
- }
-
- /**
- * Fully parameterized constructor
- */
- public SecurityRule(final String ethertype, final String ipPrefix, final String profileUuid,
- final int portRangeMin, final int portRangeMax, final int protocol) {
- this.ethertype = ethertype;
- this.ipPrefix = ipPrefix;
- this.portRangeMin = portRangeMin;
- this.portRangeMax = portRangeMax;
- this.profileUuid = profileUuid;
- this.protocol = protocol;
- }
-
- @Override
- public String getEthertype() {
- return ethertype;
- }
-
- @Override
- public void setEthertype(final String ethertype) {
- this.ethertype = ethertype;
- }
-
- public String getIpPrefix() {
- return ipPrefix;
- }
-
- public void setIpPrefix(final String ipPrefix) {
- this.ipPrefix = ipPrefix;
- }
-
- public int getPortRangeMin() {
- return portRangeMin;
- }
-
- public void setPortRangeMin(final int portRangeMin) {
- this.portRangeMin = portRangeMin;
- }
-
- public int getPortRangeMax() {
- return portRangeMax;
- }
-
- public void setPortRangeMax(final int portRangeMax) {
- this.portRangeMax = portRangeMax;
- }
-
- public String getProfileUuid() {
- return profileUuid;
- }
-
- public void setProfileUuid(final String profileUuid) {
- this.profileUuid = profileUuid;
- }
-
- @Override
- public int getProtocol() {
- return protocol;
- }
-
- @Override
- public void setProtocol(final int protocol) {
- this.protocol = protocol;
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 31)
- .append(ethertype).append(ipPrefix)
- .append(portRangeMin).append(portRangeMax)
- .append(profileUuid).append(protocol)
- .toHashCode();
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (obj == null) {
- return false;
- }
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof SecurityRule)) {
- return false;
- }
- final SecurityRule another = (SecurityRule) obj;
- return new EqualsBuilder()
- .append(ethertype, another.ethertype)
- .append(ipPrefix, another.ipPrefix)
- .append(portRangeMin, another.portRangeMin)
- .append(portRangeMax, another.portRangeMax)
- .append(profileUuid, another.profileUuid)
- .append(protocol, another.protocol)
- .isEquals();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java
deleted file mode 100644
index ea5df2c..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java
+++ /dev/null
@@ -1,40 +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 com.cloud.network.nicira;
-
-/**
- *
- */
-public class SingleDefaultRouteImplicitRoutingConfig extends RoutingConfig {
- public RouterNextHop defaultRouteNextHop;
- public final String type = "SingleDefaultRouteImplicitRoutingConfig";
-
- public SingleDefaultRouteImplicitRoutingConfig(final RouterNextHop routerNextHop) {
- defaultRouteNextHop = routerNextHop;
- }
-
- public RouterNextHop getDefaultRouteNextHop() {
- return defaultRouteNextHop;
- }
-
- public void setDefaultRouteNextHop(final RouterNextHop defaultRouteNextHop) {
- this.defaultRouteNextHop = defaultRouteNextHop;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java
deleted file mode 100644
index b95cb9a..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java
+++ /dev/null
@@ -1,119 +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 com.cloud.network.nicira;
-
-public class SourceNatRule extends NatRule {
- private String toSourceIpAddressMax;
- private String toSourceIpAddressMin;
- private Integer toSourcePort;
-
- public SourceNatRule() {
- setType("SourceNatRule");
- }
-
- public String getToSourceIpAddressMax() {
- return toSourceIpAddressMax;
- }
-
- public void setToSourceIpAddressMax(final String toSourceIpAddressMax) {
- this.toSourceIpAddressMax = toSourceIpAddressMax;
- }
-
- public String getToSourceIpAddressMin() {
- return toSourceIpAddressMin;
- }
-
- public void setToSourceIpAddressMin(final String toSourceIpAddressMin) {
- this.toSourceIpAddressMin = toSourceIpAddressMin;
- }
-
- public Integer getToSourcePort() {
- return toSourcePort;
- }
-
- public void setToSourcePort(final Integer toSourcePort) {
- this.toSourcePort = toSourcePort;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((toSourceIpAddressMax == null) ? 0 : toSourceIpAddressMax.hashCode());
- result = prime * result + ((toSourceIpAddressMin == null) ? 0 : toSourceIpAddressMin.hashCode());
- result = prime * result + ((toSourcePort == null) ? 0 : toSourcePort.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
- SourceNatRule other = (SourceNatRule)obj;
- if (toSourceIpAddressMax == null) {
- if (other.toSourceIpAddressMax != null)
- return false;
- } else if (!toSourceIpAddressMax.equals(other.toSourceIpAddressMax))
- return false;
- if (toSourceIpAddressMin == null) {
- if (other.toSourceIpAddressMin != null)
- return false;
- } else if (!toSourceIpAddressMin.equals(other.toSourceIpAddressMin))
- return false;
- if (toSourcePort == null) {
- if (other.toSourcePort != null)
- return false;
- } else if (!toSourcePort.equals(other.toSourcePort))
- return false;
- return true;
- }
-
- @Override
- public boolean equalsIgnoreUuid(final Object obj) {
- if (this == obj)
- return true;
- if (!super.equalsIgnoreUuid(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
- SourceNatRule other = (SourceNatRule)obj;
- if (toSourceIpAddressMax == null) {
- if (other.toSourceIpAddressMax != null)
- return false;
- } else if (!toSourceIpAddressMax.equals(other.toSourceIpAddressMax))
- return false;
- if (toSourceIpAddressMin == null) {
- if (other.toSourceIpAddressMin != null)
- return false;
- } else if (!toSourceIpAddressMin.equals(other.toSourceIpAddressMin))
- return false;
- if (toSourcePort == null) {
- if (other.toSourcePort != null)
- return false;
- } else if (!toSourcePort.equals(other.toSourcePort))
- return false;
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java
deleted file mode 100644
index c643876..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java
+++ /dev/null
@@ -1,50 +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 com.cloud.network.nicira;
-
-public class TransportZoneBinding {
- private String zoneUuid;
- private String transportType;
-
- public TransportZoneBinding() {
- }
-
- public TransportZoneBinding(String zoneUuid, String transportType) {
- this.zoneUuid = zoneUuid;
- this.transportType = transportType;
- }
-
- public String getZoneUuid() {
- return zoneUuid;
- }
-
- public void setZoneUuid(String zoneUuid) {
- this.zoneUuid = zoneUuid;
- }
-
- public String getTransportType() {
- return transportType;
- }
-
- public void setTransportType(String transportType) {
- this.transportType = transportType;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java
deleted file mode 100644
index fe7d93a..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java
+++ /dev/null
@@ -1,78 +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 com.cloud.network.nicira;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-public class VifAttachment extends Attachment {
- private final String type = "VifAttachment";
- private String vifUuid;
-
- public VifAttachment() {
- }
-
- public VifAttachment(final String vifUuid) {
- this.vifUuid = vifUuid;
- }
-
- public String getVifUuid() {
- return vifUuid;
- }
-
- public void setVifUuid(final String vifUuid) {
- this.vifUuid = vifUuid;
- }
-
- public String getType() {
- return type;
- }
-
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 31)
- .append(this.getClass())
- .append(vifUuid)
- .toHashCode();
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (obj == null) {
- return false;
- }
- if (obj == this) {
- return true;
- }
- if (!(this.getClass().isInstance(obj))) {
- return false;
- }
- final VifAttachment another = (VifAttachment) obj;
- return new EqualsBuilder().append(vifUuid, another.vifUuid).isEquals();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
deleted file mode 100644
index 9d261b2..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
+++ /dev/null
@@ -1,77 +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 com.cloud.network.resource;
-
-import java.util.Hashtable;
-import java.util.Set;
-
-import org.reflections.Reflections;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.Command;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.RequestWrapper;
-import com.cloud.resource.ServerResource;
-
-public class NiciraNvpRequestWrapper extends RequestWrapper {
-
- private static NiciraNvpRequestWrapper instance;
-
- static {
- instance = new NiciraNvpRequestWrapper();
- }
-
- Reflections baseWrappers = new Reflections("com.cloud.network.resource.wrapper");
- @SuppressWarnings("rawtypes")
- Set<Class<? extends CommandWrapper>> baseSet = baseWrappers.getSubTypesOf(CommandWrapper.class);
-
- private NiciraNvpRequestWrapper() {
- init();
- }
-
- @SuppressWarnings("rawtypes")
- private void init() {
- // NiciraNvpResource commands
- final Hashtable<Class<? extends Command>, CommandWrapper> niciraCommands = processAnnotations(baseSet);
-
- resources.put(NiciraNvpResource.class, niciraCommands);
- }
-
- public static NiciraNvpRequestWrapper getInstance() {
- return instance;
- }
-
- @SuppressWarnings({"rawtypes" })
- @Override
- public Answer execute(final Command command, final ServerResource serverResource) {
- final Class<? extends ServerResource> resourceClass = serverResource.getClass();
-
- final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands = retrieveResource(command, resourceClass);
-
- CommandWrapper<Command, Answer, ServerResource> commandWrapper = retrieveCommands(command.getClass(), resourceCommands);
-
- while (commandWrapper == null) {
- //Could not find the command in the given resource, will traverse the family tree.
- commandWrapper = retryWhenAllFails(command, resourceClass, resourceCommands);
- }
-
- return commandWrapper.execute(command, serverResource);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
deleted file mode 100644
index df40db4..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ /dev/null
@@ -1,319 +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 com.cloud.network.resource;
-
-import java.util.Map;
-
-import javax.naming.ConfigurationException;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.IAgentControl;
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.Command;
-import com.cloud.agent.api.PingCommand;
-import com.cloud.agent.api.StartupCommand;
-import com.cloud.agent.api.StartupNiciraNvpCommand;
-import com.cloud.host.Host;
-import com.cloud.host.Host.Type;
-import com.cloud.network.nicira.ControlClusterStatus;
-import com.cloud.network.nicira.DestinationNatRule;
-import com.cloud.network.nicira.Match;
-import com.cloud.network.nicira.NatRule;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.SourceNatRule;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.ServerResource;
-
-public class NiciraNvpResource implements ServerResource {
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
-
- public static final int NAME_MAX_LEN = 40;
- public static final int NUM_RETRIES = 2;
-
- private String name;
- private String guid;
- private String zoneId;
-
- private NiciraNvpApi niciraNvpApi;
- private NiciraNvpUtilities niciraNvpUtilities;
- private CommandRetryUtility retryUtility;
-
- protected NiciraNvpApi createNiciraNvpApi() {
- return new NiciraNvpApi();
- }
-
- @Override
- public boolean configure(final String ignoredName, final Map<String, Object> params) throws ConfigurationException {
-
- name = (String)params.get("name");
- if (name == null) {
- throw new ConfigurationException("Unable to find name");
- }
-
- guid = (String)params.get("guid");
- if (guid == null) {
- throw new ConfigurationException("Unable to find the guid");
- }
-
- zoneId = (String)params.get("zoneId");
- if (zoneId == null) {
- throw new ConfigurationException("Unable to find zone");
- }
-
- final String ip = (String)params.get("ip");
- if (ip == null) {
- throw new ConfigurationException("Unable to find IP");
- }
-
- final String adminuser = (String)params.get("adminuser");
- if (adminuser == null) {
- throw new ConfigurationException("Unable to find admin username");
- }
-
- final String adminpass = (String)params.get("adminpass");
- if (adminpass == null) {
- throw new ConfigurationException("Unable to find admin password");
- }
-
- niciraNvpUtilities = NiciraNvpUtilities.getInstance();
- retryUtility = CommandRetryUtility.getInstance();
- retryUtility.setServerResource(this);
-
- niciraNvpApi = createNiciraNvpApi();
- niciraNvpApi.setControllerAddress(ip);
- niciraNvpApi.setAdminCredentials(adminuser, adminpass);
-
- return true;
- }
-
- public NiciraNvpApi getNiciraNvpApi() {
- return niciraNvpApi;
- }
-
- public NiciraNvpUtilities getNiciraNvpUtilities() {
- return niciraNvpUtilities;
- }
-
- public CommandRetryUtility getRetryUtility() {
- return retryUtility;
- }
-
- @Override
- public boolean start() {
- return true;
- }
-
- @Override
- public boolean stop() {
- return true;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public Type getType() {
- // Think up a better name for this Type?
- return Host.Type.L2Networking;
- }
-
- @Override
- public StartupCommand[] initialize() {
- final StartupNiciraNvpCommand sc = new StartupNiciraNvpCommand();
- sc.setGuid(guid);
- sc.setName(name);
- sc.setDataCenter(zoneId);
- sc.setPod("");
- sc.setPrivateIpAddress("");
- sc.setStorageIpAddress("");
- sc.setVersion(NiciraNvpResource.class.getPackage().getImplementationVersion());
- return new StartupCommand[] {sc};
- }
-
- @Override
- public PingCommand getCurrentStatus(final long id) {
- try {
- final ControlClusterStatus ccs = niciraNvpApi.getControlClusterStatus();
- if (!"stable".equals(ccs.getClusterStatus())) {
- s_logger.error("ControlCluster state is not stable: " + ccs.getClusterStatus());
- return null;
- }
- } catch (final NiciraNvpApiException e) {
- s_logger.error("getControlClusterStatus failed", e);
- return null;
- }
- return new PingCommand(Host.Type.L2Networking, id);
- }
-
- @Override
- public Answer executeRequest(final Command cmd) {
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- try {
- return wrapper.execute(cmd, this);
- } catch (final Exception e) {
- s_logger.debug("Received unsupported command " + cmd.toString());
- return Answer.createUnsupportedCommandAnswer(cmd);
- }
- }
-
- @Override
- public void disconnected() {
- }
-
- @Override
- public IAgentControl getAgentControl() {
- return null;
- }
-
- @Override
- public void setAgentControl(final IAgentControl agentControl) {
- }
-
- public String natRuleToString(final NatRule rule) {
-
- final StringBuilder natRuleStr = new StringBuilder();
- natRuleStr.append("Rule ");
- natRuleStr.append(rule.getUuid());
- natRuleStr.append(" (");
- natRuleStr.append(rule.getType());
- natRuleStr.append(") :");
- final Match m = rule.getMatch();
- natRuleStr.append("match (");
- natRuleStr.append(m.getProtocol());
- natRuleStr.append(" ");
- natRuleStr.append(m.getSourceIpAddresses());
- natRuleStr.append(" [");
- natRuleStr.append(m.getSourcePort());
- natRuleStr.append(" ] -> ");
- natRuleStr.append(m.getDestinationIpAddresses());
- natRuleStr.append(" [");
- natRuleStr.append(m.getDestinationPort());
- natRuleStr.append(" ]) -->");
- if ("SourceNatRule".equals(rule.getType())) {
- natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMin());
- natRuleStr.append("-");
- natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMax());
- natRuleStr.append(" [");
- natRuleStr.append(((SourceNatRule)rule).getToSourcePort());
- natRuleStr.append(" ])");
- } else {
- natRuleStr.append(((DestinationNatRule)rule).getToDestinationIpAddress());
- natRuleStr.append(" [");
- natRuleStr.append(((DestinationNatRule)rule).getToDestinationPort());
- natRuleStr.append(" ])");
- }
- return natRuleStr.toString();
- }
-
- public String truncate(final String string, final int length) {
- if (string.length() <= length) {
- return string;
- } else {
- return string.substring(0, length);
- }
- }
-
- public NatRule[] generateStaticNatRulePair(final String insideIp, final String outsideIp) {
- final NatRule[] rulepair = new NatRule[2];
- rulepair[0] = new DestinationNatRule();
- rulepair[0].setType("DestinationNatRule");
- rulepair[0].setOrder(100);
- rulepair[1] = new SourceNatRule();
- rulepair[1].setType("SourceNatRule");
- rulepair[1].setOrder(100);
-
- Match m = new Match();
- m.setDestinationIpAddresses(outsideIp);
- rulepair[0].setMatch(m);
- ((DestinationNatRule)rulepair[0]).setToDestinationIpAddress(insideIp);
-
- // create matching snat rule
- m = new Match();
- m.setSourceIpAddresses(insideIp);
- rulepair[1].setMatch(m);
- ((SourceNatRule)rulepair[1]).setToSourceIpAddressMin(outsideIp);
- ((SourceNatRule)rulepair[1]).setToSourceIpAddressMax(outsideIp);
-
- return rulepair;
-
- }
-
- public NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts,
- final String protocol) {
- // Start with a basic static nat rule, then add port and protocol details
- final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp);
-
- ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]);
- rulepair[0].getMatch().setDestinationPort(outsidePorts[0]);
- rulepair[0].setOrder(50);
- rulepair[0].getMatch().setEthertype("IPv4");
- if ("tcp".equals(protocol)) {
- rulepair[0].getMatch().setProtocol(6);
- } else if ("udp".equals(protocol)) {
- rulepair[0].getMatch().setProtocol(17);
- }
-
- ((SourceNatRule)rulepair[1]).setToSourcePort(outsidePorts[0]);
- rulepair[1].getMatch().setSourcePort(insidePorts[0]);
- rulepair[1].setOrder(50);
- rulepair[1].getMatch().setEthertype("IPv4");
- if ("tcp".equals(protocol)) {
- rulepair[1].getMatch().setProtocol(6);
- } else if ("udp".equals(protocol)) {
- rulepair[1].getMatch().setProtocol(17);
- }
-
- return rulepair;
-
- }
-
- @Override
- public void setName(final String name) {
- // TODO Auto-generated method stub
- }
-
- @Override
- public void setConfigParams(final Map<String, Object> params) {
- // TODO Auto-generated method stub
- }
-
- @Override
- public Map<String, Object> getConfigParams() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int getRunLevel() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public void setRunLevel(final int level) {
- // TODO Auto-generated method stub
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
deleted file mode 100644
index 4edf5c3..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
+++ /dev/null
@@ -1,65 +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 com.cloud.network.resource;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
-import com.cloud.network.nicira.LogicalSwitch;
-import com.cloud.network.nicira.LogicalSwitchPort;
-import com.cloud.network.nicira.NiciraNvpTag;
-import com.cloud.network.nicira.VifAttachment;
-
-public class NiciraNvpUtilities {
-
- private static NiciraNvpUtilities instance;
-
- static {
- instance = new NiciraNvpUtilities();
- }
-
- private NiciraNvpUtilities() {
- }
-
- public static NiciraNvpUtilities getInstance() {
- return instance;
- }
-
- public LogicalSwitch createLogicalSwitch() {
- final LogicalSwitch logicalSwitch = new LogicalSwitch();
- return logicalSwitch;
- }
-
- public LogicalSwitchPort createLogicalSwitchPort(final CreateLogicalSwitchPortCommand command) {
- final String attachmentUuid = command.getAttachmentUuid();
-
- // Tags set to scope cs_account and account name
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
-
- final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
- return logicalSwitchPort;
- }
-
- public VifAttachment createVifAttachment(final String attachmentUuid) {
- return new VifAttachment(attachmentUuid);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
deleted file mode 100644
index 89e7a6e..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
+++ /dev/null
@@ -1,120 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.to.PortForwardingRuleTO;
-import com.cloud.network.nicira.NatRule;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class)
-public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends CommandWrapper<ConfigurePortForwardingRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigurePortForwardingRulesCommandWrapper.class);
-
- @Override
- public Answer execute(final ConfigurePortForwardingRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
- try {
- final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
- // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
- // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
- // Any other SourceNat rule should have a corresponding DestinationNat rule
-
- for (final PortForwardingRuleTO rule : command.getRules()) {
- if (rule.isAlreadyAdded() && !rule.revoked()) {
- // Don't need to do anything
- continue;
- }
-
- if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1]) {
- return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, false, "Nicira NVP doesn't support port ranges for port forwarding");
- }
-
- final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
-
- NatRule incoming = null;
- NatRule outgoing = null;
-
- for (final NatRule storedRule : existingRules.getResults()) {
- if (storedRule.equalsIgnoreUuid(rulepair[1])) {
- // The outgoing rule exists
- outgoing = storedRule;
- s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
- if (incoming != null) {
- break;
- }
- } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
- // The incoming rule exists
- incoming = storedRule;
- s_logger.debug("Found matching incoming rule " + incoming.getUuid());
- if (outgoing != null) {
- break;
- }
- }
- }
- if (incoming != null && outgoing != null) {
- if (rule.revoked()) {
- s_logger.debug("Deleting incoming rule " + incoming.getUuid());
- niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid());
-
- s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
- niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid());
- }
- } else {
- if (rule.revoked()) {
- s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
- break;
- }
-
- rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]);
- s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0]));
-
- try {
- rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]);
- s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1]));
- } catch (final NiciraNvpApiException ex) {
- s_logger.warn("NiciraNvpApiException during create call, rolling back previous create");
- niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid());
- throw ex; // Rethrow the original exception
- }
-
- }
- }
- return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " PortForwarding rules applied");
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, ConfigurePortForwardingRulesOnLogicalRouterAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
deleted file mode 100644
index e5d2dcd..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
+++ /dev/null
@@ -1,60 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
-import com.cloud.network.nicira.LogicalRouterPort;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class)
-public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrapper<ConfigurePublicIpsOnLogicalRouterCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final ConfigurePublicIpsOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid());
- if (ports.getResultCount() != 1) {
- return new ConfigurePublicIpsOnLogicalRouterAnswer(command, false, "No logical router ports found, unable to set ip addresses");
- }
- final LogicalRouterPort lrp = ports.getResults().get(0);
- lrp.setIpAddresses(command.getPublicCidrs());
- niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp);
-
- return new ConfigurePublicIpsOnLogicalRouterAnswer(command, true, "Configured " + command.getPublicCidrs().size() + " ip addresses on logical router uuid " +
- command.getLogicalRouterUuid());
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, ConfigurePublicIpsOnLogicalRouterAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
deleted file mode 100644
index 1ce3ceb..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
+++ /dev/null
@@ -1,113 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.to.StaticNatRuleTO;
-import com.cloud.network.nicira.NatRule;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class)
-public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends CommandWrapper<ConfigureStaticNatRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigureStaticNatRulesCommandWrapper.class);
-
- @Override
- public Answer execute(final ConfigureStaticNatRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
- // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
- // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
- // Any other SourceNat rule should have a corresponding DestinationNat rule
-
- for (final StaticNatRuleTO rule : command.getRules()) {
-
- final NatRule[] rulepair = niciraNvpResource.generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp());
-
- NatRule incoming = null;
- NatRule outgoing = null;
-
- for (final NatRule storedRule : existingRules.getResults()) {
- if (storedRule.equalsIgnoreUuid(rulepair[1])) {
- // The outgoing rule exists
- outgoing = storedRule;
- s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
- if (incoming != null) {
- break;
- }
- } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
- // The incoming rule exists
- incoming = storedRule;
- s_logger.debug("Found matching incoming rule " + incoming.getUuid());
- if (outgoing != null) {
- break;
- }
- }
- }
- if (incoming != null && outgoing != null) {
- if (rule.revoked()) {
- s_logger.debug("Deleting incoming rule " + incoming.getUuid());
- niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid());
-
- s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
- niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid());
- }
- } else {
- if (rule.revoked()) {
- s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
- break;
- }
-
- rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]);
- s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0]));
-
- try {
- rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]);
- s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1]));
- } catch (final NiciraNvpApiException ex) {
- s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule");
- niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid());
- throw ex; // Rethrow original exception
- }
-
- }
- }
- return new ConfigureStaticNatRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " StaticNat rules applied");
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, ConfigureStaticNatRulesOnLogicalRouterAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
deleted file mode 100644
index 1cddf4f..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
+++ /dev/null
@@ -1,152 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NAME_MAX_LEN;
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.CreateLogicalRouterAnswer;
-import com.cloud.agent.api.CreateLogicalRouterCommand;
-import com.cloud.network.nicira.L3GatewayAttachment;
-import com.cloud.network.nicira.LogicalRouter;
-import com.cloud.network.nicira.LogicalRouterPort;
-import com.cloud.network.nicira.LogicalSwitchPort;
-import com.cloud.network.nicira.Match;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpTag;
-import com.cloud.network.nicira.PatchAttachment;
-import com.cloud.network.nicira.RouterNextHop;
-import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
-import com.cloud.network.nicira.SourceNatRule;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = CreateLogicalRouterCommand.class)
-public final class NiciraNvpCreateLogicalRouterCommandWrapper extends CommandWrapper<CreateLogicalRouterCommand, Answer, NiciraNvpResource> {
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpCreateLogicalRouterCommandWrapper.class);
-
- @Override
- public Answer execute(final CreateLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
- final String routerName = command.getName();
- final String gatewayServiceUuid = command.getGatewayServiceUuid();
- final String logicalSwitchUuid = command.getLogicalSwitchUuid();
-
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
-
- final String publicNetworkNextHopIp = command.getPublicNextHop();
- final String publicNetworkIpAddress = command.getPublicIpCidr();
- final String internalNetworkAddress = command.getInternalIpCidr();
-
- s_logger.debug("Creating a logical router with external ip " + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + "on gateway service " +
- gatewayServiceUuid);
-
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- // Create the Router
- LogicalRouter lrc = new LogicalRouter();
- lrc.setDisplayName(niciraNvpResource.truncate(routerName, NAME_MAX_LEN));
- lrc.setTags(tags);
- lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp)));
- lrc = niciraNvpApi.createLogicalRouter(lrc);
-
- // store the switchport for rollback
- LogicalSwitchPort lsp = null;
-
- try {
- // Create the outside port for the router
- LogicalRouterPort lrpo = new LogicalRouterPort();
- lrpo.setAdminStatusEnabled(true);
- lrpo.setDisplayName(niciraNvpResource.truncate(routerName + "-outside-port", NAME_MAX_LEN));
- lrpo.setTags(tags);
- final List<String> outsideIpAddresses = new ArrayList<String>();
- outsideIpAddresses.add(publicNetworkIpAddress);
- lrpo.setIpAddresses(outsideIpAddresses);
- lrpo = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpo);
-
- // Attach the outside port to the gateway service on the correct VLAN
- final L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid);
- if (command.getVlanId() != 0) {
- attachment.setVlanId(command.getVlanId());
- }
- niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment);
-
- // Create the inside port for the router
- LogicalRouterPort lrpi = new LogicalRouterPort();
- lrpi.setAdminStatusEnabled(true);
- lrpi.setDisplayName(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN));
- lrpi.setTags(tags);
- final List<String> insideIpAddresses = new ArrayList<String>();
- insideIpAddresses.add(internalNetworkAddress);
- lrpi.setIpAddresses(insideIpAddresses);
- lrpi = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpi);
-
- // Create the inside port on the lswitch
- lsp = new LogicalSwitchPort(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN), tags, true);
- lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp);
-
- // Attach the inside router port to the lswitch port with a PatchAttachment
- niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid()));
-
- // Attach the inside lswitch port to the router with a PatchAttachment
- niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid()));
-
- // Setup the source nat rule
- final SourceNatRule snr = new SourceNatRule();
- snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]);
- snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]);
- final Match match = new Match();
- match.setSourceIpAddresses(internalNetworkAddress);
- snr.setMatch(match);
- snr.setOrder(200);
- niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr);
- } catch (final NiciraNvpApiException e) {
- // We need to destroy the router if we already created it
- // this will also take care of any router ports and rules
- try {
- niciraNvpApi.deleteLogicalRouter(lrc.getUuid());
- if (lsp != null) {
- niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid());
- }
- } catch (final NiciraNvpApiException ex) {
- }
-
- throw e;
- }
-
- return new CreateLogicalRouterAnswer(command, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid());
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, CreateLogicalRouterAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
deleted file mode 100644
index 7d66ada..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
+++ /dev/null
@@ -1,73 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.CreateLogicalSwitchAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchCommand;
-import com.cloud.network.nicira.LogicalSwitch;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpTag;
-import com.cloud.network.nicira.TransportZoneBinding;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.resource.NiciraNvpUtilities;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = CreateLogicalSwitchCommand.class)
-public final class NiciraNvpCreateLogicalSwitchCommandWrapper extends CommandWrapper<CreateLogicalSwitchCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final CreateLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
-
- LogicalSwitch logicalSwitch = niciraNvpUtilities.createLogicalSwitch();
- logicalSwitch.setDisplayName(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN));
- logicalSwitch.setPortIsolationEnabled(false);
-
- // Set transport binding
- final List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
- ltzb.add(new TransportZoneBinding(command.getTransportUuid(), command.getTransportType()));
- logicalSwitch.setTransportZones(ltzb);
-
- // Tags set to scope cs_account and account name
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
- logicalSwitch.setTags(tags);
-
- try {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
- logicalSwitch = niciraNvpApi.createLogicalSwitch(logicalSwitch);
- final String switchUuid = logicalSwitch.getUuid();
- return new CreateLogicalSwitchAnswer(command, true, "Logicalswitch " + switchUuid + " created", switchUuid);
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, CreateLogicalSwitchAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
deleted file mode 100644
index 42a4067..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
+++ /dev/null
@@ -1,70 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
-import com.cloud.network.nicira.LogicalSwitchPort;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.VifAttachment;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.resource.NiciraNvpUtilities;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = CreateLogicalSwitchPortCommand.class)
-public final class NiciraNvpCreateLogicalSwitchPortCommandWrapper extends CommandWrapper<CreateLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpCreateLogicalSwitchPortCommandWrapper.class);
-
- @Override
- public Answer execute(final CreateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
-
- final String logicalSwitchUuid = command.getLogicalSwitchUuid();
- final String attachmentUuid = command.getAttachmentUuid();
-
- try {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- final LogicalSwitchPort logicalSwitchPort = niciraNvpUtilities.createLogicalSwitchPort(command);
- final LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
- try {
- niciraNvpApi.updateLogicalSwitchPortAttachment(command.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
- } catch (final NiciraNvpApiException ex) {
- s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport");
- niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), newPort.getUuid());
- throw ex; // Rethrow the original exception
- }
- return new CreateLogicalSwitchPortAnswer(command, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, CreateLogicalSwitchPortAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
deleted file mode 100644
index 43665b2..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
+++ /dev/null
@@ -1,50 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.DeleteLogicalRouterAnswer;
-import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = DeleteLogicalRouterCommand.class)
-public final class NiciraNvpDeleteLogicalRouterCommandWrapper extends CommandWrapper<DeleteLogicalRouterCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final DeleteLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- niciraNvpApi.deleteLogicalRouter(command.getLogicalRouterUuid());
- return new DeleteLogicalRouterAnswer(command, true, "Logical Router deleted (uuid " + command.getLogicalRouterUuid() + ")");
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, DeleteLogicalRouterAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
deleted file mode 100644
index f7b8ab9..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
+++ /dev/null
@@ -1,49 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchCommand;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = DeleteLogicalSwitchCommand.class)
-public final class NiciraNvpDeleteLogicalSwitchCommandWrapper extends CommandWrapper<DeleteLogicalSwitchCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final DeleteLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) {
- try {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
- niciraNvpApi.deleteLogicalSwitch(command.getLogicalSwitchUuid());
- return new DeleteLogicalSwitchAnswer(command, true, "Logicalswitch " + command.getLogicalSwitchUuid() + " deleted");
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, DeleteLogicalSwitchAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
deleted file mode 100644
index b8c69f2..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
+++ /dev/null
@@ -1,50 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = DeleteLogicalSwitchPortCommand.class)
-public final class NiciraNvpDeleteLogicalSwitchPortCommandWrapper extends CommandWrapper<DeleteLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final DeleteLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid());
- return new DeleteLogicalSwitchPortAnswer(command, true, "Logical switch port " + command.getLogicalSwitchPortUuid() + " deleted");
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, DeleteLogicalSwitchPortAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
deleted file mode 100644
index 40d58fc..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
+++ /dev/null
@@ -1,59 +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 com.cloud.network.resource.wrapper;
-
-import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
-import com.cloud.agent.api.FindLogicalSwitchPortCommand;
-import com.cloud.network.nicira.LogicalSwitchPort;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.utils.CommandRetryUtility;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class)
-public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandWrapper<FindLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final FindLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
- final String logicalSwitchUuid = command.getLogicalSwitchUuid();
- final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
-
- final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
-
- try {
- final NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
- if (ports.getResultCount() == 0) {
- return new FindLogicalSwitchPortAnswer(command, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null);
- } else {
- return new FindLogicalSwitchPortAnswer(command, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
- }
- } catch (final NiciraNvpApiException e) {
- final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
- retryUtility.addRetry(command, NUM_RETRIES);
- return retryUtility.retry(command, FindLogicalSwitchPortAnswer.class, e);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
deleted file mode 100644
index 3015378..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
+++ /dev/null
@@ -1,36 +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 com.cloud.network.resource.wrapper;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.MaintainAnswer;
-import com.cloud.agent.api.MaintainCommand;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = MaintainCommand.class)
-public final class NiciraNvpMaintainCommandWrapper extends CommandWrapper<MaintainCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final MaintainCommand command, final NiciraNvpResource niciraNvpResource) {
- return new MaintainAnswer(command);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
deleted file mode 100644
index 3d0d3f3..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
+++ /dev/null
@@ -1,36 +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 com.cloud.network.resource.wrapper;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.ReadyAnswer;
-import com.cloud.agent.api.ReadyCommand;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.resource.CommandWrapper;
-import com.cloud.resource.ResourceWrapper;
-
-@ResourceWrapper(handles = ReadyCommand.class)
-public final class NiciraNvpReadyCommandWrapper extends CommandWrapper<ReadyCommand, Answer, NiciraNvpResource> {
-
- @Override
- public Answer execute(final ReadyCommand command, final NiciraNvpResource niciraNvpResource) {
- return new ReadyAnswer(command);
- }
-}
\ No newline at end of file
[46/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Add NSX specific RestClient implementation
- Add -noverify JVM arg to surefire plugin, to allow Powermockito to
de-encapsulate private methods
- Add dependency on cloud-utils test-jar to use custom HttpRequest
matchers
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/18e6b9ba
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/18e6b9ba
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/18e6b9ba
Branch: refs/heads/deploy-from-snapshot
Commit: 18e6b9ba78600fd01456d18c1f2b4c5333714dd9
Parents: de63b94
Author: Miguel Ferreira <mi...@me.com>
Authored: Sat Aug 22 17:05:30 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:15 2015 +0200
----------------------------------------------------------------------
plugins/network-elements/nicira-nvp/pom.xml | 10 +
.../cloud/network/nicira/ExecutionCounter.java | 50 +++++
.../cloud/network/nicira/NiciraRestClient.java | 202 +++++++++++++++++++
.../network/nicira/ExecutionCounterTest.java | 55 +++++
.../network/nicira/NiciraRestClientTest.java | 172 ++++++++++++++++
pom.xml | 2 +-
.../cloud/utils/rest/HttpStatusCodeHelper.java | 34 ++++
.../utils/rest/HttpStatusCodeHelperTest.java | 59 ++++++
8 files changed, 583 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/plugins/network-elements/nicira-nvp/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml
index 2d20ae2..e74a5ae 100644
--- a/plugins/network-elements/nicira-nvp/pom.xml
+++ b/plugins/network-elements/nicira-nvp/pom.xml
@@ -30,6 +30,16 @@
<relativePath>../../pom.xml</relativePath>
</parent>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.cloudstack</groupId>
+ <artifactId>cloud-utils</artifactId>
+ <version>4.6.0-SNAPSHOT</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java
new file mode 100644
index 0000000..1314498
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java
@@ -0,0 +1,50 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class ExecutionCounter {
+
+ private final int executionLimit;
+ private final AtomicInteger executionCount = new AtomicInteger(0);
+
+ public ExecutionCounter(final int executionLimit) {
+ this.executionLimit = executionLimit;
+ }
+
+ public ExecutionCounter resetExecutionCounter() {
+ executionCount.set(0);
+ return this;
+ }
+
+ public boolean hasReachedExecutionLimit() {
+ return executionCount.get() >= executionLimit;
+ }
+
+ public ExecutionCounter incrementExecutionCounter() {
+ executionCount.incrementAndGet();
+ return this;
+ }
+
+ public int getValue() {
+ return executionCount.get();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java
new file mode 100644
index 0000000..6ade3a5
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java
@@ -0,0 +1,202 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.rest.BasicRestClient;
+import com.cloud.utils.rest.CloudstackRESTException;
+import com.cloud.utils.rest.HttpConstants;
+import com.cloud.utils.rest.HttpMethods;
+import com.cloud.utils.rest.HttpStatusCodeHelper;
+import com.cloud.utils.rest.HttpUriRequestBuilder;
+
+public class NiciraRestClient extends BasicRestClient {
+
+ private static final Logger s_logger = Logger.getLogger(NiciraRestClient.class);
+
+ private static final String CONTENT_TYPE = HttpConstants.CONTENT_TYPE;
+ private static final String TEXT_HTML_CONTENT_TYPE = HttpConstants.TEXT_HTML_CONTENT_TYPE;
+
+ private static final int DEFAULT_BODY_RESP_MAX_LEN = 1024;
+ private static final int DEFAULT_EXECUTION_LIMIT = 5;
+
+ private final ExecutionCounter counter;
+ private final int maxResponseErrorMesageLength;
+ private final int executionLimit;
+
+ private final String username;
+ private final String password;
+ private final String loginUrl;
+
+ private NiciraRestClient(final Builder builder) {
+ super(builder.client, builder.clientContext, builder.hostname);
+ executionLimit = builder.executionLimit;
+ counter = new ExecutionCounter(executionLimit);
+ maxResponseErrorMesageLength = builder.maxResponseErrorMesageLength;
+ username = builder.username;
+ password = builder.password;
+ loginUrl = builder.loginUrl;
+ }
+
+ public static Builder create() {
+ return new Builder();
+ }
+
+ @Override
+ public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException {
+ return execute(request, 0);
+ }
+
+ private CloseableHttpResponse execute(final HttpUriRequest request, final int previousStatusCode) throws CloudstackRESTException {
+ if (counter.hasReachedExecutionLimit()) {
+ throw new CloudstackRESTException("Reached max executions limit of " + executionLimit);
+ }
+ counter.incrementExecutionCounter();
+ s_logger.debug("Executing " + request.getMethod() + " request [execution count = " + counter.getValue() + "]");
+ final CloseableHttpResponse response = super.execute(request);
+
+ final StatusLine statusLine = response.getStatusLine();
+ final int statusCode = statusLine.getStatusCode();
+ s_logger.debug("Status of last request: " + statusLine.toString());
+ if (HttpStatusCodeHelper.isUnauthorized(statusCode)) {
+ return handleUnauthorizedResponse(request, previousStatusCode, response, statusCode);
+ } else if (HttpStatusCodeHelper.isSuccess(statusCode)) {
+ return handleSuccessResponse(response);
+ } else {
+ throw new CloudstackRESTException("Unexpecetd status code: " + statusCode);
+ }
+ }
+
+ private CloseableHttpResponse handleUnauthorizedResponse(final HttpUriRequest request, final int previousStatusCode, final CloseableHttpResponse response, final int statusCode)
+ throws CloudstackRESTException {
+ super.closeResponse(response);
+ if (HttpStatusCodeHelper.isUnauthorized(previousStatusCode)) {
+ s_logger.error(responseToErrorMessage(response));
+ throw new CloudstackRESTException("Two consecutive failed attempts to authenticate against REST server");
+ }
+ final HttpUriRequest authenticateRequest = createAuthenticationRequest();
+ final CloseableHttpResponse loginResponse = execute(authenticateRequest, statusCode);
+ final int loginStatusCode = loginResponse.getStatusLine().getStatusCode();
+ super.closeResponse(loginResponse);
+ return execute(request, loginStatusCode);
+ }
+
+ private CloseableHttpResponse handleSuccessResponse(final CloseableHttpResponse response) {
+ counter.resetExecutionCounter();
+ return response;
+ }
+
+ private HttpUriRequest createAuthenticationRequest() {
+ final Map<String, String> parameters = new HashMap<>();
+ parameters.put("username", username);
+ parameters.put("password", password);
+ return HttpUriRequestBuilder.create()
+ .method(HttpMethods.POST)
+ .methodParameters(parameters)
+ .path(loginUrl)
+ .build();
+ }
+
+ private String responseToErrorMessage(final CloseableHttpResponse response) {
+ String errorMessage = response.getStatusLine().toString();
+ if (response.containsHeader(CONTENT_TYPE) && TEXT_HTML_CONTENT_TYPE.equals(response.getFirstHeader(CONTENT_TYPE).getValue())) {
+ try {
+ final HttpEntity entity = response.getEntity();
+ final String respobnseBody = EntityUtils.toString(entity);
+ errorMessage = respobnseBody.subSequence(0, maxResponseErrorMesageLength).toString();
+ } catch (final IOException e) {
+ s_logger.debug("Could not read repsonse body. Response: " + response, e);
+ }
+ }
+
+ return errorMessage;
+ }
+
+ protected static class Builder extends BasicRestClient.Builder<Builder> {
+ private CloseableHttpClient client;
+ private HttpClientContext clientContext;
+ private String hostname;
+ private String username;
+ private String password;
+ private String loginUrl;
+ private int executionLimit = DEFAULT_EXECUTION_LIMIT;
+ private int maxResponseErrorMesageLength = DEFAULT_BODY_RESP_MAX_LEN;
+
+ public Builder hostname(final String hostname) {
+ this.hostname = hostname;
+ return this;
+ }
+
+ public Builder username(final String username) {
+ this.username = username;
+ return this;
+ }
+
+ public Builder password(final String password) {
+ this.password = password;
+ return this;
+ }
+
+ public Builder loginUrl(final String loginUrl) {
+ this.loginUrl = loginUrl;
+ return this;
+ }
+
+ @Override
+ public Builder client(final CloseableHttpClient client) {
+ this.client = client;
+ return this;
+ }
+
+ @Override
+ public Builder clientContext(final HttpClientContext clientContext) {
+ this.clientContext = clientContext;
+ return this;
+ }
+
+ public Builder executionLimit(final int executionLimit) {
+ this.executionLimit = executionLimit;
+ return this;
+ }
+
+ public Builder maxResponseErrorMesageLength(final int maxResponseErrorMesageLength) {
+ this.maxResponseErrorMesageLength = maxResponseErrorMesageLength;
+ return this;
+ }
+
+ @Override
+ public NiciraRestClient build() {
+ return new NiciraRestClient(this);
+ }
+
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java
new file mode 100644
index 0000000..18797df
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java
@@ -0,0 +1,55 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import org.junit.Test;
+
+public class ExecutionCounterTest {
+
+ @Test
+ public void testIncrementCounter() throws Exception {
+ final ExecutionCounter executionCounter = new ExecutionCounter(-1);
+
+ executionCounter.incrementExecutionCounter().incrementExecutionCounter();
+
+ assertThat(executionCounter.getValue(), equalTo(2));
+ }
+
+ @Test
+ public void testHasNotYetReachedTheExecutuionLimit() throws Exception {
+ final ExecutionCounter executionCounter = new ExecutionCounter(2);
+
+ executionCounter.incrementExecutionCounter();
+
+ assertThat(executionCounter.hasReachedExecutionLimit(), equalTo(false));
+ }
+
+ @Test
+ public void testHasAlreadyReachedTheExecutuionLimit() throws Exception {
+ final ExecutionCounter executionCounter = new ExecutionCounter(2);
+
+ executionCounter.incrementExecutionCounter().incrementExecutionCounter();
+
+ assertThat(executionCounter.hasReachedExecutionLimit(), equalTo(true));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java
new file mode 100644
index 0000000..7fcab80
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java
@@ -0,0 +1,172 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.isEmptyOrNullString;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.sameInstance;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.powermock.api.mockito.PowerMockito.spy;
+import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.http.HttpHost;
+import org.apache.http.ProtocolVersion;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.message.BasicStatusLine;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import com.cloud.utils.rest.CloudstackRESTException;
+import com.cloud.utils.rest.HttpMethods;
+import com.cloud.utils.rest.HttpRequestMatcher;
+import com.cloud.utils.rest.HttpUriRequestBuilder;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(NiciraRestClient.class)
+public class NiciraRestClientTest {
+
+ private static final int HTTPS_PORT = 443;
+
+ private static final String HTTPS = "HTTPS";
+ private static final String LOGIN_PATH = "/login";
+ private static final String LOCALHOST = "localhost";
+ private static final String ADMIN = "admin";
+ private static final String ADMIN_PASSWORD = "adminpassword";
+
+ private static final HttpHost HTTP_HOST = new HttpHost(LOCALHOST, HTTPS_PORT, HTTPS);
+
+ private static final StatusLine HTTP_200_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 200, "OK");
+ private static final StatusLine HTTP_401_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 401, "Unauthorized");
+
+ private static final Map<String, String> loginParameters = new HashMap<String, String>();
+ private static HttpUriRequest request;
+ private static HttpUriRequest loginRequest;
+ private final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ private final CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
+ private HttpClientContext httpClientContext;
+ private NiciraRestClient client;
+
+ @BeforeClass
+ public static void setupClass() {
+ loginParameters.put("username", ADMIN);
+ loginParameters.put("password", ADMIN_PASSWORD);
+ request = HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("/path")
+ .build();
+ loginRequest = HttpUriRequestBuilder.create()
+ .method(HttpMethods.POST)
+ .methodParameters(loginParameters)
+ .path(LOGIN_PATH)
+ .build();
+ }
+
+ @Before
+ public void setup() {
+ httpClientContext = HttpClientContext.create();
+ client = spy(NiciraRestClient.create()
+ .client(httpClient)
+ .clientContext(httpClientContext)
+ .hostname(LOCALHOST)
+ .username(ADMIN)
+ .password(ADMIN_PASSWORD)
+ .loginUrl(LOGIN_PATH)
+ .executionLimit(5)
+ .build());
+ }
+
+ @Test
+ public void testExecuteSuccessAtFirstAttempt() throws Exception {
+ when(mockResponse.getStatusLine()).thenReturn(HTTP_200_STATUSLINE);
+ when(httpClient.execute(eq(HTTP_HOST), eq(request), eq(httpClientContext))).thenReturn(mockResponse);
+
+ final CloseableHttpResponse response = client.execute(request);
+
+ assertThat(response, notNullValue());
+ assertThat(response, sameInstance(mockResponse));
+ verifyPrivate(client).invoke("execute", request, 0);
+ }
+
+ @Test
+ public void testExecuteUnauthorizedThenSuccess() throws Exception {
+ when(mockResponse.getStatusLine())
+ .thenReturn(HTTP_401_STATUSLINE)
+ .thenReturn(HTTP_200_STATUSLINE)
+ .thenReturn(HTTP_200_STATUSLINE);
+ when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext)))
+ .thenReturn(mockResponse)
+ .thenReturn(mockResponse);
+ when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext)))
+ .thenReturn(mockResponse);
+
+ final CloseableHttpResponse response = client.execute(request);
+
+ assertThat(response, notNullValue());
+ assertThat(response, sameInstance(mockResponse));
+ verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(request), eq(0));
+ verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(loginRequest), eq(401));
+ verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(request), eq(200));
+ }
+
+ @Test
+ public void testExecuteTwoConsecutiveUnauthorizedExecutions() throws Exception {
+ when(mockResponse.getStatusLine())
+ .thenReturn(HTTP_401_STATUSLINE)
+ .thenReturn(HTTP_401_STATUSLINE);
+ when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext)))
+ .thenReturn(mockResponse);
+ when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext)))
+ .thenReturn(mockResponse);
+ final NiciraRestClient client = spy(NiciraRestClient.create()
+ .client(httpClient)
+ .clientContext(httpClientContext)
+ .hostname(LOCALHOST)
+ .username(ADMIN)
+ .password(ADMIN_PASSWORD)
+ .loginUrl(LOGIN_PATH)
+ .executionLimit(2)
+ .build());
+
+ try {
+ client.execute(request);
+ fail("Expected CloudstackRESTException exception");
+ } catch (final CloudstackRESTException e) {
+ assertThat(e.getMessage(), not(isEmptyOrNullString()));
+ verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(request), eq(0));
+ verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(loginRequest), eq(401));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index b5e380e..219402c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -985,7 +985,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
- <argLine>-Djava.security.egd=file:/dev/./urandom</argLine>
+ <argLine>-Djava.security.egd=file:/dev/./urandom -noverify</argLine>
</configuration>
</plugin>
<plugin>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java b/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java
new file mode 100644
index 0000000..9492920
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.rest;
+
+import org.apache.http.HttpStatus;
+
+public class HttpStatusCodeHelper {
+
+ public static boolean isSuccess(final int statusCode) {
+ return statusCode >= HttpStatus.SC_OK && statusCode <= HttpStatus.SC_MULTI_STATUS;
+ }
+
+ public static boolean isUnauthorized(final int statusCode) {
+ return statusCode == HttpStatus.SC_UNAUTHORIZED;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18e6b9ba/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java b/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java
new file mode 100644
index 0000000..3999b20
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java
@@ -0,0 +1,59 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import org.apache.http.HttpStatus;
+import org.junit.Test;
+
+public class HttpStatusCodeHelperTest {
+
+ @Test
+ public void testIsSuccess() throws Exception {
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_SWITCHING_PROTOCOLS), equalTo(false));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_PROCESSING), equalTo(false));
+
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_OK), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_CREATED), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_ACCEPTED), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_NO_CONTENT), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_RESET_CONTENT), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_PARTIAL_CONTENT), equalTo(true));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_MULTI_STATUS), equalTo(true));
+
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_MULTIPLE_CHOICES), equalTo(false));
+ assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_MOVED_PERMANENTLY), equalTo(false));
+ }
+
+ @Test
+ public void testIsUnauthorized() throws Exception {
+ assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_TEMPORARY_REDIRECT), equalTo(false));
+ assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_BAD_REQUEST), equalTo(false));
+
+ assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_UNAUTHORIZED), equalTo(true));
+
+ assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_PAYMENT_REQUIRED), equalTo(false));
+ assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_FORBIDDEN), equalTo(false));
+ }
+
+}
[41/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Refactor cloud-plugin-network-nvp project into Maven default structure
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/93b0989d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/93b0989d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/93b0989d
Branch: refs/heads/deploy-from-snapshot
Commit: 93b0989deaf01ffae3242761174098ca5207b53c
Parents: 83fd8f6
Author: Miguel Ferreira <mi...@me.com>
Authored: Sat Aug 22 20:48:27 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:10 2015 +0200
----------------------------------------------------------------------
plugins/network-elements/nicira-nvp/pom.xml | 11 +-
.../META-INF/cloudstack/nvp/module.properties | 21 -
.../cloudstack/nvp/spring-nvp-context.xml | 42 -
...ortForwardingRulesOnLogicalRouterAnswer.java | 35 -
...rtForwardingRulesOnLogicalRouterCommand.java | 63 --
...ConfigurePublicIpsOnLogicalRouterAnswer.java | 32 -
...onfigurePublicIpsOnLogicalRouterCommand.java | 66 --
...gureStaticNatRulesOnLogicalRouterAnswer.java | 44 -
...ureStaticNatRulesOnLogicalRouterCommand.java | 65 --
.../agent/api/CreateLogicalRouterAnswer.java | 42 -
.../agent/api/CreateLogicalRouterCommand.java | 116 ---
.../agent/api/CreateLogicalSwitchAnswer.java | 38 -
.../agent/api/CreateLogicalSwitchCommand.java | 57 --
.../api/CreateLogicalSwitchPortAnswer.java | 38 -
.../api/CreateLogicalSwitchPortCommand.java | 56 --
.../agent/api/DeleteLogicalRouterAnswer.java | 34 -
.../agent/api/DeleteLogicalRouterCommand.java | 44 -
.../agent/api/DeleteLogicalSwitchAnswer.java | 32 -
.../agent/api/DeleteLogicalSwitchCommand.java | 38 -
.../api/DeleteLogicalSwitchPortAnswer.java | 32 -
.../api/DeleteLogicalSwitchPortCommand.java | 44 -
.../agent/api/FindLogicalSwitchPortAnswer.java | 38 -
.../agent/api/FindLogicalSwitchPortCommand.java | 44 -
.../agent/api/StartupNiciraNvpCommand.java | 30 -
.../api/UpdateLogicalSwitchPortAnswer.java | 38 -
.../api/UpdateLogicalSwitchPortCommand.java | 63 --
.../api/commands/AddNiciraNvpDeviceCmd.java | 154 ----
.../api/commands/DeleteNiciraNvpDeviceCmd.java | 112 ---
.../ListNiciraNvpDeviceNetworksCmd.java | 111 ---
.../api/commands/ListNiciraNvpDevicesCmd.java | 108 ---
.../api/response/NiciraNvpDeviceResponse.java | 89 --
.../com/cloud/network/NiciraNvpDeviceVO.java | 99 ---
.../cloud/network/NiciraNvpNicMappingVO.java | 87 --
.../cloud/network/NiciraNvpRouterMappingVO.java | 85 --
.../src/com/cloud/network/dao/NiciraNvpDao.java | 35 -
.../com/cloud/network/dao/NiciraNvpDaoImpl.java | 53 --
.../network/dao/NiciraNvpNicMappingDao.java | 32 -
.../network/dao/NiciraNvpNicMappingDaoImpl.java | 51 --
.../network/dao/NiciraNvpRouterMappingDao.java | 28 -
.../dao/NiciraNvpRouterMappingDaoImpl.java | 51 --
.../cloud/network/element/NiciraNvpElement.java | 849 ------------------
.../element/NiciraNvpElementService.java | 45 -
.../network/guru/NiciraNvpGuestNetworkGuru.java | 256 ------
.../network/nicira/AccessConfiguration.java | 44 -
.../com/cloud/network/nicira/AccessRule.java | 58 --
.../src/com/cloud/network/nicira/Acl.java | 23 -
.../src/com/cloud/network/nicira/AclRule.java | 209 -----
.../com/cloud/network/nicira/Attachment.java | 24 -
.../cloud/network/nicira/BaseNiciraEntity.java | 85 --
.../network/nicira/BaseNiciraNamedEntity.java | 44 -
.../network/nicira/ControlClusterStatus.java | 87 --
.../network/nicira/DestinationNatRule.java | 113 ---
.../network/nicira/L3GatewayAttachment.java | 55 --
.../com/cloud/network/nicira/LogicalRouter.java | 71 --
.../cloud/network/nicira/LogicalRouterPort.java | 62 --
.../com/cloud/network/nicira/LogicalSwitch.java | 60 --
.../cloud/network/nicira/LogicalSwitchPort.java | 82 --
.../src/com/cloud/network/nicira/Match.java | 146 ---
.../src/com/cloud/network/nicira/NatRule.java | 130 ---
.../com/cloud/network/nicira/NiciraNvpApi.java | 658 --------------
.../network/nicira/NiciraNvpApiException.java | 39 -
.../com/cloud/network/nicira/NiciraNvpList.java | 48 -
.../com/cloud/network/nicira/NiciraNvpTag.java | 64 --
.../cloud/network/nicira/PatchAttachment.java | 41 -
.../com/cloud/network/nicira/RouterNextHop.java | 40 -
.../com/cloud/network/nicira/RoutingConfig.java | 24 -
.../nicira/RoutingTableRoutingConfig.java | 30 -
.../cloud/network/nicira/SecurityProfile.java | 24 -
.../com/cloud/network/nicira/SecurityRule.java | 138 ---
...SingleDefaultRouteImplicitRoutingConfig.java | 40 -
.../com/cloud/network/nicira/SourceNatRule.java | 119 ---
.../network/nicira/TransportZoneBinding.java | 50 --
.../com/cloud/network/nicira/VifAttachment.java | 78 --
.../resource/NiciraNvpRequestWrapper.java | 77 --
.../network/resource/NiciraNvpResource.java | 319 -------
.../network/resource/NiciraNvpUtilities.java | 65 --
...figurePortForwardingRulesCommandWrapper.java | 120 ---
...ciraNvpConfigurePublicIpsCommandWrapper.java | 60 --
...vpConfigureStaticNatRulesCommandWrapper.java | 113 ---
...iraNvpCreateLogicalRouterCommandWrapper.java | 152 ----
...iraNvpCreateLogicalSwitchCommandWrapper.java | 73 --
...vpCreateLogicalSwitchPortCommandWrapper.java | 70 --
...iraNvpDeleteLogicalRouterCommandWrapper.java | 50 --
...iraNvpDeleteLogicalSwitchCommandWrapper.java | 49 --
...vpDeleteLogicalSwitchPortCommandWrapper.java | 50 --
...aNvpFindLogicalSwitchPortCommandWrapper.java | 59 --
.../NiciraNvpMaintainCommandWrapper.java | 36 -
.../wrapper/NiciraNvpReadyCommandWrapper.java | 36 -
...vpUpdateLogicalSwitchPortCommandWrapper.java | 68 --
.../network/utils/CommandRetryUtility.java | 89 --
...ortForwardingRulesOnLogicalRouterAnswer.java | 35 +
...rtForwardingRulesOnLogicalRouterCommand.java | 63 ++
...ConfigurePublicIpsOnLogicalRouterAnswer.java | 32 +
...onfigurePublicIpsOnLogicalRouterCommand.java | 66 ++
...gureStaticNatRulesOnLogicalRouterAnswer.java | 44 +
...ureStaticNatRulesOnLogicalRouterCommand.java | 65 ++
.../agent/api/CreateLogicalRouterAnswer.java | 42 +
.../agent/api/CreateLogicalRouterCommand.java | 116 +++
.../agent/api/CreateLogicalSwitchAnswer.java | 38 +
.../agent/api/CreateLogicalSwitchCommand.java | 57 ++
.../api/CreateLogicalSwitchPortAnswer.java | 38 +
.../api/CreateLogicalSwitchPortCommand.java | 56 ++
.../agent/api/DeleteLogicalRouterAnswer.java | 34 +
.../agent/api/DeleteLogicalRouterCommand.java | 44 +
.../agent/api/DeleteLogicalSwitchAnswer.java | 32 +
.../agent/api/DeleteLogicalSwitchCommand.java | 38 +
.../api/DeleteLogicalSwitchPortAnswer.java | 32 +
.../api/DeleteLogicalSwitchPortCommand.java | 44 +
.../agent/api/FindLogicalSwitchPortAnswer.java | 38 +
.../agent/api/FindLogicalSwitchPortCommand.java | 44 +
.../agent/api/StartupNiciraNvpCommand.java | 30 +
.../api/UpdateLogicalSwitchPortAnswer.java | 38 +
.../api/UpdateLogicalSwitchPortCommand.java | 63 ++
.../api/commands/AddNiciraNvpDeviceCmd.java | 154 ++++
.../api/commands/DeleteNiciraNvpDeviceCmd.java | 112 +++
.../ListNiciraNvpDeviceNetworksCmd.java | 111 +++
.../api/commands/ListNiciraNvpDevicesCmd.java | 108 +++
.../api/response/NiciraNvpDeviceResponse.java | 89 ++
.../com/cloud/network/NiciraNvpDeviceVO.java | 99 +++
.../cloud/network/NiciraNvpNicMappingVO.java | 87 ++
.../cloud/network/NiciraNvpRouterMappingVO.java | 85 ++
.../com/cloud/network/dao/NiciraNvpDao.java | 35 +
.../com/cloud/network/dao/NiciraNvpDaoImpl.java | 53 ++
.../network/dao/NiciraNvpNicMappingDao.java | 32 +
.../network/dao/NiciraNvpNicMappingDaoImpl.java | 51 ++
.../network/dao/NiciraNvpRouterMappingDao.java | 28 +
.../dao/NiciraNvpRouterMappingDaoImpl.java | 51 ++
.../cloud/network/element/NiciraNvpElement.java | 849 ++++++++++++++++++
.../element/NiciraNvpElementService.java | 45 +
.../network/guru/NiciraNvpGuestNetworkGuru.java | 256 ++++++
.../network/nicira/AccessConfiguration.java | 44 +
.../com/cloud/network/nicira/AccessRule.java | 58 ++
.../main/java/com/cloud/network/nicira/Acl.java | 23 +
.../java/com/cloud/network/nicira/AclRule.java | 209 +++++
.../com/cloud/network/nicira/Attachment.java | 24 +
.../cloud/network/nicira/BaseNiciraEntity.java | 85 ++
.../network/nicira/BaseNiciraNamedEntity.java | 44 +
.../network/nicira/ControlClusterStatus.java | 87 ++
.../network/nicira/DestinationNatRule.java | 113 +++
.../network/nicira/L3GatewayAttachment.java | 55 ++
.../com/cloud/network/nicira/LogicalRouter.java | 71 ++
.../cloud/network/nicira/LogicalRouterPort.java | 62 ++
.../com/cloud/network/nicira/LogicalSwitch.java | 60 ++
.../cloud/network/nicira/LogicalSwitchPort.java | 82 ++
.../java/com/cloud/network/nicira/Match.java | 146 +++
.../java/com/cloud/network/nicira/NatRule.java | 130 +++
.../com/cloud/network/nicira/NiciraNvpApi.java | 658 ++++++++++++++
.../network/nicira/NiciraNvpApiException.java | 39 +
.../com/cloud/network/nicira/NiciraNvpList.java | 48 +
.../com/cloud/network/nicira/NiciraNvpTag.java | 64 ++
.../cloud/network/nicira/PatchAttachment.java | 41 +
.../com/cloud/network/nicira/RouterNextHop.java | 40 +
.../com/cloud/network/nicira/RoutingConfig.java | 24 +
.../nicira/RoutingTableRoutingConfig.java | 30 +
.../cloud/network/nicira/SecurityProfile.java | 24 +
.../com/cloud/network/nicira/SecurityRule.java | 138 +++
...SingleDefaultRouteImplicitRoutingConfig.java | 40 +
.../com/cloud/network/nicira/SourceNatRule.java | 119 +++
.../network/nicira/TransportZoneBinding.java | 50 ++
.../com/cloud/network/nicira/VifAttachment.java | 78 ++
.../resource/NiciraNvpRequestWrapper.java | 77 ++
.../network/resource/NiciraNvpResource.java | 319 +++++++
.../network/resource/NiciraNvpUtilities.java | 65 ++
...figurePortForwardingRulesCommandWrapper.java | 120 +++
...ciraNvpConfigurePublicIpsCommandWrapper.java | 60 ++
...vpConfigureStaticNatRulesCommandWrapper.java | 113 +++
...iraNvpCreateLogicalRouterCommandWrapper.java | 152 ++++
...iraNvpCreateLogicalSwitchCommandWrapper.java | 73 ++
...vpCreateLogicalSwitchPortCommandWrapper.java | 70 ++
...iraNvpDeleteLogicalRouterCommandWrapper.java | 50 ++
...iraNvpDeleteLogicalSwitchCommandWrapper.java | 49 ++
...vpDeleteLogicalSwitchPortCommandWrapper.java | 50 ++
...aNvpFindLogicalSwitchPortCommandWrapper.java | 59 ++
.../NiciraNvpMaintainCommandWrapper.java | 36 +
.../wrapper/NiciraNvpReadyCommandWrapper.java | 36 +
...vpUpdateLogicalSwitchPortCommandWrapper.java | 68 ++
.../network/utils/CommandRetryUtility.java | 89 ++
.../META-INF/cloudstack/nvp/module.properties | 21 +
.../cloudstack/nvp/spring-nvp-context.xml | 42 +
.../network/element/NiciraNvpElementTest.java | 217 +++++
.../guru/NiciraNvpGuestNetworkGuruTest.java | 476 ++++++++++
.../com/cloud/network/nicira/NatRuleTest.java | 55 ++
.../cloud/network/nicira/NiciraNvpApiIT.java | 347 ++++++++
.../cloud/network/nicira/NiciraNvpApiTest.java | 339 +++++++
.../com/cloud/network/nicira/NiciraTagTest.java | 58 ++
.../resource/NiciraNvpRequestWrapperTest.java | 255 ++++++
.../network/resource/NiciraNvpResourceTest.java | 882 +++++++++++++++++++
.../src/test/resources/config.properties | 23 +
.../network/element/NiciraNvpElementTest.java | 217 -----
.../guru/NiciraNvpGuestNetworkGuruTest.java | 476 ----------
.../com/cloud/network/nicira/NatRuleTest.java | 55 --
.../cloud/network/nicira/NiciraNvpApiIT.java | 347 --------
.../cloud/network/nicira/NiciraNvpApiTest.java | 339 -------
.../com/cloud/network/nicira/NiciraTagTest.java | 58 --
.../resource/NiciraNvpRequestWrapperTest.java | 255 ------
.../network/resource/NiciraNvpResourceTest.java | 882 -------------------
.../nicira-nvp/test/resources/config.properties | 23 -
197 files changed, 10231 insertions(+), 10222 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml
index 352155d..8567482 100644
--- a/plugins/network-elements/nicira-nvp/pom.xml
+++ b/plugins/network-elements/nicira-nvp/pom.xml
@@ -30,9 +30,18 @@
</parent>
<build>
+ <sourceDirectory>src/main/java</sourceDirectory>
+ <testSourceDirectory>src/test/java</testSourceDirectory>
+ <outputDirectory>target/classes</outputDirectory>
+ <testOutputDirectory>target/test-classes</testOutputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ </resource>
+ </resources>
<testResources>
<testResource>
- <directory>test/resources</directory>
+ <directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties
deleted file mode 100644
index 5085fce..0000000
--- a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties
+++ /dev/null
@@ -1,21 +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.
-#
-
-name=nvp
-parent=network
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml
deleted file mode 100644
index cd8a2c9..0000000
--- a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml
+++ /dev/null
@@ -1,42 +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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd"
- >
-
- <bean id="niciraNvpDaoImpl" class="com.cloud.network.dao.NiciraNvpDaoImpl" />
- <bean id="niciraNvpNicMappingDaoImpl" class="com.cloud.network.dao.NiciraNvpNicMappingDaoImpl" />
- <bean id="niciraNvpRouterMappingDaoImpl" class="com.cloud.network.dao.NiciraNvpRouterMappingDaoImpl" />
- <bean id="NiciraNvpGuestNetworkGuru" class="com.cloud.network.guru.NiciraNvpGuestNetworkGuru">
- <property name="name" value="NiciraNvpGuestNetworkGuru" />
- </bean>
- <bean id="NiciraNvp" class="com.cloud.network.element.NiciraNvpElement">
- <property name="name" value="NiciraNvp" />
- </bean>
-
-</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java
deleted file mode 100644
index 1765a81..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java
+++ /dev/null
@@ -1,35 +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 com.cloud.agent.api;
-
-/**
- *
- */
-public class ConfigurePortForwardingRulesOnLogicalRouterAnswer extends Answer {
-
- public ConfigurePortForwardingRulesOnLogicalRouterAnswer(final Command command, final boolean success, final String details) {
- super(command, success, details);
- }
-
- public ConfigurePortForwardingRulesOnLogicalRouterAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java
deleted file mode 100644
index 133714e..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java
+++ /dev/null
@@ -1,63 +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 com.cloud.agent.api;
-
-import java.util.List;
-
-import com.cloud.agent.api.to.PortForwardingRuleTO;
-
-/**
- *
- */
-public class ConfigurePortForwardingRulesOnLogicalRouterCommand extends Command {
-
- private String logicalRouterUuid;
- private List<PortForwardingRuleTO> rules;
-
- public ConfigurePortForwardingRulesOnLogicalRouterCommand(final String logicalRouterUuid, final List<PortForwardingRuleTO> rules) {
- this.logicalRouterUuid = logicalRouterUuid;
- this.rules = rules;
- }
-
- public String getLogicalRouterUuid() {
- return logicalRouterUuid;
- }
-
- public void setLogicalRouterUuid(final String logicalRouterUuid) {
- this.logicalRouterUuid = logicalRouterUuid;
- }
-
- public List<PortForwardingRuleTO> getRules() {
- return rules;
- }
-
- public void setRules(final List<PortForwardingRuleTO> rules) {
- this.rules = rules;
- }
-
- /* (non-Javadoc)
- * @see com.cloud.agent.api.Command#executeInSequence()
- */
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java
deleted file mode 100644
index 9da6caf..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java
+++ /dev/null
@@ -1,32 +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 com.cloud.agent.api;
-
-public class ConfigurePublicIpsOnLogicalRouterAnswer extends Answer {
-
- public ConfigurePublicIpsOnLogicalRouterAnswer(final Command command, final boolean success, final String details) {
- super(command, success, details);
- }
-
- public ConfigurePublicIpsOnLogicalRouterAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java
deleted file mode 100644
index ff81ae4..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java
+++ /dev/null
@@ -1,66 +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 com.cloud.agent.api;
-
-import java.util.List;
-
-public class ConfigurePublicIpsOnLogicalRouterCommand extends Command {
-
- private String logicalRouterUuid;
- private String l3GatewayServiceUuid;
- private List<String> publicCidrs;
-
- public ConfigurePublicIpsOnLogicalRouterCommand(final String logicalRouterUuid, final String l3GatewayServiceUuid, final List<String> publicCidrs) {
- super();
- this.logicalRouterUuid = logicalRouterUuid;
- this.publicCidrs = publicCidrs;
- this.l3GatewayServiceUuid = l3GatewayServiceUuid;
- }
-
- public String getLogicalRouterUuid() {
- return logicalRouterUuid;
- }
-
- public void setLogicalRouterUuid(final String logicalRouterUuid) {
- this.logicalRouterUuid = logicalRouterUuid;
- }
-
- public String getL3GatewayServiceUuid() {
- return l3GatewayServiceUuid;
- }
-
- public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) {
- this.l3GatewayServiceUuid = l3GatewayServiceUuid;
- }
-
- public List<String> getPublicCidrs() {
- return publicCidrs;
- }
-
- public void setPublicCidrs(final List<String> publicCidrs) {
- this.publicCidrs = publicCidrs;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java
deleted file mode 100644
index 9074491..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java
+++ /dev/null
@@ -1,44 +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 com.cloud.agent.api;
-
-/**
- *
- */
-public class ConfigureStaticNatRulesOnLogicalRouterAnswer extends Answer {
-
- /**
- * @param command
- * @param success
- * @param details
- */
- public ConfigureStaticNatRulesOnLogicalRouterAnswer(final Command command, final boolean success, final String details) {
- super(command, success, details);
- }
-
- /**
- * @param command
- * @param e
- */
- public ConfigureStaticNatRulesOnLogicalRouterAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java
deleted file mode 100644
index b5434b3..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java
+++ /dev/null
@@ -1,65 +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 com.cloud.agent.api;
-
-import java.util.List;
-
-import com.cloud.agent.api.to.StaticNatRuleTO;
-
-/**
- *
- */
-public class ConfigureStaticNatRulesOnLogicalRouterCommand extends Command {
-
- private String logicalRouterUuid;
- private List<StaticNatRuleTO> rules;
-
- public ConfigureStaticNatRulesOnLogicalRouterCommand(final String logicalRouterUuid, final List<StaticNatRuleTO> rules) {
- super();
- this.logicalRouterUuid = logicalRouterUuid;
- this.rules = rules;
-
- }
-
- public String getLogicalRouterUuid() {
- return logicalRouterUuid;
- }
-
- public void setLogicalRouterUuid(final String logicalRouterUuid) {
- this.logicalRouterUuid = logicalRouterUuid;
- }
-
- public List<StaticNatRuleTO> getRules() {
- return rules;
- }
-
- public void setRules(final List<StaticNatRuleTO> rules) {
- this.rules = rules;
- }
-
- /* (non-Javadoc)
- * @see com.cloud.agent.api.Command#executeInSequence()
- */
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java
deleted file mode 100644
index 0172891..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java
+++ /dev/null
@@ -1,42 +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 com.cloud.agent.api;
-
-/**
- *
- */
-public class CreateLogicalRouterAnswer extends Answer {
-
- private String logicalRouterUuid;
-
- public CreateLogicalRouterAnswer(final Command command, final boolean success, final String details, final String logicalRouterUuid) {
- super(command, success, details);
- this.logicalRouterUuid = logicalRouterUuid;
- }
-
- public CreateLogicalRouterAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
- public String getLogicalRouterUuid() {
- return logicalRouterUuid;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java
deleted file mode 100644
index ff12b8d..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java
+++ /dev/null
@@ -1,116 +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 com.cloud.agent.api;
-
-/**
- *
- */
-public class CreateLogicalRouterCommand extends Command {
- private String gatewayServiceUuid;
- private String logicalSwitchUuid;
- private long vlanId;
- private String name;
- private String ownerName;
- private String publicIpCidr;
- private String publicNextHop;
- private String internalIpCidr;
-
- public CreateLogicalRouterCommand(final String gatewayServiceUuid, final long vlanId, final String logicalSwitchUuid, final String name, final String publicIpCidr,
- final String publicNextHop, final String internalIpCidr, final String ownerName) {
- super();
- this.gatewayServiceUuid = gatewayServiceUuid;
- this.logicalSwitchUuid = logicalSwitchUuid;
- this.vlanId = vlanId;
- this.name = name;
- this.ownerName = ownerName;
- this.publicIpCidr = publicIpCidr;
- this.publicNextHop = publicNextHop;
- this.internalIpCidr = internalIpCidr;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
- public String getGatewayServiceUuid() {
- return gatewayServiceUuid;
- }
-
- public void setGatewayServiceUuid(final String gatewayServiceUuid) {
- this.gatewayServiceUuid = gatewayServiceUuid;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
- public void setLogicalSwitchUuid(final String logicalSwitchUuid) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- }
-
- public long getVlanId() {
- return vlanId;
- }
-
- public void setVlanId(final long vlanId) {
- this.vlanId = vlanId;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(final String name) {
- this.name = name;
- }
-
- public String getOwnerName() {
- return ownerName;
- }
-
- public void setOwnerName(final String ownerName) {
- this.ownerName = ownerName;
- }
-
- public String getPublicIpCidr() {
- return publicIpCidr;
- }
-
- public void setPublicIpCidr(final String publicIpCidr) {
- this.publicIpCidr = publicIpCidr;
- }
-
- public String getInternalIpCidr() {
- return internalIpCidr;
- }
-
- public void setInternalIpCidr(final String internalIpCidr) {
- this.internalIpCidr = internalIpCidr;
- }
-
- public String getPublicNextHop() {
- return publicNextHop;
- }
-
- public void setPublicNextHop(final String publicNextHop) {
- this.publicNextHop = publicNextHop;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java
deleted file mode 100644
index ee9924e..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java
+++ /dev/null
@@ -1,38 +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 com.cloud.agent.api;
-
-public class CreateLogicalSwitchAnswer extends Answer {
- private String logicalSwitchUuid;
-
- public CreateLogicalSwitchAnswer(final Command command, final boolean success, final String details, final String logicalSwitchUuid) {
- super(command, success, details);
- this.logicalSwitchUuid = logicalSwitchUuid;
- }
-
- public CreateLogicalSwitchAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java
deleted file mode 100644
index 5dc8616..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java
+++ /dev/null
@@ -1,57 +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 com.cloud.agent.api;
-
-public class CreateLogicalSwitchCommand extends Command {
-
- private final String transportUuid;
- private final String transportType;
- private final String name;
- private final String ownerName;
-
- public CreateLogicalSwitchCommand(final String transportUuid, final String transportType, final String name, final String ownerName) {
- this.transportUuid = transportUuid;
- this.transportType = transportType;
- this.name = name;
- this.ownerName = ownerName;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
- public String getTransportUuid() {
- return transportUuid;
- }
-
- public String getTransportType() {
- return transportType;
- }
-
- public String getName() {
- return name;
- }
-
- public String getOwnerName() {
- return ownerName;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java
deleted file mode 100644
index 8b09389..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java
+++ /dev/null
@@ -1,38 +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 com.cloud.agent.api;
-
-public class CreateLogicalSwitchPortAnswer extends Answer {
- private String logicalSwitchPortUuid;
-
- public CreateLogicalSwitchPortAnswer(final Command command, final boolean success, final String details, final String localSwitchPortUuid) {
- super(command, success, details);
- logicalSwitchPortUuid = localSwitchPortUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwitchPortUuid;
- }
-
- public CreateLogicalSwitchPortAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java
deleted file mode 100644
index 6bc578f..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java
+++ /dev/null
@@ -1,56 +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 com.cloud.agent.api;
-
-public class CreateLogicalSwitchPortCommand extends Command {
- private final String logicalSwitchUuid;
- private final String attachmentUuid;
- private final String ownerName;
- private final String nicName;
-
- public CreateLogicalSwitchPortCommand(final String logicalSwitchUuid, final String attachmentUuid, final String ownerName, final String nicName) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- this.attachmentUuid = attachmentUuid;
- this.ownerName = ownerName;
- this.nicName = nicName;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
- public String getAttachmentUuid() {
- return attachmentUuid;
- }
-
- public String getOwnerName() {
- return ownerName;
- }
-
- public String getNicName() {
- return nicName;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java
deleted file mode 100644
index f7f101d..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java
+++ /dev/null
@@ -1,34 +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 com.cloud.agent.api;
-
-/**
- *
- */
-public class DeleteLogicalRouterAnswer extends Answer {
-
- public DeleteLogicalRouterAnswer(final Command command, final boolean success, final String details) {
- super(command, success, details);
- }
-
- public DeleteLogicalRouterAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java
deleted file mode 100644
index 8fd14e9..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java
+++ /dev/null
@@ -1,44 +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 com.cloud.agent.api;
-
-/**
- *
- */
-public class DeleteLogicalRouterCommand extends Command {
-
- private final String logicalRouterUuid;
-
- public DeleteLogicalRouterCommand(String logicalRouterUuid) {
- this.logicalRouterUuid = logicalRouterUuid;
- }
-
- /* (non-Javadoc)
- * @see com.cloud.agent.api.Command#executeInSequence()
- */
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
- public String getLogicalRouterUuid() {
- return logicalRouterUuid;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java
deleted file mode 100644
index e2c483f..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java
+++ /dev/null
@@ -1,32 +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 com.cloud.agent.api;
-
-public class DeleteLogicalSwitchAnswer extends Answer {
-
- public DeleteLogicalSwitchAnswer(final Command command, final boolean success, final String details) {
- super(command, success, details);
- }
-
- public DeleteLogicalSwitchAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java
deleted file mode 100644
index dbfefe2..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java
+++ /dev/null
@@ -1,38 +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 com.cloud.agent.api;
-
-public class DeleteLogicalSwitchCommand extends Command {
-
- private final String logicalSwitchUuid;
-
- public DeleteLogicalSwitchCommand(final String logicalSwitchUuid) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java
deleted file mode 100644
index 1cd87ea..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java
+++ /dev/null
@@ -1,32 +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 com.cloud.agent.api;
-
-public class DeleteLogicalSwitchPortAnswer extends Answer {
-
- public DeleteLogicalSwitchPortAnswer(final Command command, final boolean success, final String details) {
- super(command, success, details);
- }
-
- public DeleteLogicalSwitchPortAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java
deleted file mode 100644
index 4a5e607..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java
+++ /dev/null
@@ -1,44 +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 com.cloud.agent.api;
-
-public class DeleteLogicalSwitchPortCommand extends Command {
- private final String logicalSwitchUuid;
- private final String logicalSwithPortUuid;
-
- public DeleteLogicalSwitchPortCommand(final String logicalSwitchUuid, final String logicalSwitchPortUuid) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- logicalSwithPortUuid = logicalSwitchPortUuid;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwithPortUuid;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java
deleted file mode 100644
index 0524531..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java
+++ /dev/null
@@ -1,38 +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 com.cloud.agent.api;
-
-public class FindLogicalSwitchPortAnswer extends Answer {
- private String logicalSwitchPortUuid;
-
- public FindLogicalSwitchPortAnswer(final Command command, final boolean success, final String details, final String localSwitchPortUuid) {
- super(command, success, details);
- logicalSwitchPortUuid = localSwitchPortUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwitchPortUuid;
- }
-
- public FindLogicalSwitchPortAnswer(final Command command, final Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java
deleted file mode 100644
index ee00bd2..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java
+++ /dev/null
@@ -1,44 +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 com.cloud.agent.api;
-
-public class FindLogicalSwitchPortCommand extends Command {
- private final String logicalSwitchUuid;
- private final String logicalSwitchPortUuid;
-
- public FindLogicalSwitchPortCommand(String logicalSwitchUuid, String logicalSwitchPortUuid) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- this.logicalSwitchPortUuid = logicalSwitchPortUuid;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwitchPortUuid;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/StartupNiciraNvpCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/StartupNiciraNvpCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/StartupNiciraNvpCommand.java
deleted file mode 100644
index 9597d2f..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/StartupNiciraNvpCommand.java
+++ /dev/null
@@ -1,30 +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 com.cloud.agent.api;
-
-import com.cloud.host.Host;
-
-public class StartupNiciraNvpCommand extends StartupCommand {
-
- public StartupNiciraNvpCommand() {
- super(Host.Type.L2Networking);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java
deleted file mode 100644
index 1471723..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java
+++ /dev/null
@@ -1,38 +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 com.cloud.agent.api;
-
-public class UpdateLogicalSwitchPortAnswer extends Answer {
- private String logicalSwitchPortUuid;
-
- public UpdateLogicalSwitchPortAnswer(Command command, boolean success, String details, String localSwitchPortUuid) {
- super(command, success, details);
- logicalSwitchPortUuid = localSwitchPortUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwitchPortUuid;
- }
-
- public UpdateLogicalSwitchPortAnswer(Command command, Exception e) {
- super(command, e);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java
deleted file mode 100644
index 91682a1..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java
+++ /dev/null
@@ -1,63 +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 com.cloud.agent.api;
-
-public class UpdateLogicalSwitchPortCommand extends Command {
- private final String logicalSwitchUuid;
- private final String logicalSwitchPortUuid;
- private final String attachmentUuid;
- private final String ownerName;
- private final String nicName;
-
- public UpdateLogicalSwitchPortCommand(final String logicalSwitchPortUuid, final String logicalSwitchUuid, final String attachmentUuid, final String ownerName,
- final String nicName) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- this.logicalSwitchPortUuid = logicalSwitchPortUuid;
- this.attachmentUuid = attachmentUuid;
- this.ownerName = ownerName;
- this.nicName = nicName;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwitchPortUuid;
- }
-
- public String getAttachmentUuid() {
- return attachmentUuid;
- }
-
- public String getOwnerName() {
- return ownerName;
- }
-
- public String getNicName() {
- return nicName;
- }
-
- @Override
- public boolean executeInSequence() {
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java
deleted file mode 100644
index 1a9be28..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java
+++ /dev/null
@@ -1,154 +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 com.cloud.api.commands;
-
-import javax.inject.Inject;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.ApiErrorCode;
-import org.apache.cloudstack.api.BaseAsyncCmd;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
-import org.apache.cloudstack.context.CallContext;
-
-import com.cloud.api.response.NiciraNvpDeviceResponse;
-import com.cloud.event.EventTypes;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.ResourceAllocationException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.network.element.NiciraNvpElementService;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-@APICommand(name = "addNiciraNvpDevice", responseObject = NiciraNvpDeviceResponse.class, description = "Adds a Nicira NVP device",
- requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
-public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd {
- private static final String s_name = "addniciranvpdeviceresponse";
- @Inject
- protected NiciraNvpElementService niciraNvpElementService;
-
- /////////////////////////////////////////////////////
- //////////////// API parameters /////////////////////
- /////////////////////////////////////////////////////
-
- @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID,
- type = CommandType.UUID,
- entityType = PhysicalNetworkResponse.class,
- required = true,
- description = "the Physical Network ID")
- private Long physicalNetworkId;
-
- @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname of ip address of the Nicira NVP Controller.")
- private String host;
-
- @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to access the Nicira Controller API")
- private String username;
-
- @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to access the Nicira Controller API")
- private String password;
-
- @Parameter(name = ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID,
- type = CommandType.STRING,
- required = true,
- description = "The Transportzone UUID configured on the Nicira Controller")
- private String transportzoneuuid;
-
- @Parameter(name = ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID,
- type = CommandType.STRING,
- required = false,
- description = "The L3 Gateway Service UUID configured on the Nicira Controller")
- private String l3gatewayserviceuuid;
-
- /////////////////////////////////////////////////////
- /////////////////// Accessors ///////////////////////
- /////////////////////////////////////////////////////
-
- public Long getPhysicalNetworkId() {
- return physicalNetworkId;
- }
-
- public String getHost() {
- return host;
- }
-
- public String getUsername() {
- return username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public String getTransportzoneUuid() {
- return transportzoneuuid;
- }
-
- public String getL3GatewayServiceUuid() {
- return l3gatewayserviceuuid;
- }
-
- /////////////////////////////////////////////////////
- /////////////// API Implementation///////////////////
- /////////////////////////////////////////////////////
-
- @Override
- public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
- ResourceAllocationException {
- try {
- NiciraNvpDeviceVO niciraNvpDeviceVO = niciraNvpElementService.addNiciraNvpDevice(this);
- if (niciraNvpDeviceVO != null) {
- NiciraNvpDeviceResponse response = niciraNvpElementService.createNiciraNvpDeviceResponse(niciraNvpDeviceVO);
- response.setObjectName("niciranvpdevice");
- response.setResponseName(getCommandName());
- setResponseObject(response);
- } else {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error.");
- }
- } catch (InvalidParameterValueException invalidParamExcp) {
- throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
- } catch (CloudRuntimeException runtimeExcp) {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
- }
- }
-
- @Override
- public String getCommandName() {
- return s_name;
- }
-
- @Override
- public long getEntityOwnerId() {
- return CallContext.current().getCallingAccount().getId();
- }
-
- @Override
- public String getEventType() {
- return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_ADD;
- }
-
- @Override
- public String getEventDescription() {
- return "Adding a Nicira Nvp Controller";
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java
deleted file mode 100644
index d3fadea..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java
+++ /dev/null
@@ -1,112 +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 com.cloud.api.commands;
-
-import javax.inject.Inject;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.ApiErrorCode;
-import org.apache.cloudstack.api.BaseAsyncCmd;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.response.SuccessResponse;
-import org.apache.cloudstack.context.CallContext;
-
-import com.cloud.api.response.NiciraNvpDeviceResponse;
-import com.cloud.event.EventTypes;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.ResourceAllocationException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.network.element.NiciraNvpElementService;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-@APICommand(name = "deleteNiciraNvpDevice", responseObject = SuccessResponse.class, description = " delete a nicira nvp device",
- requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
-public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd {
- private static final String s_name = "deleteniciranvpdeviceresponse";
- @Inject
- protected NiciraNvpElementService niciraNvpElementService;
-
- /////////////////////////////////////////////////////
- //////////////// API parameters /////////////////////
- /////////////////////////////////////////////////////
-
- @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID,
- type = CommandType.UUID,
- entityType = NiciraNvpDeviceResponse.class,
- required = true,
- description = "Nicira device ID")
- private Long niciraNvpDeviceId;
-
- /////////////////////////////////////////////////////
- /////////////////// Accessors ///////////////////////
- /////////////////////////////////////////////////////
-
- public Long getNiciraNvpDeviceId() {
- return niciraNvpDeviceId;
- }
-
- /////////////////////////////////////////////////////
- /////////////// API Implementation///////////////////
- /////////////////////////////////////////////////////
-
- @Override
- public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
- ResourceAllocationException {
- try {
- boolean result = niciraNvpElementService.deleteNiciraNvpDevice(this);
- if (result) {
- SuccessResponse response = new SuccessResponse(getCommandName());
- response.setResponseName(getCommandName());
- setResponseObject(response);
- } else {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Nicira device.");
- }
- } catch (InvalidParameterValueException invalidParamExcp) {
- throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
- } catch (CloudRuntimeException runtimeExcp) {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
- }
- }
-
- @Override
- public String getCommandName() {
- return s_name;
- }
-
- @Override
- public long getEntityOwnerId() {
- return CallContext.current().getCallingAccount().getId();
- }
-
- @Override
- public String getEventType() {
- return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_DELETE;
- }
-
- @Override
- public String getEventDescription() {
- return "Deleting Nicira Nvp Controller";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java
deleted file mode 100644
index a3217cc..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java
+++ /dev/null
@@ -1,111 +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 com.cloud.api.commands;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.inject.Inject;
-
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.ApiErrorCode;
-import org.apache.cloudstack.api.BaseListCmd;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.ResponseObject.ResponseView;
-import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.response.ListResponse;
-import org.apache.cloudstack.api.response.NetworkResponse;
-
-import com.cloud.api.response.NiciraNvpDeviceResponse;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.ResourceAllocationException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.network.Network;
-import com.cloud.network.element.NiciraNvpElementService;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-@APICommand(name = "listNiciraNvpDeviceNetworks", responseObject = NetworkResponse.class, description = "lists network that are using a nicira nvp device",
- requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
-public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd {
-
- public static final Logger s_logger = Logger.getLogger(ListNiciraNvpDeviceNetworksCmd.class.getName());
- private static final String s_name = "listniciranvpdevicenetworks";
- @Inject
- protected NiciraNvpElementService niciraNvpElementService;
-
- /////////////////////////////////////////////////////
- //////////////// API parameters /////////////////////
- /////////////////////////////////////////////////////
-
- @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID,
- type = CommandType.UUID,
- entityType = NiciraNvpDeviceResponse.class,
- required = true,
- description = "nicira nvp device ID")
- private Long niciraNvpDeviceId;
-
- /////////////////////////////////////////////////////
- /////////////////// Accessors ///////////////////////
- /////////////////////////////////////////////////////
-
- public Long getNiciraNvpDeviceId() {
- return niciraNvpDeviceId;
- }
-
- /////////////////////////////////////////////////////
- /////////////// API Implementation///////////////////
- /////////////////////////////////////////////////////
-
- @Override
- public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
- ResourceAllocationException {
- try {
- List<? extends Network> networks = niciraNvpElementService.listNiciraNvpDeviceNetworks(this);
- ListResponse<NetworkResponse> response = new ListResponse<NetworkResponse>();
- List<NetworkResponse> networkResponses = new ArrayList<NetworkResponse>();
-
- if (networks != null && !networks.isEmpty()) {
- for (Network network : networks) {
- NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Full, network);
- networkResponses.add(networkResponse);
- }
- }
-
- response.setResponses(networkResponses);
- response.setResponseName(getCommandName());
- setResponseObject(response);
- } catch (InvalidParameterValueException invalidParamExcp) {
- throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
- } catch (CloudRuntimeException runtimeExcp) {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
- }
- }
-
- @Override
- public String getCommandName() {
- return s_name;
- }
-
-}
[44/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Add basic RestClient implentation based on HTTP Components 4.5
- Upgrade version of HTTP Components to 4.5
- Add helper class to create Http clients
- Add helper class to build http requests
- Add enum with the different Http Methods
- Add constants class for HTTP related values
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/8a93bb8d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/8a93bb8d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/8a93bb8d
Branch: refs/heads/deploy-from-snapshot
Commit: 8a93bb8d2dc85dc6382e373744f8e7c6a9593fb1
Parents: 6e74ef8
Author: Miguel Ferreira <mi...@me.com>
Authored: Fri Aug 21 17:44:57 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:13 2015 +0200
----------------------------------------------------------------------
pom.xml | 2 +-
.../com/cloud/utils/rest/BasicRestClient.java | 118 ++++++++++++++++
.../com/cloud/utils/rest/HttpClientHelper.java | 71 ++++++++++
.../com/cloud/utils/rest/HttpConstants.java | 34 +++++
.../java/com/cloud/utils/rest/HttpMethods.java | 41 ++++++
.../cloud/utils/rest/HttpUriRequestBuilder.java | 119 ++++++++++++++++
.../java/com/cloud/utils/rest/RestClient.java | 31 ++++
.../cloud/utils/rest/BasicRestClientTest.java | 106 ++++++++++++++
.../cloud/utils/rest/HttpClientHelperTest.java | 38 +++++
.../cloud/utils/rest/HttpRequestMatcher.java | 141 +++++++++++++++++++
.../utils/rest/HttpUriRequestBuilderTest.java | 115 +++++++++++++++
.../utils/rest/HttpUriRequestQueryMatcher.java | 48 +++++++
12 files changed, 863 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 95b90db..b5e380e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -77,7 +77,7 @@
<cs.guava-testlib.version>18.0</cs.guava-testlib.version>
<cs.guava.version>18.0</cs.guava.version>
<cs.xapi.version>6.2.0-3.1</cs.xapi.version>
- <cs.httpclient.version>4.3.6</cs.httpclient.version>
+ <cs.httpclient.version>4.5</cs.httpclient.version>
<cs.httpcore.version>4.4</cs.httpcore.version>
<cs.commons-httpclient.version>3.1</cs.commons-httpclient.version>
<cs.mysql.version>5.1.34</cs.mysql.version>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java b/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java
new file mode 100644
index 0000000..5c29155
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java
@@ -0,0 +1,118 @@
+//
+// 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 com.cloud.utils.rest;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.http.HttpHost;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.log4j.Logger;
+
+public class BasicRestClient implements RestClient {
+
+ private static final Logger s_logger = Logger.getLogger(BasicRestClient.class);
+
+ private static final String HTTPS = HttpConstants.HTTPS;
+ private static final int HTTPS_PORT = HttpConstants.HTTPS_PORT;
+
+ private final CloseableHttpClient client;
+ private final HttpClientContext clientContext;
+
+ private BasicRestClient(final Builder<?> builder) {
+ client = builder.client;
+ clientContext = builder.clientContext;
+ clientContext.setTargetHost(buildHttpHost(builder.host));
+ }
+
+ protected BasicRestClient(final CloseableHttpClient client, final HttpClientContext clientContex, final String host) {
+ this.client = client;
+ clientContext = clientContex;
+ clientContext.setTargetHost(buildHttpHost(host));
+ }
+
+ private static HttpHost buildHttpHost(final String host) {
+ return new HttpHost(host, HTTPS_PORT, HTTPS);
+ }
+
+ @SuppressWarnings("rawtypes")
+ public static Builder create() {
+ return new Builder();
+ }
+
+ @Override
+ public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException {
+ logRequestExecution(request);
+ try {
+ return client.execute(clientContext.getTargetHost(), request, clientContext);
+ } catch (final IOException e) {
+ throw new CloudstackRESTException("Could not execute request " + request, e);
+ }
+ }
+
+ private void logRequestExecution(final HttpUriRequest request) {
+ final URI uri = request.getURI();
+ String query = uri.getQuery();
+ query = query != null ? "?" + query : "";
+ s_logger.debug("Executig " + request.getMethod() + " request on " + clientContext.getTargetHost() + uri.getPath() + query);
+ }
+
+ @Override
+ public void closeResponse(final CloseableHttpResponse response) throws CloudstackRESTException {
+ try {
+ s_logger.debug("Closing HTTP connection");
+ response.close();
+ } catch (final IOException e) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("Failed to close response object for request.\nResponse: ").append(response);
+ throw new CloudstackRESTException(sb.toString(), e);
+ }
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected static class Builder<T extends Builder> {
+ private CloseableHttpClient client;
+ private HttpClientContext clientContext = HttpClientContext.create();
+ private String host;
+
+ public T client(final CloseableHttpClient client) {
+ this.client = client;
+ return (T) this;
+ }
+
+ public T clientContext(final HttpClientContext clientContext) {
+ this.clientContext = clientContext;
+ return (T) this;
+ }
+
+ public T host(final String host) {
+ this.host = host;
+ return (T) this;
+ }
+
+ public BasicRestClient build() {
+ return new BasicRestClient(this);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java b/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java
new file mode 100644
index 0000000..1c6f564
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java
@@ -0,0 +1,71 @@
+//
+// 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 com.cloud.utils.rest;
+
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+
+import javax.net.ssl.SSLContext;
+
+import org.apache.http.client.config.CookieSpecs;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
+import org.apache.http.impl.client.BasicCookieStore;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.LaxRedirectStrategy;
+import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.ssl.SSLContexts;
+
+public class HttpClientHelper {
+
+ private static final String HTTPS = HttpConstants.HTTPS;
+
+ public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
+ final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
+ final BasicCookieStore cookieStore = new BasicCookieStore();
+ return HttpClientBuilder.create()
+ .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
+ .setRedirectStrategy(new LaxRedirectStrategy())
+ .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setMaxRedirects(maxRedirects).build())
+ .setDefaultCookieStore(cookieStore)
+ .setRetryHandler(new StandardHttpRequestRetryHandler())
+ .build();
+ }
+
+ private static Registry<ConnectionSocketFactory> createSocketFactoryConfigration() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
+ Registry<ConnectionSocketFactory> socketFactoryRegistry;
+ final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
+ final SSLConnectionSocketFactory cnnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
+ socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
+ .register(HTTPS, cnnectionSocketFactory)
+ .build();
+
+ return socketFactoryRegistry;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java b/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java
new file mode 100644
index 0000000..93502a5
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.rest;
+
+public class HttpConstants {
+
+ public static final int HTTPS_PORT = 443;
+ public static final String HTTPS = "https";
+ public static final String GET_METHOD_TYPE = "get";
+ public static final String DELETE_METHOD_TYPE = "delete";
+ public static final String PUT_METHOD_TYPE = "put";
+ public static final String POST_METHOD_TYPE = "post";
+ public static final String TEXT_HTML_CONTENT_TYPE = "text/html";
+ public static final String JSON_CONTENT_TYPE = "application/json";
+ public static final String CONTENT_TYPE = "Content-Type";
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java b/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java
new file mode 100644
index 0000000..7fecad0
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java
@@ -0,0 +1,41 @@
+//
+// 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 com.cloud.utils.rest;
+
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+
+public enum HttpMethods {
+
+ GET(HttpGet.METHOD_NAME), POST(HttpPost.METHOD_NAME), PUT(HttpPut.METHOD_NAME), DELETE(HttpDelete.METHOD_NAME);
+
+ private final String name;
+
+ private HttpMethods(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java b/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java
new file mode 100644
index 0000000..4fb3a1d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java
@@ -0,0 +1,119 @@
+//
+// 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 com.cloud.utils.rest;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.http.Consts;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.methods.RequestBuilder;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.message.BasicHeader;
+import org.springframework.util.Assert;
+
+import com.google.common.base.Optional;
+
+public class HttpUriRequestBuilder {
+
+ private static final String CONTENT_TYPE = HttpConstants.CONTENT_TYPE;
+ private static final String JSON_CONTENT_TYPE = HttpConstants.JSON_CONTENT_TYPE;
+
+ private static final Optional<String> ABSENT = Optional.absent();
+
+ private HttpMethods method;
+ private String path;
+ private Optional<String> jsonPayload = ABSENT;
+ private final Map<String, String> parameters = new HashMap<String, String>();
+ private final Map<String, String> methodParameters = new HashMap<String, String>();
+
+ private HttpUriRequestBuilder() {
+
+ }
+
+ public static HttpUriRequestBuilder create() {
+ return new HttpUriRequestBuilder();
+ }
+
+ public HttpUriRequestBuilder method(final HttpMethods method) {
+ this.method = method;
+ return this;
+ }
+
+ public HttpUriRequestBuilder path(final String path) {
+ this.path = path;
+ return this;
+ }
+
+ public HttpUriRequestBuilder jsonPayload(final Optional<String> jsonPayload) {
+ this.jsonPayload = jsonPayload;
+ return this;
+ }
+
+ public HttpUriRequestBuilder parameters(final Map<String, String> parameters) {
+ this.parameters.clear();
+ this.parameters.putAll(parameters);
+ return this;
+ }
+
+ public HttpUriRequestBuilder methodParameters(final Map<String, String> methodParameters) {
+ this.methodParameters.clear();
+ this.methodParameters.putAll(methodParameters);
+ return this;
+ }
+
+ public HttpUriRequest build() {
+ validate();
+ final RequestBuilder builder = RequestBuilder.create(method.toString()).setUri(buildUri());
+ if (!methodParameters.isEmpty()) {
+ for (final Entry<String, String> entry : methodParameters.entrySet()) {
+ builder.addParameter(entry.getKey(), entry.getValue());
+ }
+ }
+ if (jsonPayload.isPresent()) {
+ builder.addHeader(new BasicHeader(CONTENT_TYPE, JSON_CONTENT_TYPE))
+ .setEntity(new StringEntity(jsonPayload.get(), ContentType.create(JSON_CONTENT_TYPE, Consts.UTF_8)));
+ }
+ return builder.build();
+ }
+
+ private void validate() {
+ Assert.notNull(method, "HTTP Method cannot be null");
+ Assert.hasText(path, "target path must be defined");
+ Assert.isTrue(path.startsWith("/"), "targte path must start with a '/' character");
+ }
+
+ private URI buildUri() {
+ try {
+ final URIBuilder builder = new URIBuilder().setPath(path);
+ for (final Map.Entry<String, String> entry : parameters.entrySet()) {
+ builder.addParameter(entry.getKey(), entry.getValue());
+ }
+ return builder.build();
+ } catch (final URISyntaxException e) {
+ throw new IllegalArgumentException("Unable to build REST Service URI", e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/main/java/com/cloud/utils/rest/RestClient.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RestClient.java b/utils/src/main/java/com/cloud/utils/rest/RestClient.java
new file mode 100644
index 0000000..104f09b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/rest/RestClient.java
@@ -0,0 +1,31 @@
+//
+// 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 com.cloud.utils.rest;
+
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+
+public interface RestClient {
+
+ public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException;
+
+ public void closeResponse(final CloseableHttpResponse response) throws CloudstackRESTException;
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java b/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java
new file mode 100644
index 0000000..c30103e
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java
@@ -0,0 +1,106 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.sameInstance;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import org.apache.http.HttpHost;
+import org.apache.http.ProtocolVersion;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.message.BasicStatusLine;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class BasicRestClientTest {
+
+ private static final String LOCALHOST = "localhost";
+ private static final String HTTPS = HttpConstants.HTTPS;
+
+ private static final StatusLine HTTP_200_REPSONSE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 200, "OK");
+ private static final StatusLine HTTP_503_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 503, "Service unavailable");
+
+ private static final CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
+
+ private static CloseableHttpClient httpClient;
+ private static HttpUriRequest request;
+
+ @BeforeClass
+ public static void setupClass() throws Exception {
+ request = HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("/path")
+ .build();
+ httpClient = spy(HttpClientHelper.createHttpClient(2));
+ }
+
+ @Test
+ public void testExecuteRequest() throws Exception {
+ when(mockResponse.getStatusLine()).thenReturn(HTTP_200_REPSONSE);
+ doReturn(mockResponse).when(httpClient).execute(any(HttpHost.class), HttpRequestMatcher.eq(request), any(HttpClientContext.class));
+ final BasicRestClient restClient = BasicRestClient.create()
+ .host(LOCALHOST)
+ .client(httpClient)
+ .build();
+
+ final CloseableHttpResponse response = restClient.execute(request);
+
+ assertThat(response, notNullValue());
+ assertThat(response, sameInstance(mockResponse));
+ assertThat(response.getStatusLine(), sameInstance(HTTP_200_REPSONSE));
+ }
+
+ @Test
+ public void testExecuteRequestStatusCodeIsNotOk() throws Exception {
+ when(mockResponse.getStatusLine()).thenReturn(HTTP_503_STATUSLINE);
+ doReturn(mockResponse).when(httpClient).execute(any(HttpHost.class), HttpRequestMatcher.eq(request), any(HttpClientContext.class));
+ final BasicRestClient restClient = BasicRestClient.create()
+ .host(LOCALHOST)
+ .client(httpClient)
+ .build();
+
+ final CloseableHttpResponse response = restClient.execute(request);
+
+ assertThat(response, notNullValue());
+ assertThat(response, sameInstance(mockResponse));
+ assertThat(response.getStatusLine(), sameInstance(HTTP_503_STATUSLINE));
+ }
+
+ @Test(expected = CloudstackRESTException.class)
+ public void testExecuteRequestWhenClientThrowsIOException() throws Exception {
+ final BasicRestClient restClient = BasicRestClient.create()
+ .host(LOCALHOST)
+ .client(HttpClientHelper.createHttpClient(5))
+ .build();
+
+ restClient.execute(request);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java b/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java
new file mode 100644
index 0000000..20b32dd
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.notNullValue;
+
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.junit.Test;
+
+public class HttpClientHelperTest {
+
+ @Test
+ public void testCreateClient() throws Exception {
+ int maxRedirects = 5;
+ final CloseableHttpClient client = HttpClientHelper.createHttpClient(maxRedirects);
+
+ assertThat(client, notNullValue());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java
new file mode 100644
index 0000000..effec79
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java
@@ -0,0 +1,141 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.mockito.Matchers.argThat;
+
+import java.io.IOException;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.http.HttpEntityEnclosingRequest;
+import org.apache.http.HttpRequest;
+import org.apache.http.ParseException;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.util.EntityUtils;
+import org.hamcrest.Description;
+import org.hamcrest.SelfDescribing;
+import org.mockito.ArgumentMatcher;
+
+public class HttpRequestMatcher extends ArgumentMatcher<HttpRequest> {
+ private final HttpRequest wanted;
+
+ public HttpRequestMatcher(final HttpRequest wanted) {
+ this.wanted = wanted;
+ }
+
+ public static HttpRequest eq(final HttpRequest request) {
+ return argThat(new HttpRequestMatcher(request));
+ }
+
+ @Override
+ public boolean matches(final Object actual) {
+ if (actual instanceof HttpUriRequest) {
+ final HttpUriRequest converted = (HttpUriRequest) actual;
+ return checkMethod(converted) && checkUri(converted) && checkPayload(converted);
+ } else {
+ return wanted == actual;
+ }
+ }
+
+ private boolean checkPayload(final HttpUriRequest actual) {
+ final String wantedPayload = getPayload(wanted);
+ final String actualPayload = getPayload(actual);
+ return equalsString(wantedPayload, actualPayload);
+ }
+
+ private static String getPayload(final HttpRequest request) {
+ String payload = "";
+ if (request instanceof HttpEntityEnclosingRequest) {
+ try {
+ payload = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
+ } catch (final ParseException e) {
+ throw new IllegalArgumentException("Couldn't read request's entity payload.", e);
+ } catch (final IOException e) {
+ throw new IllegalArgumentException("Couldn't read request's entity payload.", e);
+ }
+ }
+ return payload;
+ }
+
+ private boolean checkUri(final HttpUriRequest actual) {
+ if (wanted instanceof HttpUriRequest) {
+ final String wantedQuery = ((HttpUriRequest) wanted).getURI().getQuery();
+ final String actualQuery = actual.getURI().getQuery();
+ return equalsString(wantedQuery, actualQuery);
+ } else {
+ return wanted == actual;
+ }
+ }
+
+ private boolean checkMethod(final HttpUriRequest actual) {
+ if (wanted instanceof HttpUriRequest) {
+ final String wantedMethod = ((HttpUriRequest) wanted).getMethod();
+ final String actualMethod = actual.getMethod();
+ return equalsString(wantedMethod, actualMethod);
+ } else {
+ return wanted == actual;
+ }
+ }
+
+ private static boolean equalsString(final String a, final String b) {
+ return a == b || a != null && a.equals(b);
+ }
+
+ @Override
+ public void describeTo(final Description description) {
+ description.appendText(describe(wanted));
+ }
+
+ public String describe(final HttpRequest object) {
+ final StringBuilder sb = new StringBuilder();
+ if (object instanceof HttpUriRequest) {
+ final HttpUriRequest converted = (HttpUriRequest) object;
+ sb.append("method = ").append(converted.getMethod());
+ sb.append(", query = ").append(converted.getURI().getQuery());
+ sb.append(", payload = ").append(getPayload(object));
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ return EqualsBuilder.reflectionEquals(this, o);
+ }
+
+ @Override
+ public int hashCode() {
+ return HashCodeBuilder.reflectionHashCode(this);
+ }
+
+ public SelfDescribing withExtraTypeInfo() {
+ return new SelfDescribing() {
+ @Override
+ public void describeTo(final Description description) {
+ description.appendText("(" + wanted.getClass().getSimpleName() + ") ").appendText(describe(wanted));
+ }
+ };
+ }
+
+ public boolean typeMatches(final Object object) {
+ return wanted != null && object != null && object.getClass() == wanted.getClass();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java
new file mode 100644
index 0000000..470f563
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java
@@ -0,0 +1,115 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+
+import java.util.HashMap;
+
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.junit.Test;
+
+import com.google.common.base.Optional;
+
+public class HttpUriRequestBuilderTest {
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuildWithNullMethod() throws Exception {
+ HttpUriRequestBuilder.create().path("/path").build();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuildWithNullPath() throws Exception {
+ HttpUriRequestBuilder.create().method(HttpMethods.GET).build();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuildWithEmptyPath() throws Exception {
+ HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("")
+ .build();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuildWithIlegalPath() throws Exception {
+ HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("path")
+ .build();
+ }
+
+ @Test
+ public void testBuildSimpleRequest() throws Exception {
+ final HttpUriRequest request = HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("/path")
+ .build();
+
+ assertThat(request, notNullValue());
+ assertThat(request.getURI().getPath(), equalTo("/path"));
+ assertThat(request.getURI().getScheme(), nullValue());
+ assertThat(request.getURI().getQuery(), nullValue());
+ assertThat(request.getURI().getHost(), nullValue());
+ assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME));
+ }
+
+ @Test
+ public void testBuildRequestWithParameters() throws Exception {
+ final HashMap<String, String> parameters = new HashMap<String, String>();
+ parameters.put("key1", "value1");
+ final HttpUriRequest request = HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("/path")
+ .parameters(parameters)
+ .build();
+
+ assertThat(request, notNullValue());
+ assertThat(request.getURI().getPath(), equalTo("/path"));
+ assertThat(request.getURI().getQuery(), equalTo("key1=value1"));
+ assertThat(request.getURI().getScheme(), nullValue());
+ assertThat(request.getURI().getHost(), nullValue());
+ assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME));
+ }
+
+ @Test
+ public void testBuildRequestWithJsonPayload() throws Exception {
+ final HttpUriRequest request = HttpUriRequestBuilder.create()
+ .method(HttpMethods.GET)
+ .path("/path")
+ .jsonPayload(Optional.of("{'key1':'value1'}"))
+ .build();
+
+ assertThat(request, notNullValue());
+ assertThat(request.getURI().getPath(), equalTo("/path"));
+ assertThat(request.getURI().getScheme(), nullValue());
+ assertThat(request.getURI().getQuery(), nullValue());
+ assertThat(request.getURI().getHost(), nullValue());
+ assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME));
+ assertThat(request.containsHeader(HttpConstants.CONTENT_TYPE), equalTo(true));
+ assertThat(request.getFirstHeader(HttpConstants.CONTENT_TYPE).getValue(), equalTo(HttpConstants.JSON_CONTENT_TYPE));
+ assertThat(request, HttpUriRequestPayloadMatcher.hasPayload("{'key1':'value1'}"));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8a93bb8d/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java
new file mode 100644
index 0000000..e73641b
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java
@@ -0,0 +1,48 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.mockito.Matchers.argThat;
+
+import org.apache.http.client.methods.HttpUriRequest;
+import org.hamcrest.FeatureMatcher;
+import org.hamcrest.Matcher;
+
+public class HttpUriRequestQueryMatcher extends FeatureMatcher<HttpUriRequest, String> {
+
+ public static HttpUriRequest aQuery(final String query) {
+ return argThat(new HttpUriRequestQueryMatcher(equalTo(query), "query", "query"));
+ }
+
+ public static HttpUriRequest aQueryThatContains(final String query) {
+ return argThat(new HttpUriRequestQueryMatcher(containsString(query), "query", "query"));
+ }
+
+ public HttpUriRequestQueryMatcher(final Matcher<? super String> subMatcher, final String featureDescription, final String featureName) {
+ super(subMatcher, featureDescription, featureName);
+ }
+
+ @Override
+ protected String featureValueOf(final HttpUriRequest actual) {
+ return actual.getURI().getQuery();
+ }
+}
[50/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Merge pull request #737 from miguelaferreira/feature/mferreira/ncx-follow-redirects-gardened-rebase
CLOUDSTACK-8758: Handle redirects in communication with NXS controller (a.k.a. Nicira NVP)When an NSX controller node is part of a cluster it will redirect API calls to the master controller. Because the ACS management server does not follow such redirects, if there is a change of master within a NSX cluster, the NSX device (a.k.a. NiciraNvp) needs to be reconfigured (via the management server DB).
The goal of this PR is to enable ACS management server to follow HTTP redirects sent by NSX controllers. However, other changes were made to the cloud-utils module that provides the REST client that the NSX plugin uses.
Cosmetic changes:
* Upgrade maven module structure for cloud-utils and cloud-plugin-netowkr-nvp to comply with maven default
* Several refactorings on both modules to consistently format the code, remove unused code, declare final when possible, remove auto generated comments, etc
Other changes:
* Upgrade HTTP library used in REST client to version 4.5 of Apache HTTP Components
* Implement generic REST client that supports HTTP redirects
* Implement NSX specific REST client
* Simplify NSX api implementation
* Previously existing unit tests for both the REST client and NSX api were either maintained in the same test classes, moved to new test classes (because code under tests also moved), or removed (because code under tests was also removed)
* New Marvin tests for NSX controllers
Testing:
* Ran all unit tests present in the project
* Ran Java Integration tests for NSX api targeting both a master and a slave controller
* Ran new Marvin test for NSX controller
* Manual inspection of logs to confirm redirection is taking place
* pr/737:
Use NSX specific RestClient in API implementation (NiciraNvpApi)
Refactor NSX api implementation (NiciraNvpApi)
Add NSX specific RestClient implementation
Delegate HTTP protocol activity in RESTServiceConnector to RestClient
Add basic RestClient implentation based on HTTP Components 4.5
Code clean up in cloud-plugin-network-nvp project
Code clean up in cloud-utils project
Refactor cloud-plugin-network-nvp project into Maven default structure
Refactor cloud-utils project into Maven default structure
Fix unit-test library dependencies
Add Marvin test for Nicira NVP plugin
Create Nicira NVP devices and enable plugin at deploy
Signed-off-by: Remi Bergsma <gi...@remi.nl>
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/44ba14d1
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/44ba14d1
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/44ba14d1
Branch: refs/heads/deploy-from-snapshot
Commit: 44ba14d17ba3b8fa00cd05c97eaceed49367816c
Parents: 2772e4d 09f7153
Author: Remi Bergsma <gi...@remi.nl>
Authored: Tue Aug 25 20:44:50 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Tue Aug 25 20:44:52 2015 +0200
----------------------------------------------------------------------
plugins/network-elements/nicira-nvp/pom.xml | 24 +-
.../META-INF/cloudstack/nvp/module.properties | 21 -
.../cloudstack/nvp/spring-nvp-context.xml | 42 -
...ortForwardingRulesOnLogicalRouterAnswer.java | 35 -
...rtForwardingRulesOnLogicalRouterCommand.java | 63 -
...ConfigurePublicIpsOnLogicalRouterAnswer.java | 32 -
...onfigurePublicIpsOnLogicalRouterCommand.java | 66 -
...gureStaticNatRulesOnLogicalRouterAnswer.java | 44 -
...ureStaticNatRulesOnLogicalRouterCommand.java | 65 -
.../agent/api/CreateLogicalRouterAnswer.java | 42 -
.../agent/api/CreateLogicalRouterCommand.java | 116 --
.../agent/api/CreateLogicalSwitchAnswer.java | 38 -
.../agent/api/CreateLogicalSwitchCommand.java | 57 -
.../api/CreateLogicalSwitchPortAnswer.java | 38 -
.../api/CreateLogicalSwitchPortCommand.java | 56 -
.../agent/api/DeleteLogicalRouterAnswer.java | 34 -
.../agent/api/DeleteLogicalRouterCommand.java | 44 -
.../agent/api/DeleteLogicalSwitchAnswer.java | 32 -
.../agent/api/DeleteLogicalSwitchCommand.java | 38 -
.../api/DeleteLogicalSwitchPortAnswer.java | 32 -
.../api/DeleteLogicalSwitchPortCommand.java | 44 -
.../agent/api/FindLogicalSwitchPortAnswer.java | 38 -
.../agent/api/FindLogicalSwitchPortCommand.java | 44 -
.../agent/api/StartupNiciraNvpCommand.java | 30 -
.../api/UpdateLogicalSwitchPortAnswer.java | 38 -
.../api/UpdateLogicalSwitchPortCommand.java | 63 -
.../api/commands/AddNiciraNvpDeviceCmd.java | 154 --
.../api/commands/DeleteNiciraNvpDeviceCmd.java | 112 --
.../ListNiciraNvpDeviceNetworksCmd.java | 111 --
.../api/commands/ListNiciraNvpDevicesCmd.java | 108 --
.../api/response/NiciraNvpDeviceResponse.java | 89 -
.../com/cloud/network/NiciraNvpDeviceVO.java | 99 --
.../cloud/network/NiciraNvpNicMappingVO.java | 87 -
.../cloud/network/NiciraNvpRouterMappingVO.java | 85 -
.../src/com/cloud/network/dao/NiciraNvpDao.java | 35 -
.../com/cloud/network/dao/NiciraNvpDaoImpl.java | 53 -
.../network/dao/NiciraNvpNicMappingDao.java | 32 -
.../network/dao/NiciraNvpNicMappingDaoImpl.java | 51 -
.../network/dao/NiciraNvpRouterMappingDao.java | 28 -
.../dao/NiciraNvpRouterMappingDaoImpl.java | 51 -
.../cloud/network/element/NiciraNvpElement.java | 849 ----------
.../element/NiciraNvpElementService.java | 45 -
.../network/guru/NiciraNvpGuestNetworkGuru.java | 256 ---
.../network/nicira/AccessConfiguration.java | 44 -
.../com/cloud/network/nicira/AccessRule.java | 58 -
.../src/com/cloud/network/nicira/Acl.java | 23 -
.../src/com/cloud/network/nicira/AclRule.java | 209 ---
.../com/cloud/network/nicira/Attachment.java | 24 -
.../cloud/network/nicira/BaseNiciraEntity.java | 85 -
.../network/nicira/BaseNiciraNamedEntity.java | 44 -
.../network/nicira/ControlClusterStatus.java | 87 -
.../network/nicira/DestinationNatRule.java | 113 --
.../network/nicira/L3GatewayAttachment.java | 55 -
.../com/cloud/network/nicira/LogicalRouter.java | 71 -
.../cloud/network/nicira/LogicalRouterPort.java | 62 -
.../com/cloud/network/nicira/LogicalSwitch.java | 60 -
.../cloud/network/nicira/LogicalSwitchPort.java | 82 -
.../src/com/cloud/network/nicira/Match.java | 146 --
.../src/com/cloud/network/nicira/NatRule.java | 130 --
.../com/cloud/network/nicira/NiciraNvpApi.java | 658 --------
.../network/nicira/NiciraNvpApiException.java | 39 -
.../com/cloud/network/nicira/NiciraNvpList.java | 48 -
.../com/cloud/network/nicira/NiciraNvpTag.java | 64 -
.../cloud/network/nicira/PatchAttachment.java | 41 -
.../com/cloud/network/nicira/RouterNextHop.java | 40 -
.../com/cloud/network/nicira/RoutingConfig.java | 24 -
.../nicira/RoutingTableRoutingConfig.java | 30 -
.../cloud/network/nicira/SecurityProfile.java | 24 -
.../com/cloud/network/nicira/SecurityRule.java | 138 --
...SingleDefaultRouteImplicitRoutingConfig.java | 40 -
.../com/cloud/network/nicira/SourceNatRule.java | 119 --
.../network/nicira/TransportZoneBinding.java | 50 -
.../com/cloud/network/nicira/VifAttachment.java | 78 -
.../resource/NiciraNvpRequestWrapper.java | 77 -
.../network/resource/NiciraNvpResource.java | 319 ----
.../network/resource/NiciraNvpUtilities.java | 65 -
...figurePortForwardingRulesCommandWrapper.java | 120 --
...ciraNvpConfigurePublicIpsCommandWrapper.java | 60 -
...vpConfigureStaticNatRulesCommandWrapper.java | 113 --
...iraNvpCreateLogicalRouterCommandWrapper.java | 152 --
...iraNvpCreateLogicalSwitchCommandWrapper.java | 73 -
...vpCreateLogicalSwitchPortCommandWrapper.java | 70 -
...iraNvpDeleteLogicalRouterCommandWrapper.java | 50 -
...iraNvpDeleteLogicalSwitchCommandWrapper.java | 49 -
...vpDeleteLogicalSwitchPortCommandWrapper.java | 50 -
...aNvpFindLogicalSwitchPortCommandWrapper.java | 59 -
.../NiciraNvpMaintainCommandWrapper.java | 36 -
.../wrapper/NiciraNvpReadyCommandWrapper.java | 36 -
...vpUpdateLogicalSwitchPortCommandWrapper.java | 68 -
.../network/utils/CommandRetryUtility.java | 89 -
...ortForwardingRulesOnLogicalRouterAnswer.java | 35 +
...rtForwardingRulesOnLogicalRouterCommand.java | 63 +
...ConfigurePublicIpsOnLogicalRouterAnswer.java | 32 +
...onfigurePublicIpsOnLogicalRouterCommand.java | 66 +
...gureStaticNatRulesOnLogicalRouterAnswer.java | 44 +
...ureStaticNatRulesOnLogicalRouterCommand.java | 65 +
.../agent/api/CreateLogicalRouterAnswer.java | 42 +
.../agent/api/CreateLogicalRouterCommand.java | 116 ++
.../agent/api/CreateLogicalSwitchAnswer.java | 38 +
.../agent/api/CreateLogicalSwitchCommand.java | 57 +
.../api/CreateLogicalSwitchPortAnswer.java | 38 +
.../api/CreateLogicalSwitchPortCommand.java | 56 +
.../agent/api/DeleteLogicalRouterAnswer.java | 34 +
.../agent/api/DeleteLogicalRouterCommand.java | 44 +
.../agent/api/DeleteLogicalSwitchAnswer.java | 32 +
.../agent/api/DeleteLogicalSwitchCommand.java | 38 +
.../api/DeleteLogicalSwitchPortAnswer.java | 32 +
.../api/DeleteLogicalSwitchPortCommand.java | 44 +
.../agent/api/FindLogicalSwitchPortAnswer.java | 38 +
.../agent/api/FindLogicalSwitchPortCommand.java | 44 +
.../agent/api/StartupNiciraNvpCommand.java | 30 +
.../api/UpdateLogicalSwitchPortAnswer.java | 38 +
.../api/UpdateLogicalSwitchPortCommand.java | 63 +
.../api/commands/AddNiciraNvpDeviceCmd.java | 154 ++
.../api/commands/DeleteNiciraNvpDeviceCmd.java | 112 ++
.../ListNiciraNvpDeviceNetworksCmd.java | 111 ++
.../api/commands/ListNiciraNvpDevicesCmd.java | 108 ++
.../api/response/NiciraNvpDeviceResponse.java | 89 +
.../com/cloud/network/NiciraNvpDeviceVO.java | 99 ++
.../cloud/network/NiciraNvpNicMappingVO.java | 87 +
.../cloud/network/NiciraNvpRouterMappingVO.java | 85 +
.../com/cloud/network/dao/NiciraNvpDao.java | 35 +
.../com/cloud/network/dao/NiciraNvpDaoImpl.java | 53 +
.../network/dao/NiciraNvpNicMappingDao.java | 32 +
.../network/dao/NiciraNvpNicMappingDaoImpl.java | 51 +
.../network/dao/NiciraNvpRouterMappingDao.java | 28 +
.../dao/NiciraNvpRouterMappingDaoImpl.java | 51 +
.../cloud/network/element/NiciraNvpElement.java | 849 ++++++++++
.../element/NiciraNvpElementService.java | 45 +
.../network/guru/NiciraNvpGuestNetworkGuru.java | 251 +++
.../network/nicira/AccessConfiguration.java | 44 +
.../com/cloud/network/nicira/AccessRule.java | 58 +
.../main/java/com/cloud/network/nicira/Acl.java | 23 +
.../java/com/cloud/network/nicira/AclRule.java | 209 +++
.../com/cloud/network/nicira/Attachment.java | 24 +
.../cloud/network/nicira/BaseNiciraEntity.java | 85 +
.../network/nicira/BaseNiciraNamedEntity.java | 44 +
.../network/nicira/ControlClusterStatus.java | 87 +
.../network/nicira/DestinationNatRule.java | 113 ++
.../cloud/network/nicira/ExecutionCounter.java | 50 +
.../network/nicira/L3GatewayAttachment.java | 55 +
.../com/cloud/network/nicira/LogicalRouter.java | 71 +
.../cloud/network/nicira/LogicalRouterPort.java | 62 +
.../com/cloud/network/nicira/LogicalSwitch.java | 60 +
.../cloud/network/nicira/LogicalSwitchPort.java | 82 +
.../java/com/cloud/network/nicira/Match.java | 146 ++
.../java/com/cloud/network/nicira/NatRule.java | 130 ++
.../cloud/network/nicira/NatRuleAdapter.java | 49 +
.../cloud/network/nicira/NiciraConstants.java | 42 +
.../com/cloud/network/nicira/NiciraNvpApi.java | 627 +++++++
.../network/nicira/NiciraNvpApiException.java | 39 +
.../com/cloud/network/nicira/NiciraNvpList.java | 48 +
.../com/cloud/network/nicira/NiciraNvpTag.java | 64 +
.../cloud/network/nicira/NiciraRestClient.java | 202 +++
.../cloud/network/nicira/PatchAttachment.java | 41 +
.../com/cloud/network/nicira/RouterNextHop.java | 40 +
.../com/cloud/network/nicira/RoutingConfig.java | 24 +
.../network/nicira/RoutingConfigAdapter.java | 52 +
.../nicira/RoutingTableRoutingConfig.java | 30 +
.../cloud/network/nicira/SecurityProfile.java | 24 +
.../com/cloud/network/nicira/SecurityRule.java | 138 ++
...SingleDefaultRouteImplicitRoutingConfig.java | 40 +
.../com/cloud/network/nicira/SourceNatRule.java | 119 ++
.../network/nicira/TransportZoneBinding.java | 50 +
.../com/cloud/network/nicira/VifAttachment.java | 78 +
.../resource/NiciraNvpRequestWrapper.java | 77 +
.../network/resource/NiciraNvpResource.java | 335 ++++
.../network/resource/NiciraNvpUtilities.java | 65 +
...figurePortForwardingRulesCommandWrapper.java | 122 ++
...ciraNvpConfigurePublicIpsCommandWrapper.java | 61 +
...vpConfigureStaticNatRulesCommandWrapper.java | 114 ++
...iraNvpCreateLogicalRouterCommandWrapper.java | 152 ++
...iraNvpCreateLogicalSwitchCommandWrapper.java | 73 +
...vpCreateLogicalSwitchPortCommandWrapper.java | 70 +
...iraNvpDeleteLogicalRouterCommandWrapper.java | 50 +
...iraNvpDeleteLogicalSwitchCommandWrapper.java | 49 +
...vpDeleteLogicalSwitchPortCommandWrapper.java | 50 +
...aNvpFindLogicalSwitchPortCommandWrapper.java | 60 +
.../NiciraNvpMaintainCommandWrapper.java | 36 +
.../wrapper/NiciraNvpReadyCommandWrapper.java | 36 +
...vpUpdateLogicalSwitchPortCommandWrapper.java | 68 +
.../network/utils/CommandRetryUtility.java | 89 +
.../META-INF/cloudstack/nvp/module.properties | 21 +
.../cloudstack/nvp/spring-nvp-context.xml | 42 +
.../network/element/NiciraNvpElementTest.java | 217 +++
.../guru/NiciraNvpGuestNetworkGuruTest.java | 476 ++++++
.../network/nicira/ExecutionCounterTest.java | 55 +
.../network/nicira/NatRuleAdapterTest.java | 60 +
.../com/cloud/network/nicira/NatRuleTest.java | 55 +
.../cloud/network/nicira/NiciraNvpApiIT.java | 319 ++++
.../cloud/network/nicira/NiciraNvpApiTest.java | 198 +++
.../network/nicira/NiciraRestClientTest.java | 172 ++
.../com/cloud/network/nicira/NiciraTagTest.java | 58 +
.../nicira/RoutingConfigAdapterTest.java | 57 +
.../resource/NiciraNvpRequestWrapperTest.java | 250 +++
.../network/resource/NiciraNvpResourceTest.java | 829 ++++++++++
.../src/test/resources/config.properties | 23 +
.../network/element/NiciraNvpElementTest.java | 217 ---
.../guru/NiciraNvpGuestNetworkGuruTest.java | 476 ------
.../com/cloud/network/nicira/NatRuleTest.java | 55 -
.../cloud/network/nicira/NiciraNvpApiIT.java | 347 ----
.../cloud/network/nicira/NiciraNvpApiTest.java | 339 ----
.../com/cloud/network/nicira/NiciraTagTest.java | 58 -
.../resource/NiciraNvpRequestWrapperTest.java | 255 ---
.../network/resource/NiciraNvpResourceTest.java | 882 ----------
.../nicira-nvp/test/resources/config.properties | 23 -
pom.xml | 169 +-
.../integration/smoke/test_nicira_controller.py | 310 ++++
tools/marvin/marvin/cloudstackTestCase.py | 4 +
tools/marvin/marvin/deployDataCenter.py | 112 +-
tools/marvin/marvin/lib/base.py | 46 +
utils/certs/cloud.keystore | Bin 1316 -> 0 bytes
utils/pom.xml | 44 +-
utils/src/com/cloud/maint/Version.java | 77 -
utils/src/com/cloud/utils/ActionDelegate.java | 24 -
.../src/com/cloud/utils/AutoCloseableUtil.java | 36 -
.../com/cloud/utils/CloudResourceBundle.java | 48 -
.../com/cloud/utils/ConstantTimeComparator.java | 42 -
utils/src/com/cloud/utils/DateUtil.java | 274 ----
utils/src/com/cloud/utils/EncryptionUtil.java | 73 -
utils/src/com/cloud/utils/EnumUtils.java | 58 -
utils/src/com/cloud/utils/ExecutionResult.java | 46 -
utils/src/com/cloud/utils/FileUtil.java | 32 -
utils/src/com/cloud/utils/HttpUtils.java | 114 --
utils/src/com/cloud/utils/IteratorUtil.java | 72 -
utils/src/com/cloud/utils/Journal.java | 104 --
utils/src/com/cloud/utils/LogUtils.java | 45 -
utils/src/com/cloud/utils/MethodCapturer.java | 113 --
utils/src/com/cloud/utils/NumbersUtil.java | 139 --
utils/src/com/cloud/utils/Pair.java | 87 -
.../src/com/cloud/utils/PasswordGenerator.java | 90 -
utils/src/com/cloud/utils/Predicate.java | 24 -
utils/src/com/cloud/utils/ProcessUtil.java | 112 --
utils/src/com/cloud/utils/Profiler.java | 91 -
utils/src/com/cloud/utils/PropertiesUtil.java | 196 ---
utils/src/com/cloud/utils/ReflectUtil.java | 213 ---
utils/src/com/cloud/utils/ReflectionUse.java | 31 -
utils/src/com/cloud/utils/S3Utils.java | 603 -------
utils/src/com/cloud/utils/SerialVersionUID.java | 69 -
utils/src/com/cloud/utils/StringUtils.java | 323 ----
utils/src/com/cloud/utils/SwiftUtil.java | 239 ---
utils/src/com/cloud/utils/Ternary.java | 85 -
utils/src/com/cloud/utils/UriUtils.java | 394 -----
.../cloud/utils/UsernamePasswordValidator.java | 49 -
utils/src/com/cloud/utils/UuidUtils.java | 34 -
.../cloud/utils/backoff/BackoffAlgorithm.java | 38 -
.../utils/backoff/impl/ConstantTimeBackoff.java | 102 --
.../backoff/impl/ConstantTimeBackoffMBean.java | 35 -
.../utils/cisco/n1kv/vsm/NetconfHelper.java | 355 ----
.../cloud/utils/cisco/n1kv/vsm/PolicyMap.java | 34 -
.../cloud/utils/cisco/n1kv/vsm/PortProfile.java | 48 -
.../cloud/utils/cisco/n1kv/vsm/VsmCommand.java | 999 -----------
.../utils/cisco/n1kv/vsm/VsmOkResponse.java | 44 -
.../cisco/n1kv/vsm/VsmPolicyMapResponse.java | 84 -
.../cisco/n1kv/vsm/VsmPortProfileResponse.java | 166 --
.../cloud/utils/cisco/n1kv/vsm/VsmResponse.java | 222 ---
.../src/com/cloud/utils/component/Adapter.java | 27 -
.../com/cloud/utils/component/AdapterBase.java | 40 -
.../com/cloud/utils/component/AdapterList.java | 37 -
.../cloud/utils/component/ComponentContext.java | 282 ----
.../ComponentInstantiationPostProcessor.java | 149 --
.../utils/component/ComponentLifecycle.java | 64 -
.../utils/component/ComponentLifecycleBase.java | 87 -
.../component/ComponentMethodInterceptable.java | 27 -
.../component/ComponentMethodInterceptor.java | 32 -
.../utils/component/ComponentNamingPolicy.java | 65 -
.../src/com/cloud/utils/component/Manager.java | 27 -
.../com/cloud/utils/component/ManagerBase.java | 28 -
utils/src/com/cloud/utils/component/Named.java | 26 -
.../cloud/utils/component/PluggableService.java | 29 -
.../src/com/cloud/utils/component/Registry.java | 51 -
.../utils/component/SystemIntegrityChecker.java | 30 -
.../utils/concurrency/NamedThreadFactory.java | 38 -
.../com/cloud/utils/concurrency/Scheduler.java | 31 -
.../utils/concurrency/SynchronizationEvent.java | 89 -
.../com/cloud/utils/concurrency/TestClock.java | 161 --
.../com/cloud/utils/crypt/DBEncryptionUtil.java | 87 -
.../utils/crypt/EncryptionSecretKeyChecker.java | 146 --
.../utils/crypt/EncryptionSecretKeySender.java | 65 -
utils/src/com/cloud/utils/crypt/RSAHelper.java | 90 -
utils/src/com/cloud/utils/db/DbProperties.java | 109 --
utils/src/com/cloud/utils/db/EntityManager.java | 84 -
utils/src/com/cloud/utils/db/UUIDManager.java | 48 -
.../com/cloud/utils/encoding/URLEncoder.java | 113 --
utils/src/com/cloud/utils/events/EventArgs.java | 44 -
.../com/cloud/utils/events/SubscriptionMgr.java | 164 --
.../utils/exception/CSExceptionErrorCode.java | 100 --
.../utils/exception/CloudRuntimeException.java | 141 --
.../com/cloud/utils/exception/ErrorContext.java | 31 -
.../utils/exception/ExceptionProxyObject.java | 55 -
.../cloud/utils/exception/ExceptionUtil.java | 54 -
.../utils/exception/ExecutionException.java | 49 -
.../HypervisorVersionChangedException.java | 35 -
utils/src/com/cloud/utils/fsm/ChangeEvent.java | 24 -
utils/src/com/cloud/utils/fsm/FiniteState.java | 58 -
utils/src/com/cloud/utils/fsm/FiniteState2.java | 34 -
.../com/cloud/utils/fsm/FiniteStateObject.java | 25 -
.../cloud/utils/fsm/NoTransitionException.java | 36 -
utils/src/com/cloud/utils/fsm/State.java | 27 -
utils/src/com/cloud/utils/fsm/StateDao.java | 25 -
.../src/com/cloud/utils/fsm/StateListener.java | 43 -
utils/src/com/cloud/utils/fsm/StateMachine.java | 147 --
.../src/com/cloud/utils/fsm/StateMachine2.java | 261 ---
utils/src/com/cloud/utils/fsm/StateObject.java | 27 -
.../cloud/utils/log/CglibThrowableRenderer.java | 84 -
utils/src/com/cloud/utils/mgmt/JmxUtil.java | 90 -
.../com/cloud/utils/mgmt/ManagementBean.java | 27 -
.../utils/mgmt/PropertyMapDynamicBean.java | 120 --
utils/src/com/cloud/utils/net/Ip.java | 98 --
utils/src/com/cloud/utils/net/Ip4Address.java | 80 -
utils/src/com/cloud/utils/net/MacAddress.java | 367 -----
utils/src/com/cloud/utils/net/NetUtils.java | 1550 ------------------
utils/src/com/cloud/utils/net/NfsUtils.java | 55 -
utils/src/com/cloud/utils/net/UrlUtil.java | 63 -
.../src/com/cloud/utils/nio/HandlerFactory.java | 28 -
utils/src/com/cloud/utils/nio/Link.java | 567 -------
utils/src/com/cloud/utils/nio/NioClient.java | 125 --
.../src/com/cloud/utils/nio/NioConnection.java | 476 ------
utils/src/com/cloud/utils/nio/NioServer.java | 97 --
utils/src/com/cloud/utils/nio/Task.java | 89 -
.../com/cloud/utils/nio/TrustAllManager.java | 45 -
.../BasicEncodedRESTValidationStrategy.java | 66 -
.../utils/rest/CloudstackRESTException.java | 39 -
.../cloud/utils/rest/RESTServiceConnector.java | 395 -----
.../utils/rest/RESTValidationStrategy.java | 165 --
.../cloud/utils/script/OutputInterpreter.java | 141 --
utils/src/com/cloud/utils/script/Script.java | 502 ------
utils/src/com/cloud/utils/script/Script2.java | 70 -
.../cloud/utils/security/CertificateHelper.java | 166 --
utils/src/com/cloud/utils/ssh/SSHCmdHelper.java | 179 --
.../src/com/cloud/utils/ssh/SSHKeysHelper.java | 115 --
utils/src/com/cloud/utils/ssh/SshException.java | 30 -
utils/src/com/cloud/utils/ssh/SshHelper.java | 209 ---
.../storage/encoding/DecodedDataObject.java | 56 -
.../storage/encoding/DecodedDataStore.java | 68 -
.../cloud/utils/storage/encoding/Decoder.java | 66 -
.../utils/storage/encoding/EncodingType.java | 32 -
.../com/cloud/utils/time/InaccurateClock.java | 102 --
.../cloud/utils/time/InaccurateClockMBean.java | 28 -
.../com/cloud/utils/xmlobject/XmlObject.java | 214 ---
.../cloud/utils/xmlobject/XmlObjectParser.java | 128 --
.../src/main/java/com/cloud/maint/Version.java | 77 +
.../java/com/cloud/utils/ActionDelegate.java | 24 +
.../java/com/cloud/utils/AutoCloseableUtil.java | 36 +
.../com/cloud/utils/CloudResourceBundle.java | 48 +
.../com/cloud/utils/ConstantTimeComparator.java | 42 +
.../src/main/java/com/cloud/utils/DateUtil.java | 274 ++++
.../java/com/cloud/utils/EncryptionUtil.java | 73 +
.../main/java/com/cloud/utils/EnumUtils.java | 58 +
.../java/com/cloud/utils/ExecutionResult.java | 46 +
.../src/main/java/com/cloud/utils/FileUtil.java | 32 +
.../main/java/com/cloud/utils/HttpUtils.java | 114 ++
.../main/java/com/cloud/utils/IteratorUtil.java | 72 +
.../src/main/java/com/cloud/utils/Journal.java | 104 ++
.../src/main/java/com/cloud/utils/LogUtils.java | 45 +
.../java/com/cloud/utils/MethodCapturer.java | 113 ++
.../main/java/com/cloud/utils/NumbersUtil.java | 139 ++
utils/src/main/java/com/cloud/utils/Pair.java | 87 +
.../java/com/cloud/utils/PasswordGenerator.java | 90 +
.../main/java/com/cloud/utils/Predicate.java | 24 +
.../main/java/com/cloud/utils/ProcessUtil.java | 112 ++
.../src/main/java/com/cloud/utils/Profiler.java | 91 +
.../java/com/cloud/utils/PropertiesUtil.java | 196 +++
.../main/java/com/cloud/utils/ReflectUtil.java | 213 +++
.../java/com/cloud/utils/ReflectionUse.java | 31 +
.../src/main/java/com/cloud/utils/S3Utils.java | 603 +++++++
.../java/com/cloud/utils/SerialVersionUID.java | 69 +
.../main/java/com/cloud/utils/StringUtils.java | 323 ++++
.../main/java/com/cloud/utils/SwiftUtil.java | 239 +++
.../src/main/java/com/cloud/utils/Ternary.java | 85 +
.../src/main/java/com/cloud/utils/UriUtils.java | 394 +++++
.../cloud/utils/UsernamePasswordValidator.java | 49 +
.../main/java/com/cloud/utils/UuidUtils.java | 34 +
.../cloud/utils/backoff/BackoffAlgorithm.java | 38 +
.../utils/backoff/impl/ConstantTimeBackoff.java | 102 ++
.../backoff/impl/ConstantTimeBackoffMBean.java | 35 +
.../utils/cisco/n1kv/vsm/NetconfHelper.java | 355 ++++
.../cloud/utils/cisco/n1kv/vsm/PolicyMap.java | 34 +
.../cloud/utils/cisco/n1kv/vsm/PortProfile.java | 48 +
.../cloud/utils/cisco/n1kv/vsm/VsmCommand.java | 999 +++++++++++
.../utils/cisco/n1kv/vsm/VsmOkResponse.java | 44 +
.../cisco/n1kv/vsm/VsmPolicyMapResponse.java | 84 +
.../cisco/n1kv/vsm/VsmPortProfileResponse.java | 166 ++
.../cloud/utils/cisco/n1kv/vsm/VsmResponse.java | 222 +++
.../java/com/cloud/utils/component/Adapter.java | 27 +
.../com/cloud/utils/component/AdapterBase.java | 40 +
.../com/cloud/utils/component/AdapterList.java | 37 +
.../cloud/utils/component/ComponentContext.java | 282 ++++
.../ComponentInstantiationPostProcessor.java | 149 ++
.../utils/component/ComponentLifecycle.java | 64 +
.../utils/component/ComponentLifecycleBase.java | 87 +
.../component/ComponentMethodInterceptable.java | 27 +
.../component/ComponentMethodInterceptor.java | 32 +
.../utils/component/ComponentNamingPolicy.java | 65 +
.../java/com/cloud/utils/component/Manager.java | 27 +
.../com/cloud/utils/component/ManagerBase.java | 28 +
.../java/com/cloud/utils/component/Named.java | 26 +
.../cloud/utils/component/PluggableService.java | 29 +
.../com/cloud/utils/component/Registry.java | 51 +
.../utils/component/SystemIntegrityChecker.java | 30 +
.../utils/concurrency/NamedThreadFactory.java | 38 +
.../com/cloud/utils/concurrency/Scheduler.java | 31 +
.../utils/concurrency/SynchronizationEvent.java | 89 +
.../com/cloud/utils/concurrency/TestClock.java | 161 ++
.../com/cloud/utils/crypt/DBEncryptionUtil.java | 87 +
.../utils/crypt/EncryptionSecretKeyChecker.java | 146 ++
.../utils/crypt/EncryptionSecretKeySender.java | 65 +
.../java/com/cloud/utils/crypt/RSAHelper.java | 90 +
.../java/com/cloud/utils/db/DbProperties.java | 109 ++
.../java/com/cloud/utils/db/EntityManager.java | 84 +
.../java/com/cloud/utils/db/UUIDManager.java | 48 +
.../com/cloud/utils/encoding/URLEncoder.java | 113 ++
.../java/com/cloud/utils/events/EventArgs.java | 44 +
.../com/cloud/utils/events/SubscriptionMgr.java | 164 ++
.../utils/exception/CSExceptionErrorCode.java | 100 ++
.../utils/exception/CloudRuntimeException.java | 141 ++
.../com/cloud/utils/exception/ErrorContext.java | 31 +
.../utils/exception/ExceptionProxyObject.java | 55 +
.../cloud/utils/exception/ExceptionUtil.java | 54 +
.../utils/exception/ExecutionException.java | 49 +
.../HypervisorVersionChangedException.java | 35 +
.../java/com/cloud/utils/fsm/ChangeEvent.java | 24 +
.../java/com/cloud/utils/fsm/FiniteState.java | 58 +
.../java/com/cloud/utils/fsm/FiniteState2.java | 34 +
.../com/cloud/utils/fsm/FiniteStateObject.java | 25 +
.../cloud/utils/fsm/NoTransitionException.java | 36 +
.../main/java/com/cloud/utils/fsm/State.java | 27 +
.../main/java/com/cloud/utils/fsm/StateDao.java | 25 +
.../java/com/cloud/utils/fsm/StateListener.java | 43 +
.../java/com/cloud/utils/fsm/StateMachine.java | 147 ++
.../java/com/cloud/utils/fsm/StateMachine2.java | 261 +++
.../java/com/cloud/utils/fsm/StateObject.java | 27 +
.../main/java/com/cloud/utils/mgmt/JmxUtil.java | 90 +
.../com/cloud/utils/mgmt/ManagementBean.java | 27 +
.../utils/mgmt/PropertyMapDynamicBean.java | 120 ++
utils/src/main/java/com/cloud/utils/net/Ip.java | 98 ++
.../java/com/cloud/utils/net/Ip4Address.java | 80 +
.../java/com/cloud/utils/net/MacAddress.java | 367 +++++
.../main/java/com/cloud/utils/net/NetUtils.java | 1550 ++++++++++++++++++
.../main/java/com/cloud/utils/net/NfsUtils.java | 55 +
.../main/java/com/cloud/utils/net/UrlUtil.java | 63 +
.../com/cloud/utils/nio/HandlerFactory.java | 28 +
.../src/main/java/com/cloud/utils/nio/Link.java | 567 +++++++
.../java/com/cloud/utils/nio/NioClient.java | 125 ++
.../java/com/cloud/utils/nio/NioConnection.java | 476 ++++++
.../java/com/cloud/utils/nio/NioServer.java | 97 ++
.../src/main/java/com/cloud/utils/nio/Task.java | 89 +
.../com/cloud/utils/nio/TrustAllManager.java | 45 +
.../com/cloud/utils/rest/BasicRestClient.java | 118 ++
.../utils/rest/CloudstackRESTException.java | 33 +
.../com/cloud/utils/rest/HttpClientHelper.java | 71 +
.../com/cloud/utils/rest/HttpConstants.java | 34 +
.../java/com/cloud/utils/rest/HttpMethods.java | 41 +
.../cloud/utils/rest/HttpStatusCodeHelper.java | 34 +
.../cloud/utils/rest/HttpUriRequestBuilder.java | 119 ++
.../cloud/utils/rest/RESTServiceConnector.java | 166 ++
.../java/com/cloud/utils/rest/RestClient.java | 31 +
.../cloud/utils/script/OutputInterpreter.java | 141 ++
.../java/com/cloud/utils/script/Script.java | 502 ++++++
.../java/com/cloud/utils/script/Script2.java | 70 +
.../cloud/utils/security/CertificateHelper.java | 166 ++
.../java/com/cloud/utils/ssh/SSHCmdHelper.java | 179 ++
.../java/com/cloud/utils/ssh/SSHKeysHelper.java | 115 ++
.../java/com/cloud/utils/ssh/SshException.java | 30 +
.../java/com/cloud/utils/ssh/SshHelper.java | 209 +++
.../storage/encoding/DecodedDataObject.java | 56 +
.../storage/encoding/DecodedDataStore.java | 68 +
.../cloud/utils/storage/encoding/Decoder.java | 66 +
.../utils/storage/encoding/EncodingType.java | 32 +
.../com/cloud/utils/time/InaccurateClock.java | 102 ++
.../cloud/utils/time/InaccurateClockMBean.java | 28 +
.../com/cloud/utils/xmlobject/XmlObject.java | 214 +++
.../cloud/utils/xmlobject/XmlObjectParser.java | 128 ++
.../utils/baremetal/BaremetalUtils.java | 24 +
.../utils/graphite/GraphiteClient.java | 123 ++
.../utils/graphite/GraphiteException.java | 31 +
.../utils/identity/ManagementServerNode.java | 63 +
.../utils/imagestore/ImageStoreUtil.java | 110 ++
.../cloudstack/utils/security/SSLUtils.java | 58 +
.../utils/security/SecureSSLSocketFactory.java | 124 ++
.../cloudstack/utils/usage/UsageUtils.java | 24 +
.../ssl/EasySSLProtocolSocketFactory.java | 210 +++
.../contrib/ssl/EasyX509TrustManager.java | 110 ++
utils/src/main/resources/cloud.keystore | Bin 0 -> 1316 bytes
.../utils/baremetal/BaremetalUtils.java | 24 -
.../utils/graphite/GraphiteClient.java | 123 --
.../utils/graphite/GraphiteException.java | 31 -
.../utils/identity/ManagementServerNode.java | 63 -
.../utils/imagestore/ImageStoreUtil.java | 110 --
.../cloudstack/utils/security/SSLUtils.java | 58 -
.../utils/security/SecureSSLSocketFactory.java | 124 --
.../cloudstack/utils/usage/UsageUtils.java | 24 -
.../ssl/EasySSLProtocolSocketFactory.java | 210 ---
.../contrib/ssl/EasyX509TrustManager.java | 110 --
.../test/java/com/cloud/utils/DateUtilTest.java | 60 +
.../test/java/com/cloud/utils/DummyImpl.java | 31 +
.../java/com/cloud/utils/DummyInterface.java | 24 +
.../java/com/cloud/utils/DummyPremiumImpl.java | 28 +
.../java/com/cloud/utils/HttpUtilsTest.java | 94 ++
.../java/com/cloud/utils/NumbersUtilTest.java | 47 +
.../com/cloud/utils/PasswordGeneratorTest.java | 42 +
.../java/com/cloud/utils/ProcessUtilTest.java | 76 +
.../com/cloud/utils/PropertiesUtilsTest.java | 64 +
.../java/com/cloud/utils/ReflectUtilTest.java | 148 ++
.../test/java/com/cloud/utils/ScriptTest.java | 135 ++
.../java/com/cloud/utils/StringUtilsTest.java | 253 +++
.../test/java/com/cloud/utils/TernaryTest.java | 34 +
.../test/java/com/cloud/utils/TestProfiler.java | 116 ++
.../test/java/com/cloud/utils/UriUtilsTest.java | 60 +
.../java/com/cloud/utils/UuidUtilsTest.java | 42 +
.../backoff/impl/ConstantTimeBackoffTest.java | 112 ++
.../crypto/EncryptionSecretKeyCheckerTest.java | 45 +
.../com/cloud/utils/crypto/RSAHelperTest.java | 54 +
.../cloud/utils/encoding/UrlEncoderTest.java | 33 +
.../utils/exception/ExceptionUtilTest.java | 52 +
.../com/cloud/utils/net/Ip4AddressTest.java | 40 +
.../test/java/com/cloud/utils/net/IpTest.java | 63 +
.../com/cloud/utils/net/MacAddressTest.java | 60 +
.../java/com/cloud/utils/net/NetUtilsTest.java | 421 +++++
.../cloud/utils/rest/BasicRestClientTest.java | 106 ++
.../cloud/utils/rest/HttpClientHelperTest.java | 38 +
.../cloud/utils/rest/HttpRequestMatcher.java | 141 ++
.../utils/rest/HttpStatusCodeHelperTest.java | 59 +
.../utils/rest/HttpUriRequestBuilderTest.java | 115 ++
.../utils/rest/HttpUriRequestMethodMatcher.java | 44 +
.../utils/rest/HttpUriRequestPathMatcher.java | 43 +
.../rest/HttpUriRequestPayloadMatcher.java | 62 +
.../utils/rest/HttpUriRequestQueryMatcher.java | 48 +
.../utils/rest/RESTServiceConnectorTest.java | 323 ++++
.../com/cloud/utils/ssh/SSHKeysHelperTest.java | 73 +
.../utils/testcase/Log4jEnabledTestCase.java | 58 +
.../java/com/cloud/utils/testcase/NioTest.java | 216 +++
.../cloud/utils/xmlobject/TestXmlObject.java | 53 +
.../cloud/utils/xmlobject/TestXmlObject2.java | 54 +
.../utils/imagestore/ImageStoreUtilTest.java | 54 +
.../com/cloud/utils/QualifierTestContext.xml | 38 +
.../utils/db/transactionContextBuilderTest.xml | 48 +
utils/src/test/resources/log4j.xml | 118 ++
utils/src/test/resources/testContext.xml | 52 +
utils/test/com/cloud/utils/DateUtilTest.java | 60 -
utils/test/com/cloud/utils/DummyImpl.java | 31 -
utils/test/com/cloud/utils/DummyInterface.java | 24 -
.../test/com/cloud/utils/DummyPremiumImpl.java | 28 -
utils/test/com/cloud/utils/HttpUtilsTest.java | 94 --
utils/test/com/cloud/utils/NumbersUtilTest.java | 47 -
.../com/cloud/utils/PasswordGeneratorTest.java | 42 -
utils/test/com/cloud/utils/ProcessUtilTest.java | 76 -
.../com/cloud/utils/PropertiesUtilsTest.java | 64 -
utils/test/com/cloud/utils/ReflectUtilTest.java | 148 --
utils/test/com/cloud/utils/ScriptTest.java | 135 --
utils/test/com/cloud/utils/StringUtilsTest.java | 253 ---
utils/test/com/cloud/utils/TernaryTest.java | 34 -
utils/test/com/cloud/utils/TestProfiler.java | 116 --
utils/test/com/cloud/utils/UriUtilsTest.java | 60 -
utils/test/com/cloud/utils/UuidUtilsTest.java | 42 -
.../backoff/impl/ConstantTimeBackoffTest.java | 112 --
.../crypto/EncryptionSecretKeyCheckerTest.java | 45 -
.../com/cloud/utils/crypto/RSAHelperTest.java | 54 -
.../cloud/utils/encoding/UrlEncoderTest.java | 33 -
.../utils/exception/ExceptionUtilTest.java | 52 -
.../com/cloud/utils/net/Ip4AddressTest.java | 40 -
utils/test/com/cloud/utils/net/IpTest.java | 63 -
.../com/cloud/utils/net/MacAddressTest.java | 60 -
.../test/com/cloud/utils/net/NetUtilsTest.java | 421 -----
.../utils/rest/RESTServiceConnectorTest.java | 395 -----
.../com/cloud/utils/ssh/SSHKeysHelperTest.java | 73 -
.../utils/testcase/Log4jEnabledTestCase.java | 58 -
.../test/com/cloud/utils/testcase/NioTest.java | 216 ---
.../cloud/utils/xmlobject/TestXmlObject.java | 53 -
.../cloud/utils/xmlobject/TestXmlObject2.java | 54 -
.../utils/imagestore/ImageStoreUtilTest.java | 54 -
.../com/cloud/utils/QualifierTestContext.xml | 38 -
.../utils/db/transactionContextBuilderTest.xml | 48 -
utils/test/resources/log4j.xml | 118 --
utils/test/resources/testContext.xml | 52 -
575 files changed, 32174 insertions(+), 30772 deletions(-)
----------------------------------------------------------------------
[04/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Merge pull request #731 from remibergsma/centos7-kvm
CLOUDSTACK-8443: Support CentOS 7 as KVM hypervisorThis adds support for CentOS 7 as a KVM hypervisor. As discussed in the Jira issue, the root cause of the issue was the `cloudstack-setup-agent` script that added this line to `/etc/libvirt/qemu.conf`:
`cgroup_controllers=["cpu"]`
On CentOS 6 this 'works', but since by default no cgroups are mounted, this setting is ignored by `libvirtd`. On CentOS 7 is does not work, because the `cpu` and `cpuacct` are 'co-mounted'. This simpy means you cannot use one without the order. The config line above instructs `libvirtd` to only use the `cpu` cgroup, which it can't.
There was code added to make sure the `cpu` cgroup was not co-mounted. It did this with a shell script, but after a reboot it was gone. It wasn't reliable and not even a solution at all. I went ahead and removed the code, because the co-mounted cgroups work fine. The real issue was the config line we put in `/etc/libvirt/qemu.conf` so much better to fix that instead.
The default for `libvirtd` is to use only cgroups that are mounted. When you remove the 'cgroup_controllers' line, the default kicks in. According to the `qemu.conf` file, the default is:
`cgroup_controllers = ["cpu", "devices", "memory", "blkio", "cpuacct", "net_cls"]`
Then again, if it's not mounted, it's not used. So, that's a nice way to control it.
This works just fine for both RHEL/CentOS 6 and RHEL/CentOS 7.
Along the debugging, I came across some small issues here and there which I also fixed in this PR.
If you test this, be sure to build RPMs from this branch and install those on the KVM hypervisor.
At Schuberg Philis we run KVM hypervisors on CentOS 7 for months with these fixes. Now I took the time to fix the issues in CloudStack, rather than work around them.
@bhaisaab @karuturi could you please review this? Thanks!
Please note:
The next step is to fix CLOUDSTACK-8625 (Systemd profile for KVM Agent) as currently a sysvinit script is still used. Although it works, we do not have any systemd benefits. As it is a separate issue, I'll try to address it in a separate PR.
* pr/731:
CLOUDSTACK-8443: detect CentOS 7.x as RHEL 7 alike
CLOUDSTACK-8443: mention the correct logfile
CLOUDSTACK-8443: display the right hypervisor type
CLOUDSTACK-8443: don't try to fix co-mounted cgroups
Signed-off-by: Remi Bergsma <gi...@remi.nl>
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c0fde9a1
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c0fde9a1
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c0fde9a1
Branch: refs/heads/deploy-from-snapshot
Commit: c0fde9a12bf32d0d4009792d05b1648f7c6ea419
Parents: a527d27 0a320c1
Author: Remi Bergsma <gi...@remi.nl>
Authored: Tue Aug 25 10:32:27 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Tue Aug 25 10:32:27 2015 +0200
----------------------------------------------------------------------
agent/bindir/cloud-setup-agent.in | 2 +-
.../kvm/resource/LibvirtComputingResource.java | 23 ---------
python/lib/cloud_utils.py | 19 -------
python/lib/cloudutils/serviceConfig.py | 7 ++-
python/lib/cloudutils/utilities.py | 2 +-
scripts/vm/hypervisor/kvm/setup-cgroups.sh | 52 --------------------
6 files changed, 5 insertions(+), 100 deletions(-)
----------------------------------------------------------------------
[25/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentLifecycle.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentLifecycle.java b/utils/src/com/cloud/utils/component/ComponentLifecycle.java
deleted file mode 100644
index 897ddb1..0000000
--- a/utils/src/com/cloud/utils/component/ComponentLifecycle.java
+++ /dev/null
@@ -1,64 +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 com.cloud.utils.component;
-
-import java.util.Map;
-
-import javax.naming.ConfigurationException;
-
-public interface ComponentLifecycle extends Named {
- public static final int RUN_LEVEL_SYSTEM_BOOTSTRAP = 0; // for system level bootstrap components
- public static final int RUN_LEVEL_SYSTEM = 1; // for system level service components (i.e., DAOs)
- public static final int RUN_LEVEL_FRAMEWORK_BOOTSTRAP = 2; // for framework startup checkers (i.e., DB migration check)
- public static final int RUN_LEVEL_FRAMEWORK = 3; // for framework bootstrap components(i.e., clustering management components)
- public static final int RUN_LEVEL_COMPONENT_BOOTSTRAP = 4; // general manager components
- public static final int RUN_LEVEL_COMPONENT = 5; // regular adapters, plugin components
- public static final int RUN_LEVEL_APPLICATION_MAINLOOP = 6;
- public static final int MAX_RUN_LEVELS = 7;
-
- @Override
- String getName();
-
- void setName(String name);
-
- void setConfigParams(Map<String, Object> params);
-
- Map<String, Object> getConfigParams();
-
- int getRunLevel();
-
- void setRunLevel(int level);
-
- public boolean configure(String name, Map<String, Object> params) throws ConfigurationException;
-
- /**
- * Start any background tasks.
- *
- * @return true if the tasks were started, false otherwise.
- */
- public boolean start();
-
- /**
- * Stop any background tasks.
- *
- * @return true background tasks were stopped, false otherwise.
- */
- public boolean stop();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentLifecycleBase.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentLifecycleBase.java b/utils/src/com/cloud/utils/component/ComponentLifecycleBase.java
deleted file mode 100644
index 829dc9b..0000000
--- a/utils/src/com/cloud/utils/component/ComponentLifecycleBase.java
+++ /dev/null
@@ -1,87 +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 com.cloud.utils.component;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.naming.ConfigurationException;
-
-import org.apache.log4j.Logger;
-
-public class ComponentLifecycleBase implements ComponentLifecycle {
- private static final Logger s_logger = Logger.getLogger(ComponentLifecycleBase.class);
-
- protected String _name;
- protected int _runLevel;
- protected Map<String, Object> _configParams = new HashMap<String, Object>();
-
- public ComponentLifecycleBase() {
- _name = this.getClass().getSimpleName();
- _runLevel = RUN_LEVEL_COMPONENT;
- }
-
- @Override
- public String getName() {
- return _name;
- }
-
- @Override
- public void setName(String name) {
- _name = name;
- }
-
- @Override
- public void setConfigParams(Map<String, Object> params) {
- _configParams = params;
- }
-
- @Override
- public Map<String, Object> getConfigParams() {
- return _configParams;
- }
-
- @Override
- public int getRunLevel() {
- return _runLevel;
- }
-
- @Override
- public void setRunLevel(int level) {
- _runLevel = level;
- }
-
- @Override
- public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
- _name = name;
- _configParams = params;
- return true;
- }
-
- @Override
- public boolean start() {
- return true;
- }
-
- @Override
- public boolean stop() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java b/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java
deleted file mode 100644
index 4d94391..0000000
--- a/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java
+++ /dev/null
@@ -1,27 +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 com.cloud.utils.component;
-
-/**
- * Marker interface to work with CGLIB based CloudStack legacy AOP
- *
- */
-public interface ComponentMethodInterceptable {
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java b/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java
deleted file mode 100644
index dca688a..0000000
--- a/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java
+++ /dev/null
@@ -1,32 +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 com.cloud.utils.component;
-
-import java.lang.reflect.Method;
-
-public interface ComponentMethodInterceptor {
- boolean needToIntercept(Method method);
-
- Object interceptStart(Method method, Object target);
-
- void interceptComplete(Method method, Object target, Object objReturnedInInterceptStart);
-
- void interceptException(Method method, Object target, Object objReturnedInInterceptStart);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java b/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java
deleted file mode 100644
index 33d1dd4..0000000
--- a/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java
+++ /dev/null
@@ -1,65 +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 com.cloud.utils.component;
-
-import net.sf.cglib.core.NamingPolicy;
-import net.sf.cglib.core.Predicate;
-
-/**
- * Copied/Modified from Spring source
- *
- */
-public class ComponentNamingPolicy implements NamingPolicy {
-
- public static final ComponentNamingPolicy INSTANCE = new ComponentNamingPolicy();
-
- @Override
- public String getClassName(String prefix, String source, Object key, Predicate names) {
- if (prefix == null) {
- prefix = "net.sf.cglib.empty.Object";
- } else if (prefix.startsWith("java")) {
- prefix = "_" + prefix;
- }
- String base = prefix + "_" + source.substring(source.lastIndexOf('.') + 1) + getTag() + "_" + Integer.toHexString(key.hashCode());
- String attempt = base;
- int index = 2;
- while (names.evaluate(attempt))
- attempt = base + "_" + index++;
- return attempt;
- }
-
- /**
- * Returns a string which is incorporated into every generated class name.
- * By default returns "ByCloudStack"
- */
- protected String getTag() {
- return "ByCloudStack";
- }
-
- @Override
- public int hashCode() {
- return getTag().hashCode();
- }
-
- @Override
- public boolean equals(Object o) {
- return (o instanceof ComponentNamingPolicy) && ((ComponentNamingPolicy)o).getTag().equals(getTag());
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/Manager.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/Manager.java b/utils/src/com/cloud/utils/component/Manager.java
deleted file mode 100644
index 3200b46..0000000
--- a/utils/src/com/cloud/utils/component/Manager.java
+++ /dev/null
@@ -1,27 +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 com.cloud.utils.component;
-
-/**
- *
- * For now we only expose some simple methods. In the future, we can use this
- **/
-public interface Manager extends ComponentLifecycle {
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/ManagerBase.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/ManagerBase.java b/utils/src/com/cloud/utils/component/ManagerBase.java
deleted file mode 100644
index 01e4f40..0000000
--- a/utils/src/com/cloud/utils/component/ManagerBase.java
+++ /dev/null
@@ -1,28 +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 com.cloud.utils.component;
-
-public class ManagerBase extends ComponentLifecycleBase implements ComponentMethodInterceptable {
- public ManagerBase() {
- super();
- // set default run level for manager components
- setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT_BOOTSTRAP);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/Named.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/Named.java b/utils/src/com/cloud/utils/component/Named.java
deleted file mode 100644
index 60835b0..0000000
--- a/utils/src/com/cloud/utils/component/Named.java
+++ /dev/null
@@ -1,26 +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 com.cloud.utils.component;
-
-public interface Named {
-
- String getName();
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/PluggableService.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/PluggableService.java b/utils/src/com/cloud/utils/component/PluggableService.java
deleted file mode 100644
index 60c64bf..0000000
--- a/utils/src/com/cloud/utils/component/PluggableService.java
+++ /dev/null
@@ -1,29 +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 com.cloud.utils.component;
-
-import java.util.List;
-
-// This interface defines methods for pluggable code within the Cloud Stack.
-public interface PluggableService {
- // The config command properties filenames that lists allowed API commands
- // and role masks supported by this pluggable service
- List<Class<?>> getCommands();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/Registry.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/Registry.java b/utils/src/com/cloud/utils/component/Registry.java
deleted file mode 100644
index d3a48df..0000000
--- a/utils/src/com/cloud/utils/component/Registry.java
+++ /dev/null
@@ -1,51 +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 com.cloud.utils.component;
-
-import java.util.List;
-
-/**
- * Simple interface to represents a registry of items
- *
- * @param <T>
- */
-public interface Registry<T> extends Named {
-
- /**
- * Registers an item. If the item has already been registered the implementation
- * should detect that it is registered and not re-register it.
- *
- * @param type
- * @return true if register, false if not registered or already exists
- */
- boolean register(T type);
-
- void unregister(T type);
-
- /**
- * Returns a list that will dynamically change as items are registered/unregister.
- * The list is thread safe to iterate upon. Traversing the list using an index
- * would not be safe as the size may changed during traversal.
- *
- * @return Unmodifiable list of registered items
- */
- List<T> getRegistered();
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/component/SystemIntegrityChecker.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/SystemIntegrityChecker.java b/utils/src/com/cloud/utils/component/SystemIntegrityChecker.java
deleted file mode 100644
index a0e2581..0000000
--- a/utils/src/com/cloud/utils/component/SystemIntegrityChecker.java
+++ /dev/null
@@ -1,30 +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 com.cloud.utils.component;
-
-/**
- * before any other components are loaded. Within ComponentLocator
- * database upgrades and other verification to make sure it works.
- */
-public interface SystemIntegrityChecker {
- public static final String Name = "system-integrity-checker";
-
- void check();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/concurrency/NamedThreadFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/concurrency/NamedThreadFactory.java b/utils/src/com/cloud/utils/concurrency/NamedThreadFactory.java
deleted file mode 100644
index ed4d6b0..0000000
--- a/utils/src/com/cloud/utils/concurrency/NamedThreadFactory.java
+++ /dev/null
@@ -1,38 +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 com.cloud.utils.concurrency;
-
-import java.util.concurrent.ThreadFactory;
-
-public class NamedThreadFactory implements ThreadFactory {
- private int _number;
- private final String _name;
-
- public NamedThreadFactory(String name) {
- _name = name;
- _number = 1;
- }
-
- @Override
- public synchronized Thread newThread(Runnable r) {
- return new Thread(r, _name + "-" + _number++);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/concurrency/Scheduler.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/concurrency/Scheduler.java b/utils/src/com/cloud/utils/concurrency/Scheduler.java
deleted file mode 100644
index e0dba24..0000000
--- a/utils/src/com/cloud/utils/concurrency/Scheduler.java
+++ /dev/null
@@ -1,31 +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 com.cloud.utils.concurrency;
-
-import java.util.Date;
-
-public interface Scheduler {
-
- /**
- * This is called from the TimerTask thread periodically about every one minute.
- *
- */
- public void poll(Date currentTimestamp);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/concurrency/SynchronizationEvent.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/concurrency/SynchronizationEvent.java b/utils/src/com/cloud/utils/concurrency/SynchronizationEvent.java
deleted file mode 100644
index 5207ad4..0000000
--- a/utils/src/com/cloud/utils/concurrency/SynchronizationEvent.java
+++ /dev/null
@@ -1,89 +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 com.cloud.utils.concurrency;
-
-import org.apache.log4j.Logger;
-
-public class SynchronizationEvent {
- protected final static Logger s_logger = Logger.getLogger(SynchronizationEvent.class);
-
- private boolean signalled;
-
- public SynchronizationEvent() {
- signalled = false;
- }
-
- public SynchronizationEvent(boolean signalled) {
- this.signalled = signalled;
- }
-
- public void setEvent() {
- synchronized (this) {
- signalled = true;
- notifyAll();
- }
- }
-
- public void resetEvent() {
- synchronized (this) {
- signalled = false;
- }
- }
-
- public boolean waitEvent() throws InterruptedException {
- synchronized (this) {
- if (signalled)
- return true;
-
- while (true) {
- try {
- wait();
- assert (signalled);
- return signalled;
- } catch (InterruptedException e) {
- s_logger.debug("unexpected awaken signal in wait()");
- throw e;
- }
- }
- }
- }
-
- public boolean waitEvent(long timeOutMiliseconds) throws InterruptedException {
- synchronized (this) {
- if (signalled)
- return true;
-
- try {
- wait(timeOutMiliseconds);
- return signalled;
- } catch (InterruptedException e) {
- // TODO, we don't honor time out semantics when the waiting thread is interrupted
- s_logger.debug("unexpected awaken signal in wait(...)");
- throw e;
- }
- }
- }
-
- public boolean isSignalled() {
- synchronized (this) {
- return signalled;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/concurrency/TestClock.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/concurrency/TestClock.java b/utils/src/com/cloud/utils/concurrency/TestClock.java
deleted file mode 100644
index 43fe56f..0000000
--- a/utils/src/com/cloud/utils/concurrency/TestClock.java
+++ /dev/null
@@ -1,161 +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 com.cloud.utils.concurrency;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.TimerTask;
-
-/**
- * A test clock which is also a TimerTask. The task calls a Scheduler's poll method
- *
- */
-public class TestClock extends TimerTask {
- private int _minute = 0;
- private int _hour = 0;
- private int _day = 0;
- private int _week = 0;
- private int _month = 0;
- private int _year = 0;
- private Calendar _cal = null;
- private final int _minutesPerHour;
- private final int _hoursPerDay;
- private final int _daysPerWeek;
- private final int _daysPerMonth;
- private final int _weeksPerMonth;
- private final int _monthsPerYear;
- private final Scheduler _scheduler;
-
- public TestClock(Scheduler scheduler, int minutesPerHour, int hoursPerDay, int daysPerWeek, int daysPerMonth, int weeksPerMonth, int monthsPerYear) {
- _minutesPerHour = minutesPerHour;
- _hoursPerDay = hoursPerDay;
- _daysPerWeek = daysPerWeek;
- _daysPerMonth = daysPerMonth;
- _weeksPerMonth = weeksPerMonth;
- _monthsPerYear = monthsPerYear;
- _cal = Calendar.getInstance();
- _year = _cal.get(Calendar.YEAR);
- _month = _cal.get(Calendar.MONTH);
- _day = _cal.get(Calendar.DAY_OF_MONTH);
- _week = _cal.get(Calendar.WEEK_OF_MONTH);
- _hour = _cal.get(Calendar.HOUR_OF_DAY);
- _minute = _cal.get(Calendar.MINUTE);
- _scheduler = scheduler;
- }
-
- public int getMinute() {
- synchronized (this) {
- return _minute;
- }
- }
-
- public int getHour() {
- synchronized (this) {
- return _hour;
- }
- }
-
- public int getDay() {
- synchronized (this) {
- return _day;
- }
- }
-
- public int getWeek() {
- synchronized (this) {
- return _week;
- }
- }
-
- public int getMonth() {
- synchronized (this) {
- return _month;
- }
- }
-
- public int getYear() {
- synchronized (this) {
- return _year;
- }
- }
-
- public int getMinutesPerHour() {
- return _minutesPerHour;
- }
-
- public int getHoursPerDay() {
- return _hoursPerDay;
- }
-
- public int getDaysPerMonth() {
- return _daysPerMonth;
- }
-
- public int getDaysPerWeek() {
- return _daysPerWeek;
- }
-
- public int getWeeksPerMonth() {
- return _weeksPerMonth;
- }
-
- public int getMonthsPerYear() {
- return _monthsPerYear;
- }
-
- @Override
- public void run() {
- synchronized (this) {
- _minute++;
- if ((_minute > 0) && ((_minute % _minutesPerHour) == 0)) {
- _minute = 0;
- _hour++;
- }
-
- if ((_hour > 0) && ((_hour % _hoursPerDay) == 0)) {
- _hour = 0;
- _day++;
- }
-
- if ((_day > 0) && ((_day % _daysPerWeek) == 0)) {
- _week++;
- }
-
- if ((_day > 0) && ((_day % _daysPerMonth) == 0)) {
- _day = 0;
- _week = 0;
- _month++;
- }
-
- if ((_month > 0) && ((_month % _monthsPerYear) == 0)) {
- _month = 0;
- _year++;
- }
- if (_scheduler != null) {
- // XXX: Creating new date is hugely inefficient for every minute.
- // Later the time in the database will be changed to currentTimeInMillis.
- // Then we can use System.getCurrentTimeInMillis() which is damn cheap.
- _cal.set(_year, _month, _day, _hour, _minute);
- Date currentTimestamp = _cal.getTime();
- _scheduler.poll(currentTimestamp);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java b/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java
deleted file mode 100644
index 52f2034..0000000
--- a/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java
+++ /dev/null
@@ -1,87 +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 com.cloud.utils.crypt;
-
-import java.util.Properties;
-
-import org.apache.log4j.Logger;
-import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
-import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
-
-import com.cloud.utils.db.DbProperties;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class DBEncryptionUtil {
-
- public static final Logger s_logger = Logger.getLogger(DBEncryptionUtil.class);
- private static StandardPBEStringEncryptor s_encryptor = null;
-
- public static String encrypt(String plain) {
- if (!EncryptionSecretKeyChecker.useEncryption() || (plain == null) || plain.isEmpty()) {
- return plain;
- }
- if (s_encryptor == null) {
- initialize();
- }
- String encryptedString = null;
- try {
- encryptedString = s_encryptor.encrypt(plain);
- } catch (EncryptionOperationNotPossibleException e) {
- s_logger.debug("Error while encrypting: " + plain);
- throw e;
- }
- return encryptedString;
- }
-
- public static String decrypt(String encrypted) {
- if (!EncryptionSecretKeyChecker.useEncryption() || (encrypted == null) || encrypted.isEmpty()) {
- return encrypted;
- }
- if (s_encryptor == null) {
- initialize();
- }
-
- String plain = null;
- try {
- plain = s_encryptor.decrypt(encrypted);
- } catch (EncryptionOperationNotPossibleException e) {
- s_logger.debug("Error while decrypting: " + encrypted);
- throw e;
- }
- return plain;
- }
-
- private static void initialize() {
- final Properties dbProps = DbProperties.getDbProperties();
-
- if (EncryptionSecretKeyChecker.useEncryption()) {
- String dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret");
- if (dbSecretKey == null || dbSecretKey.isEmpty()) {
- throw new CloudRuntimeException("Empty DB secret key in db.properties");
- }
-
- s_encryptor = new StandardPBEStringEncryptor();
- s_encryptor.setAlgorithm("PBEWithMD5AndDES");
- s_encryptor.setPassword(dbSecretKey);
- } else {
- throw new CloudRuntimeException("Trying to encrypt db values when encrytion is not enabled");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java
deleted file mode 100644
index 6524987..0000000
--- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java
+++ /dev/null
@@ -1,146 +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 com.cloud.utils.crypt;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.Properties;
-
-import javax.annotation.PostConstruct;
-
-import org.apache.log4j.Logger;
-import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
-import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
-
-import com.cloud.utils.db.DbProperties;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class EncryptionSecretKeyChecker {
-
- private static final Logger s_logger = Logger.getLogger(EncryptionSecretKeyChecker.class);
-
- // Two possible locations with the new packaging naming
- private static final String s_altKeyFile = "key";
- private static final String s_keyFile = "key";
- private static final String s_envKey = "CLOUD_SECRET_KEY";
- private static StandardPBEStringEncryptor s_encryptor = new StandardPBEStringEncryptor();
- private static boolean s_useEncryption = false;
-
- @PostConstruct
- public void init() {
- /* This will call DbProperties, which will call this to initialize the encryption. Yep,
- * round about and annoying */
- DbProperties.getDbProperties();
- }
-
- public void check(Properties dbProps) throws IOException {
- String encryptionType = dbProps.getProperty("db.cloud.encryption.type");
-
- s_logger.debug("Encryption Type: " + encryptionType);
-
- if (encryptionType == null || encryptionType.equals("none")) {
- return;
- }
-
- if (s_useEncryption) {
- s_logger.warn("Encryption already enabled, is check() called twice?");
- return;
- }
-
- s_encryptor.setAlgorithm("PBEWithMD5AndDES");
- String secretKey = null;
-
- SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig();
-
- if (encryptionType.equals("file")) {
- InputStream is = this.getClass().getClassLoader().getResourceAsStream(s_keyFile);
- if (is == null) {
- is = this.getClass().getClassLoader().getResourceAsStream(s_altKeyFile);
- }
- if(is == null) { //This is means we are not able to load key file from the classpath.
- throw new CloudRuntimeException(s_keyFile + " File containing secret key not found in the classpath: ");
- }
-
- try (BufferedReader in = new BufferedReader(new InputStreamReader(is));) {
- secretKey = in.readLine();
- //Check for null or empty secret key
- } catch (IOException e) {
- throw new CloudRuntimeException("Error while reading secret key from: " + s_keyFile, e);
- }
-
- if (secretKey == null || secretKey.isEmpty()) {
- throw new CloudRuntimeException("Secret key is null or empty in file " + s_keyFile);
- }
-
- } else if (encryptionType.equals("env")) {
- secretKey = System.getenv(s_envKey);
- if (secretKey == null || secretKey.isEmpty()) {
- throw new CloudRuntimeException("Environment variable " + s_envKey + " is not set or empty");
- }
- } else if (encryptionType.equals("web")) {
- int port = 8097;
- try (ServerSocket serverSocket = new ServerSocket(port);) {
- s_logger.info("Waiting for admin to send secret key on port " + port);
- try (
- Socket clientSocket = serverSocket.accept();
- PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
- BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- ) {
- String inputLine;
- if ((inputLine = in.readLine()) != null) {
- secretKey = inputLine;
- }
- } catch (IOException e) {
- throw new CloudRuntimeException("Accept failed on " + port);
- }
- } catch (IOException ioex) {
- throw new CloudRuntimeException("Error initializing secret key reciever", ioex);
- }
- } else {
- throw new CloudRuntimeException("Invalid encryption type: " + encryptionType);
- }
-
- stringConfig.setPassword(secretKey);
- s_encryptor.setConfig(stringConfig);
- s_useEncryption = true;
- }
-
- public static StandardPBEStringEncryptor getEncryptor() {
- return s_encryptor;
- }
-
- public static boolean useEncryption() {
- return s_useEncryption;
- }
-
- //Initialize encryptor for migration during secret key change
- public static void initEncryptorForMigration(String secretKey) {
- s_encryptor.setAlgorithm("PBEWithMD5AndDES");
- SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig();
- stringConfig.setPassword(secretKey);
- s_encryptor.setConfig(stringConfig);
- s_useEncryption = true;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
deleted file mode 100644
index ed44ac6..0000000
--- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
+++ /dev/null
@@ -1,65 +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 com.cloud.utils.crypt;
-
-
-import java.io.PrintWriter;
-import java.net.InetAddress;
-import java.net.Socket;
-import com.cloud.utils.NumbersUtil;
-
-
-public class EncryptionSecretKeySender {
- public static void main(String args[]) {
- try {
- // Create a socket to the host
- String hostname = "localhost";
- int port = 8097;
-
- if (args.length == 2) {
- hostname = args[0];
- port = NumbersUtil.parseInt(args[1], port);
- }
- InetAddress addr = InetAddress.getByName(hostname);
- try(Socket socket = new Socket(addr, port);
- PrintWriter out = new PrintWriter(socket.getOutputStream(), true);)
- {
- java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
- String validationWord = "cloudnine";
- String validationInput = "";
- while (!validationWord.equals(validationInput)) {
- System.out.print("Enter Validation Word:");
- validationInput = stdin.readLine();
- System.out.println();
- }
- System.out.print("Enter Secret Key:");
- String input = stdin.readLine();
- if (input != null) {
- out.println(input);
- }
- }catch (Exception e)
- {
- System.out.println("Exception " + e.getMessage());
- }
- } catch (Exception e) {
- System.out.print("Exception while sending secret key " + e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/crypt/RSAHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/crypt/RSAHelper.java b/utils/src/com/cloud/utils/crypt/RSAHelper.java
deleted file mode 100644
index 692ac22..0000000
--- a/utils/src/com/cloud/utils/crypt/RSAHelper.java
+++ /dev/null
@@ -1,90 +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 com.cloud.utils.crypt;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInput;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.KeyFactory;
-import java.security.SecureRandom;
-import java.security.Security;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.KeySpec;
-import java.security.spec.RSAPublicKeySpec;
-
-import javax.crypto.Cipher;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-
-public class RSAHelper {
- final static Logger s_logger = Logger.getLogger(RSAHelper.class);
-
- static {
- BouncyCastleProvider provider = new BouncyCastleProvider();
- if (Security.getProvider(provider.getName()) == null)
- Security.addProvider(provider);
- }
-
- private static RSAPublicKey readKey(String key) throws Exception {
- byte[] encKey = Base64.decodeBase64(key.split(" ")[1]);
- DataInputStream dis = new DataInputStream(new ByteArrayInputStream(encKey));
-
- byte[] header = readElement(dis);
- String pubKeyFormat = new String(header);
- if (!pubKeyFormat.equals("ssh-rsa"))
- throw new RuntimeException("Unsupported format");
-
- byte[] publicExponent = readElement(dis);
- byte[] modulus = readElement(dis);
-
- KeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
- KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
- RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(spec);
-
- return pubKey;
- }
-
- private static byte[] readElement(DataInput dis) throws IOException {
- int len = dis.readInt();
- byte[] buf = new byte[len];
- dis.readFully(buf);
- return buf;
- }
-
- public static String encryptWithSSHPublicKey(String sshPublicKey, String content) {
- String returnString = null;
- try {
- RSAPublicKey publicKey = readKey(sshPublicKey);
- Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
- cipher.init(Cipher.ENCRYPT_MODE, publicKey, new SecureRandom());
- byte[] encrypted = cipher.doFinal(content.getBytes());
- returnString = Base64.encodeBase64String(encrypted);
- } catch (Exception e) {
- s_logger.info("[ignored]"
- + "error during public key encryption: " + e.getLocalizedMessage());
- }
-
- return returnString;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/db/DbProperties.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/DbProperties.java b/utils/src/com/cloud/utils/db/DbProperties.java
deleted file mode 100644
index 8420614..0000000
--- a/utils/src/com/cloud/utils/db/DbProperties.java
+++ /dev/null
@@ -1,109 +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 com.cloud.utils.db;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.log4j.Logger;
-import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
-import org.jasypt.properties.EncryptableProperties;
-
-import com.cloud.utils.PropertiesUtil;
-import com.cloud.utils.crypt.EncryptionSecretKeyChecker;
-
-public class DbProperties {
-
- private static final Logger log = Logger.getLogger(DbProperties.class);
-
- private static Properties properties = new Properties();
- private static boolean loaded = false;
-
- protected static Properties wrapEncryption(Properties dbProps) throws IOException {
- EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker();
- checker.check(dbProps);
-
- if (EncryptionSecretKeyChecker.useEncryption()) {
- return dbProps;
- } else {
- EncryptableProperties encrProps = new EncryptableProperties(EncryptionSecretKeyChecker.getEncryptor());
- encrProps.putAll(dbProps);
- return encrProps;
- }
- }
-
- public synchronized static Properties getDbProperties() {
- if (!loaded) {
- Properties dbProps = new Properties();
- InputStream is = null;
- try {
- File props = PropertiesUtil.findConfigFile("db.properties");
- if (props != null && props.exists()) {
- is = new FileInputStream(props);
- }
-
- if (is == null) {
- is = PropertiesUtil.openStreamFromURL("db.properties");
- }
-
- if (is == null) {
- System.err.println("Failed to find db.properties");
- log.error("Failed to find db.properties");
- }
-
- if (is != null) {
- dbProps.load(is);
- }
-
- EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker();
- checker.check(dbProps);
-
- if (EncryptionSecretKeyChecker.useEncryption()) {
- StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor();
- EncryptableProperties encrDbProps = new EncryptableProperties(encryptor);
- encrDbProps.putAll(dbProps);
- dbProps = encrDbProps;
- }
- } catch (IOException e) {
- throw new IllegalStateException("Failed to load db.properties", e);
- } finally {
- IOUtils.closeQuietly(is);
- }
-
- properties = dbProps;
- loaded = true;
- }
-
- return properties;
- }
-
- public synchronized static Properties setDbProperties(Properties props) throws IOException {
- if (loaded) {
- throw new IllegalStateException("DbProperties has already been loaded");
- }
- properties = wrapEncryption(props);
- loaded = true;
- return properties;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/db/EntityManager.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/EntityManager.java b/utils/src/com/cloud/utils/db/EntityManager.java
deleted file mode 100644
index 8f4e385..0000000
--- a/utils/src/com/cloud/utils/db/EntityManager.java
+++ /dev/null
@@ -1,84 +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 com.cloud.utils.db;
-
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * Generic Entity Manager to retrieve database objects.
- *
- */
-public interface EntityManager {
- /**
- * Finds an entity by its id.
- * @param <T> class of the entity you're trying to find.
- * @param <K> class of the id that the entity uses.
- * @param entityType Type of the entity.
- * @param id id value
- * @return T if found; null if not.
- */
- public <T, K extends Serializable> T findById(Class<T> entityType, K id);
-
- /**
- * Finds a unique entity by uuid string
- * @param <T> entity class
- * @param entityType type of entity you're looking for.
- * @param uuid the unique id
- * @return T if found, null if not.
- */
- public <T> T findByUuid(Class<T> entityType, String uuid);
-
- /**
- * Finds a unique entity by uuid string, including those removed entries
- * @param <T> entity class
- * @param entityType type of entity you're looking for.
- * @param uuid the unique id
- * @return T if found, null if not.
- */
- public <T> T findByUuidIncludingRemoved(Class<T> entityType, String uuid);
-
- /**
- * Finds an entity by external id which is always String
- * @param <T> entity class
- * @param entityType type of entity you're looking for.
- * @param xid external id
- * @return T if found, null if not.
- */
- public <T> T findByXId(Class<T> entityType, String xid);
-
- /**
- * Lists all entities. Use this method at your own risk.
- * @param <T> entity class
- * @param entityType type of entity you're looking for.
- * @return List<T>
- */
- public <T> List<? extends T> list(Class<T> entityType);
-
- public <T, K extends Serializable> void remove(Class<T> entityType, K id);
-
- public <T, K extends Serializable> T findByIdIncludingRemoved(Class<T> entityType, K id);
-
- public static final String MESSAGE_REMOVE_ENTITY_EVENT = "Message.RemoveEntity.Event";
-
- public static final String MESSAGE_GRANT_ENTITY_EVENT = "Message.GrantEntity.Event";
- public static final String MESSAGE_REVOKE_ENTITY_EVENT = "Message.RevokeEntity.Event";
- public static final String MESSAGE_ADD_DOMAIN_WIDE_ENTITY_EVENT = "Message.AddDomainWideEntity.Event";
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/db/UUIDManager.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/UUIDManager.java b/utils/src/com/cloud/utils/db/UUIDManager.java
deleted file mode 100644
index cac1876..0000000
--- a/utils/src/com/cloud/utils/db/UUIDManager.java
+++ /dev/null
@@ -1,48 +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 com.cloud.utils.db;
-
-
-public interface UUIDManager {
-
- /**
- * Generates a new uuid or uses the customId
- * @param entityType the type of entity
- * @param customId optional custom uuid of the object.
- * @return newly created uuid.
- */
- public <T> String generateUuid(Class<T> entityType, String customId);
-
- /**
- * Checks the uuid for correct format, uniqueness and permissions.
- * @param uuid uuid to check
- * @param entityType the type of entity
- * .
- */
- <T> void checkUuid(String uuid, Class<T> entityType);
-
- /**
- * Checks the uuid for correct format, uniqueness, without checking permissions
- * @param uuid uuid to check
- * @param entityType the type of entity
- * .
- */
- <T> void checkUuidSimple(String uuid, Class<T> entityType);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/encoding/URLEncoder.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/encoding/URLEncoder.java b/utils/src/com/cloud/utils/encoding/URLEncoder.java
deleted file mode 100644
index 58971e7..0000000
--- a/utils/src/com/cloud/utils/encoding/URLEncoder.java
+++ /dev/null
@@ -1,113 +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 com.cloud.utils.encoding;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-import java.util.BitSet;
-
-/**
- *
- * This class is very similar to the java.net.URLEncoder class.
- *
- * Unfortunately, with java.net.URLEncoder there is no way to specify to the
- * java.net.URLEncoder which characters should NOT be encoded.
- *
- * This code was moved from DefaultServlet.java
- *
- * @author Craig R. McClanahan
- * @author Remy Maucherat
- */
-
-public class URLEncoder {
- protected static final char[] hexadecimal = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
-
- static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder(); // or "ISO-8859-1" for ISO Latin 1
-
- //Array containing the safe characters set.
- protected BitSet safeCharacters = new BitSet(256);
-
- public URLEncoder() {
- for (char i = 'a'; i <= 'z'; i++) {
- addSafeCharacter(i);
- }
- for (char i = 'A'; i <= 'Z'; i++) {
- addSafeCharacter(i);
- }
- for (char i = '0'; i <= '9'; i++) {
- addSafeCharacter(i);
- }
- }
-
- private void addSafeCharacter(char c) {
- safeCharacters.set(c);
- }
-
- public String encode(String path) {
- int maxBytesPerChar = 10;
- StringBuffer rewrittenPath = new StringBuffer(path.length());
- ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
- OutputStreamWriter writer = null;
- try {
- writer = new OutputStreamWriter(buf, "UTF8");
- } catch (Exception e) {
- e.printStackTrace();
- writer = new OutputStreamWriter(buf);
- }
-
- for (int i = 0; i < path.length(); i++) {
- int c = path.charAt(i);
- // NOTICE - !isPureAscii(path.charAt(i)) check was added by
- // CloudStack
- if (safeCharacters.get(c) || !isPureAscii(path.charAt(i))) {
- rewrittenPath.append((char)c);
- } else {
- // convert to external encoding before hex conversion
- try {
- writer.write((char)c);
- writer.flush();
- } catch (IOException e) {
- buf.reset();
- continue;
- }
- byte[] ba = buf.toByteArray();
- for (int j = 0; j < ba.length; j++) {
- // Converting each byte in the buffer
- byte toEncode = ba[j];
- rewrittenPath.append('%');
- int low = toEncode & 0x0f;
- int high = (toEncode & 0xf0) >> 4;
- rewrittenPath.append(hexadecimal[high]);
- rewrittenPath.append(hexadecimal[low]);
- }
- buf.reset();
- }
- }
- return rewrittenPath.toString();
- }
-
- // NOTICE - this part was added by CloudStack
- public static boolean isPureAscii(Character v) {
- return asciiEncoder.canEncode(v);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/events/EventArgs.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/events/EventArgs.java b/utils/src/com/cloud/utils/events/EventArgs.java
deleted file mode 100644
index 5c06b4b..0000000
--- a/utils/src/com/cloud/utils/events/EventArgs.java
+++ /dev/null
@@ -1,44 +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 com.cloud.utils.events;
-
-import java.io.Serializable;
-
-public class EventArgs implements Serializable {
- private static final long serialVersionUID = 30659016120504139L;
- public static final EventArgs Empty = new EventArgs();
-
- private String subject;
-
- public EventArgs() {
- }
-
- public EventArgs(String subject) {
- this.subject = subject;
- }
-
- public String getSubject() {
- return subject;
- }
-
- public void setSubject(String subject) {
- this.subject = subject;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/events/SubscriptionMgr.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/events/SubscriptionMgr.java b/utils/src/com/cloud/utils/events/SubscriptionMgr.java
deleted file mode 100644
index 254c27d..0000000
--- a/utils/src/com/cloud/utils/events/SubscriptionMgr.java
+++ /dev/null
@@ -1,164 +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 com.cloud.utils.events;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-
-public class SubscriptionMgr {
- protected final static Logger s_logger = Logger.getLogger(SubscriptionMgr.class);
-
- private static SubscriptionMgr s_instance = new SubscriptionMgr();
-
- private Map<String, List<SubscriberInfo>> registry;
-
- private SubscriptionMgr() {
- registry = new HashMap<String, List<SubscriberInfo>>();
- }
-
- public static SubscriptionMgr getInstance() {
- return s_instance;
- }
-
- public <T> void subscribe(String subject, T subscriber, String listenerMethod) throws SecurityException, NoSuchMethodException {
-
- synchronized (this) {
- List<SubscriberInfo> l = getAndSetSubscriberList(subject);
-
- Class<?> clazz = subscriber.getClass();
- SubscriberInfo subscribeInfo = new SubscriberInfo(clazz, subscriber, listenerMethod);
-
- if (!l.contains(subscribeInfo))
- l.add(subscribeInfo);
- }
- }
-
- public <T> void unsubscribe(String subject, T subscriber, String listenerMethod) {
- synchronized (this) {
- List<SubscriberInfo> l = getSubscriberList(subject);
- if (l != null) {
- for (SubscriberInfo info : l) {
- if (info.isMe(subscriber.getClass(), subscriber, listenerMethod)) {
- l.remove(info);
- return;
- }
- }
- }
- }
- }
-
- public void notifySubscribers(String subject, Object sender, EventArgs args) {
-
- List<SubscriberInfo> l = getExecutableSubscriberList(subject);
- if (l != null) {
- for (SubscriberInfo info : l) {
- try {
- info.execute(sender, args);
- } catch (IllegalArgumentException e) {
- s_logger.warn("Exception on notifying event subscribers: ", e);
- } catch (IllegalAccessException e) {
- s_logger.warn("Exception on notifying event subscribers: ", e);
- } catch (InvocationTargetException e) {
- s_logger.warn("Exception on notifying event subscribers: ", e);
- }
- }
- }
- }
-
- private List<SubscriberInfo> getAndSetSubscriberList(String subject) {
- List<SubscriberInfo> l = registry.get(subject);
- if (l == null) {
- l = new ArrayList<SubscriberInfo>();
- registry.put(subject, l);
- }
-
- return l;
- }
-
- private List<SubscriberInfo> getSubscriberList(String subject) {
- return registry.get(subject);
- }
-
- private synchronized List<SubscriberInfo> getExecutableSubscriberList(String subject) {
- List<SubscriberInfo> l = registry.get(subject);
- if (l != null) {
- // do a shadow clone
- ArrayList<SubscriberInfo> clonedList = new ArrayList<SubscriberInfo>(l.size());
- for (SubscriberInfo info : l)
- clonedList.add(info);
-
- return clonedList;
- }
- return null;
- }
-
- private static class SubscriberInfo {
- private Class<?> clazz;
- private Object subscriber;
- private String methodName;
- private Method method;
-
- public SubscriberInfo(Class<?> clazz, Object subscriber, String methodName) throws SecurityException, NoSuchMethodException {
-
- this.clazz = clazz;
- this.subscriber = subscriber;
- this.methodName = methodName;
- for (Method method : clazz.getMethods()) {
- if (method.getName().equals(methodName)) {
- Class<?>[] paramTypes = method.getParameterTypes();
- if (paramTypes != null && paramTypes.length == 2 && paramTypes[0] == Object.class && EventArgs.class.isAssignableFrom(paramTypes[1])) {
- this.method = method;
-
- break;
- }
- }
- }
- if (this.method == null)
- throw new NoSuchMethodException();
- }
-
- public void execute(Object sender, EventArgs args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
-
- method.invoke(subscriber, sender, args);
- }
-
- public boolean isMe(Class<?> clazz, Object subscriber, String methodName) {
- return this.clazz == clazz && this.subscriber == subscriber && this.methodName.equals(methodName);
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == null)
- return false;
-
- if (o instanceof SubscriberInfo) {
- return this.clazz == ((SubscriberInfo)o).clazz && this.subscriber == ((SubscriberInfo)o).subscriber &&
- this.methodName.equals(((SubscriberInfo)o).methodName);
- }
- return false;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
deleted file mode 100644
index 62af14e..0000000
--- a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
+++ /dev/null
@@ -1,100 +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 com.cloud.utils.exception;
-
-import java.util.HashMap;
-
-import org.apache.log4j.Logger;
-
-/**
- * CSExceptionErrorCode lists the CloudStack error codes that correspond
- * to a each exception thrown by the CloudStack API.
- */
-
-public class CSExceptionErrorCode {
-
- public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName());
-
- // Declare a hashmap of CloudStack Error Codes for Exceptions.
- protected static final HashMap<String, Integer> ExceptionErrorCodeMap;
-
- static {
- try {
- ExceptionErrorCodeMap = new HashMap<String, Integer>();
- ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250);
- ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260);
- ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265);
- ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275);
- ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280);
- ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285);
- ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290);
- ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300);
- ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305);
- ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310);
- ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315);
- ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320);
- ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325);
- ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330);
- ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapacityException", 4331);
- ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335);
- ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340);
- ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345);
- ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350);
- ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355);
- ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360);
- ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365);
- ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370);
- ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375);
- ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380);
- ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385);
- ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390);
- ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395);
- ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540);
- ExceptionErrorCodeMap.put("com.cloud.exception.RequestLimitException", 4545);
- ExceptionErrorCodeMap.put("com.cloud.exception.StorageConflictException", 4550);
-
- // Have a special error code for ServerApiException when it is
- // thrown in a standalone manner when failing to detect any of the above
- // standard exceptions.
- ExceptionErrorCodeMap.put("org.apache.cloudstack.api.ServerApiException", 9999);
- } catch (Exception e) {
- e.printStackTrace();
- throw new ExceptionInInitializerError(e);
- }
- }
-
- public static HashMap<String, Integer> getErrCodeList() {
- return ExceptionErrorCodeMap;
- }
-
- public static int getCSErrCode(String exceptionName) {
- if (ExceptionErrorCodeMap.containsKey(exceptionName)) {
- return ExceptionErrorCodeMap.get(exceptionName);
- } else {
- s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions");
- return -1;
- }
- }
-
- public static String getCurMethodName() {
- StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace();
- return stackTraceCalls[1].toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/CloudRuntimeException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java b/utils/src/com/cloud/utils/exception/CloudRuntimeException.java
deleted file mode 100644
index dd5abc8..0000000
--- a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java
+++ /dev/null
@@ -1,141 +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 com.cloud.utils.exception;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.cloud.utils.Pair;
-import com.cloud.utils.SerialVersionUID;
-
-/**
- * wrap exceptions that you know there's no point in dealing with.
- */
-public class CloudRuntimeException extends RuntimeException implements ErrorContext {
-
- private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException;
-
- // This holds a list of uuids and their descriptive names.
- transient protected ArrayList<ExceptionProxyObject> idList = new ArrayList<ExceptionProxyObject>();
-
- transient protected ArrayList<Pair<Class<?>, String>> uuidList = new ArrayList<Pair<Class<?>, String>>();
-
- protected int csErrorCode;
-
- public CloudRuntimeException(String message) {
- super(message);
- setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
- }
-
- public CloudRuntimeException(String message, Throwable th) {
- super(message, th);
- setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
- }
-
- protected CloudRuntimeException() {
- super();
-
- setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
- }
-
- public void addProxyObject(ExceptionProxyObject obj) {
- idList.add(obj);
- }
-
- public void addProxyObject(String uuid) {
- idList.add(new ExceptionProxyObject(uuid, null));
- }
-
- public void addProxyObject(String voObjUuid, String description) {
- ExceptionProxyObject proxy = new ExceptionProxyObject(voObjUuid, description);
- idList.add(proxy);
- }
-
- @Override
- public CloudRuntimeException add(Class<?> entity, String uuid) {
- uuidList.add(new Pair<Class<?>, String>(entity, uuid));
- return this;
- }
-
- public ArrayList<ExceptionProxyObject> getIdProxyList() {
- return idList;
- }
-
- public void setCSErrorCode(int cserrcode) {
- csErrorCode = cserrcode;
- }
-
- public int getCSErrorCode() {
- return csErrorCode;
- }
-
- public CloudRuntimeException(Throwable t) {
- super(t.getMessage(), t);
- }
-
- @Override
- public List<Pair<Class<?>, String>> getEntitiesInError() {
- return uuidList;
- }
-
- private void writeObject(ObjectOutputStream out) throws IOException {
- out.defaultWriteObject();
-
- int idListSize = idList.size();
- out.writeInt(idListSize);
- for (ExceptionProxyObject proxy : idList) {
- out.writeObject(proxy);
- }
-
- int uuidListSize = uuidList.size();
- out.writeInt(uuidListSize);
- for (Pair<Class<?>, String> entry : uuidList) {
- out.writeObject(entry.first().getCanonicalName());
- out.writeObject(entry.second());
- }
- }
-
- private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
- in.defaultReadObject();
-
- int idListSize = in.readInt();
- if (idList == null)
- idList = new ArrayList<ExceptionProxyObject>();
- if (uuidList == null)
- uuidList = new ArrayList<Pair<Class<?>, String>>();
-
- for (int i = 0; i < idListSize; i++) {
- ExceptionProxyObject proxy = (ExceptionProxyObject)in.readObject();
-
- idList.add(proxy);
- }
-
- int uuidListSize = in.readInt();
- for (int i = 0; i < uuidListSize; i++) {
- String clzName = (String)in.readObject();
- String val = (String)in.readObject();
-
- uuidList.add(new Pair<Class<?>, String>(Class.forName(clzName), val));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/ErrorContext.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/ErrorContext.java b/utils/src/com/cloud/utils/exception/ErrorContext.java
deleted file mode 100644
index 5391373..0000000
--- a/utils/src/com/cloud/utils/exception/ErrorContext.java
+++ /dev/null
@@ -1,31 +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 com.cloud.utils.exception;
-
-import java.util.List;
-
-import com.cloud.utils.Pair;
-
-public interface ErrorContext {
-
- ErrorContext add(Class<?> entity, String uuid);
-
- List<Pair<Class<?>, String>> getEntitiesInError();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java b/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java
deleted file mode 100644
index 5a689d4..0000000
--- a/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java
+++ /dev/null
@@ -1,55 +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 com.cloud.utils.exception;
-
-import java.io.Serializable;
-
-
-public class ExceptionProxyObject implements Serializable {
- private static final long serialVersionUID = -7514266713085362352L;
-
- private String uuid;
- private String description;
-
- public ExceptionProxyObject(){
-
- }
-
- public ExceptionProxyObject(String uuid, String desc){
- this.uuid = uuid;
- description = desc;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-}
[42/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Code clean up in cloud-utils project
- Code formatting
- Remove unused methods
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/5fc953ed
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/5fc953ed
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/5fc953ed
Branch: refs/heads/deploy-from-snapshot
Commit: 5fc953eda2640d1bf69b7ed0f85110b8ac2a4087
Parents: 93b0989
Author: Miguel Ferreira <mi...@me.com>
Authored: Sat Aug 22 20:53:12 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:11 2015 +0200
----------------------------------------------------------------------
.../utils/rest/CloudstackRESTException.java | 8 +-
.../cloud/utils/rest/RESTServiceConnector.java | 118 +++++++++----------
.../utils/rest/RESTValidationStrategy.java | 16 +--
.../utils/rest/RESTServiceConnectorTest.java | 21 ++--
4 files changed, 73 insertions(+), 90 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5fc953ed/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java b/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
index 5985fa0..2078d57 100644
--- a/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
+++ b/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java
@@ -19,19 +19,13 @@
package com.cloud.utils.rest;
+@SuppressWarnings("serial")
public class CloudstackRESTException extends Exception {
- public CloudstackRESTException() {
- }
-
public CloudstackRESTException(final String message) {
super(message);
}
- public CloudstackRESTException(final Throwable cause) {
- super(cause);
- }
-
public CloudstackRESTException(final String message, final Throwable cause) {
super(message, cause);
}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5fc953ed/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
index 6ededcb..01aca89 100644
--- a/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
+++ b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
@@ -19,11 +19,29 @@
package com.cloud.utils.rest;
-import com.google.gson.FieldNamingPolicy;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.reflect.TypeToken;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Type;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.Socket;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
import org.apache.cloudstack.utils.security.SSLUtils;
import org.apache.cloudstack.utils.security.SecureSSLSocketFactory;
import org.apache.commons.httpclient.ConnectTimeoutException;
@@ -46,36 +64,18 @@ import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.log4j.Logger;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Type;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MalformedURLException;
-import java.net.Socket;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.reflect.TypeToken;
/**
- * This abstraction encapsulates client side code for REST service communication. It encapsulates
- * access in a delegate validation strategy. There may different implementations extending
- * {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
+ * This abstraction encapsulates client side code for REST service communication. It encapsulates access in a delegate validation strategy. There may different implementations
+ * extending {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
*
- * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide
- * in the constructor a list of classes and a list of deserializers for these classes. These should
- * be a correlated so that Nth deserializer is correctly mapped to Nth class.
+ * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide in the constructor a list of classes and a list of deserializers for these
+ * classes. These should be a correlated so that Nth deserializer is correctly mapped to Nth class.
*/
public class RESTServiceConnector {
private static final String HTTPS = "https";
@@ -101,7 +101,6 @@ public class RESTServiceConnector {
private final Gson gson;
-
/**
* Getter that may be needed only for test purpose
*
@@ -122,14 +121,14 @@ public class RESTServiceConnector {
try {
// Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
- Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT));
+ Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
} catch (final IOException e) {
s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
}
final GsonBuilder gsonBuilder = new GsonBuilder();
- if(classList != null && deserializerList != null) {
- for(int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
+ if (classList != null && deserializerList != null) {
+ for (int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
}
}
@@ -173,7 +172,7 @@ public class RESTServiceConnector {
public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
- final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri);
+ final PutMethod pm = (PutMethod) createMethod(PUT_METHOD_TYPE, uri);
pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
@@ -193,10 +192,9 @@ public class RESTServiceConnector {
}
@SuppressWarnings("unchecked")
- public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters)
- throws CloudstackRESTException {
+ public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
- final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri);
+ final PostMethod pm = (PostMethod) createMethod(POST_METHOD_TYPE, uri);
pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
@@ -215,7 +213,7 @@ public class RESTServiceConnector {
T result;
try {
- result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
+ result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
} catch (final IOException e) {
throw new CloudstackRESTException("Failed to decode json response body", e);
} finally {
@@ -226,7 +224,7 @@ public class RESTServiceConnector {
}
public void executeDeleteObject(final String uri) throws CloudstackRESTException {
- final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri);
+ final DeleteMethod dm = (DeleteMethod) createMethod(DELETE_METHOD_TYPE, uri);
dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
executeMethod(dm);
@@ -242,7 +240,7 @@ public class RESTServiceConnector {
@SuppressWarnings("unchecked")
public <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
- final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri);
+ final GetMethod gm = (GetMethod) createMethod(GET_METHOD_TYPE, uri);
gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
if (parameters != null && !parameters.isEmpty()) {
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
@@ -263,7 +261,7 @@ public class RESTServiceConnector {
T returnValue;
try {
- returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
+ returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
} catch (final IOException e) {
s_logger.error("IOException while retrieving response body", e);
throw new CloudstackRESTException(e);
@@ -287,7 +285,7 @@ public class RESTServiceConnector {
}
}
- private String responseToErrorMessage(final HttpMethodBase method) {
+ private static String responseToErrorMessage(final HttpMethodBase method) {
assert method.isRequestSent() : "no use getting an error message unless the request is sent";
if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
@@ -305,10 +303,8 @@ public class RESTServiceConnector {
return method.getStatusText();
}
- /* Some controllers use a self-signed certificate. The
- * TrustingProtocolSocketFactory will accept any provided
- * certificate when making an SSL connection to the SDN
- * Manager
+ /*
+ * Some controllers use a self-signed certificate. The TrustingProtocolSocketFactory will accept any provided certificate when making an SSL connection to the SDN Manager
*/
private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
@@ -316,7 +312,7 @@ public class RESTServiceConnector {
public TrustingProtocolSocketFactory() throws IOException {
// Create a trust manager that does not validate certificate chains
- final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
+ final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
@@ -331,7 +327,7 @@ public class RESTServiceConnector {
public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
// Trust always
}
- }};
+ } };
try {
// Install the all-trusting trust manager
@@ -347,43 +343,43 @@ public class RESTServiceConnector {
@Override
public Socket createSocket(final String host, final int port) throws IOException {
- SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
+ final SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
socket.setEnabledProtocols(SSLUtils.getSupportedProtocols(socket.getEnabledProtocols()));
return socket;
}
@Override
public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
- Socket socket = ssf.createSocket(address, port, localAddress, localPort);
+ final Socket socket = ssf.createSocket(address, port, localAddress, localPort);
if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ ((SSLSocket) socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
}
return socket;
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
- Socket s = ssf.createSocket(socket, host, port, autoClose);
+ final Socket s = ssf.createSocket(socket, host, port, autoClose);
if (s instanceof SSLSocket) {
- ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
+ ((SSLSocket) s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) s).getEnabledProtocols()));
}
return s;
}
@Override
- public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
- throws IOException, UnknownHostException, ConnectTimeoutException {
+ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException,
+ UnknownHostException, ConnectTimeoutException {
final int timeout = params.getConnectionTimeout();
if (timeout == 0) {
- Socket socket = createSocket(host, port, localAddress, localPort);
+ final Socket socket = createSocket(host, port, localAddress, localPort);
if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
+ ((SSLSocket) socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
}
return socket;
} else {
final Socket s = ssf.createSocket();
if (s instanceof SSLSocket) {
- ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
+ ((SSLSocket) s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) s).getEnabledProtocols()));
}
s.bind(new InetSocketAddress(localAddress, localPort));
s.connect(new InetSocketAddress(host, port), timeout);
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5fc953ed/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
index 77ac8d0..8ec920a 100644
--- a/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
+++ b/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
@@ -33,9 +33,8 @@ import org.apache.log4j.Logger;
/**
* Basic authentication strategy. This strategy needs user and password for authentication.
*
- * A login URL is needed which will be used for login and getting the cookie to be
- * used in next requests. If an executeMethod request fails due to authorization it will try
- * to login, get the cookie and repeat the attempt to execute the method.
+ * A login URL is needed which will be used for login and getting the cookie to be used in next requests. If an executeMethod request fails due to authorization it will try to
+ * login, get the cookie and repeat the attempt to execute the method.
*/
public class RESTValidationStrategy {
@@ -47,8 +46,7 @@ public class RESTValidationStrategy {
protected String serverVersion;
protected String loginUrl;
- public RESTValidationStrategy(final String host, final String user, final String password,
- final String serverVersion, final String loginUrl) {
+ public RESTValidationStrategy(final String host, final String user, final String password, final String serverVersion, final String loginUrl) {
super();
this.host = host;
this.user = user;
@@ -96,9 +94,7 @@ public class RESTValidationStrategy {
this.host = host;
}
- public void executeMethod(final HttpMethodBase method, final HttpClient client,
- final String protocol)
- throws CloudstackRESTException, HttpException, IOException {
+ public void executeMethod(final HttpMethodBase method, final HttpClient client, final String protocol) throws CloudstackRESTException, HttpException, IOException {
if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
throw new CloudstackRESTException("Hostname/credentials are null or empty");
}
@@ -118,9 +114,7 @@ public class RESTValidationStrategy {
* The method returns false if the login failed or the connection could not be made.
*
*/
- protected void login(final String protocol,
- final HttpClient client)
- throws CloudstackRESTException {
+ protected void login(final String protocol, final HttpClient client) throws CloudstackRESTException {
String url;
if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5fc953ed/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
index 6d58b5b..b177fe1 100644
--- a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
+++ b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
@@ -156,25 +156,24 @@ public class RESTServiceConnectorTest {
@Test(expected = CloudstackRESTException.class)
public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException {
final GetMethod gm = mock(GetMethod.class);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
connector.executeMethod(gm);
verify(gm, times(1)).getStatusCode();
}
- /* Bit of a roundabout way to ensure that login is called after an un authorized result
- * It not possible to properly mock login()
+ /*
+ * Bit of a roundabout way to ensure that login is called after an un authorized result It not possible to properly mock login()
*/
- public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException, HttpException, IOException {
+ public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException {
// Prepare
final GetMethod gm = mock(GetMethod.class);
when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
final RESTValidationStrategy previousValidationStrategy = connector.validation;
- connector.validation = new RESTValidationStrategy(){
+ connector.validation = new RESTValidationStrategy() {
@Override
- protected void login(final String protocol, final HttpClient client)
- throws CloudstackRESTException {
+ protected void login(final String protocol, final HttpClient client) throws CloudstackRESTException {
// Do nothing
}
};
@@ -222,7 +221,7 @@ public class RESTServiceConnectorTest {
@Test(expected = CloudstackRESTException.class)
public void testExecuteCreateObjectException() throws CloudstackRESTException, IOException {
JsonEntity ls = new JsonEntity();
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
@@ -268,7 +267,7 @@ public class RESTServiceConnectorTest {
final JsonEntity ls = new JsonEntity();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException());
+ when(client.executeMethod((HttpMethod) any())).thenThrow(new IOException());
try {
connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
} finally {
@@ -305,7 +304,7 @@ public class RESTServiceConnectorTest {
public void testExecuteDeleteObjectException() throws CloudstackRESTException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
try {
connector.executeDeleteObject("/");
} finally {
@@ -345,7 +344,7 @@ public class RESTServiceConnectorTest {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
+ when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
try {
connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
} finally {
[17/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentLifecycle.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentLifecycle.java b/utils/src/main/java/com/cloud/utils/component/ComponentLifecycle.java
new file mode 100644
index 0000000..897ddb1
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentLifecycle.java
@@ -0,0 +1,64 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+public interface ComponentLifecycle extends Named {
+ public static final int RUN_LEVEL_SYSTEM_BOOTSTRAP = 0; // for system level bootstrap components
+ public static final int RUN_LEVEL_SYSTEM = 1; // for system level service components (i.e., DAOs)
+ public static final int RUN_LEVEL_FRAMEWORK_BOOTSTRAP = 2; // for framework startup checkers (i.e., DB migration check)
+ public static final int RUN_LEVEL_FRAMEWORK = 3; // for framework bootstrap components(i.e., clustering management components)
+ public static final int RUN_LEVEL_COMPONENT_BOOTSTRAP = 4; // general manager components
+ public static final int RUN_LEVEL_COMPONENT = 5; // regular adapters, plugin components
+ public static final int RUN_LEVEL_APPLICATION_MAINLOOP = 6;
+ public static final int MAX_RUN_LEVELS = 7;
+
+ @Override
+ String getName();
+
+ void setName(String name);
+
+ void setConfigParams(Map<String, Object> params);
+
+ Map<String, Object> getConfigParams();
+
+ int getRunLevel();
+
+ void setRunLevel(int level);
+
+ public boolean configure(String name, Map<String, Object> params) throws ConfigurationException;
+
+ /**
+ * Start any background tasks.
+ *
+ * @return true if the tasks were started, false otherwise.
+ */
+ public boolean start();
+
+ /**
+ * Stop any background tasks.
+ *
+ * @return true background tasks were stopped, false otherwise.
+ */
+ public boolean stop();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentLifecycleBase.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentLifecycleBase.java b/utils/src/main/java/com/cloud/utils/component/ComponentLifecycleBase.java
new file mode 100644
index 0000000..829dc9b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentLifecycleBase.java
@@ -0,0 +1,87 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+
+public class ComponentLifecycleBase implements ComponentLifecycle {
+ private static final Logger s_logger = Logger.getLogger(ComponentLifecycleBase.class);
+
+ protected String _name;
+ protected int _runLevel;
+ protected Map<String, Object> _configParams = new HashMap<String, Object>();
+
+ public ComponentLifecycleBase() {
+ _name = this.getClass().getSimpleName();
+ _runLevel = RUN_LEVEL_COMPONENT;
+ }
+
+ @Override
+ public String getName() {
+ return _name;
+ }
+
+ @Override
+ public void setName(String name) {
+ _name = name;
+ }
+
+ @Override
+ public void setConfigParams(Map<String, Object> params) {
+ _configParams = params;
+ }
+
+ @Override
+ public Map<String, Object> getConfigParams() {
+ return _configParams;
+ }
+
+ @Override
+ public int getRunLevel() {
+ return _runLevel;
+ }
+
+ @Override
+ public void setRunLevel(int level) {
+ _runLevel = level;
+ }
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+ _name = name;
+ _configParams = params;
+ return true;
+ }
+
+ @Override
+ public boolean start() {
+ return true;
+ }
+
+ @Override
+ public boolean stop() {
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptable.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptable.java b/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptable.java
new file mode 100644
index 0000000..4d94391
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptable.java
@@ -0,0 +1,27 @@
+//
+// 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 com.cloud.utils.component;
+
+/**
+ * Marker interface to work with CGLIB based CloudStack legacy AOP
+ *
+ */
+public interface ComponentMethodInterceptable {
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptor.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptor.java b/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptor.java
new file mode 100644
index 0000000..dca688a
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptor.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.lang.reflect.Method;
+
+public interface ComponentMethodInterceptor {
+ boolean needToIntercept(Method method);
+
+ Object interceptStart(Method method, Object target);
+
+ void interceptComplete(Method method, Object target, Object objReturnedInInterceptStart);
+
+ void interceptException(Method method, Object target, Object objReturnedInInterceptStart);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentNamingPolicy.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentNamingPolicy.java b/utils/src/main/java/com/cloud/utils/component/ComponentNamingPolicy.java
new file mode 100644
index 0000000..33d1dd4
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentNamingPolicy.java
@@ -0,0 +1,65 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.component;
+
+import net.sf.cglib.core.NamingPolicy;
+import net.sf.cglib.core.Predicate;
+
+/**
+ * Copied/Modified from Spring source
+ *
+ */
+public class ComponentNamingPolicy implements NamingPolicy {
+
+ public static final ComponentNamingPolicy INSTANCE = new ComponentNamingPolicy();
+
+ @Override
+ public String getClassName(String prefix, String source, Object key, Predicate names) {
+ if (prefix == null) {
+ prefix = "net.sf.cglib.empty.Object";
+ } else if (prefix.startsWith("java")) {
+ prefix = "_" + prefix;
+ }
+ String base = prefix + "_" + source.substring(source.lastIndexOf('.') + 1) + getTag() + "_" + Integer.toHexString(key.hashCode());
+ String attempt = base;
+ int index = 2;
+ while (names.evaluate(attempt))
+ attempt = base + "_" + index++;
+ return attempt;
+ }
+
+ /**
+ * Returns a string which is incorporated into every generated class name.
+ * By default returns "ByCloudStack"
+ */
+ protected String getTag() {
+ return "ByCloudStack";
+ }
+
+ @Override
+ public int hashCode() {
+ return getTag().hashCode();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return (o instanceof ComponentNamingPolicy) && ((ComponentNamingPolicy)o).getTag().equals(getTag());
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/Manager.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/Manager.java b/utils/src/main/java/com/cloud/utils/component/Manager.java
new file mode 100644
index 0000000..3200b46
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/Manager.java
@@ -0,0 +1,27 @@
+//
+// 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 com.cloud.utils.component;
+
+/**
+ *
+ * For now we only expose some simple methods. In the future, we can use this
+ **/
+public interface Manager extends ComponentLifecycle {
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ManagerBase.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ManagerBase.java b/utils/src/main/java/com/cloud/utils/component/ManagerBase.java
new file mode 100644
index 0000000..01e4f40
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ManagerBase.java
@@ -0,0 +1,28 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.component;
+
+public class ManagerBase extends ComponentLifecycleBase implements ComponentMethodInterceptable {
+ public ManagerBase() {
+ super();
+ // set default run level for manager components
+ setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT_BOOTSTRAP);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/Named.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/Named.java b/utils/src/main/java/com/cloud/utils/component/Named.java
new file mode 100644
index 0000000..60835b0
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/Named.java
@@ -0,0 +1,26 @@
+//
+// 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 com.cloud.utils.component;
+
+public interface Named {
+
+ String getName();
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/PluggableService.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/PluggableService.java b/utils/src/main/java/com/cloud/utils/component/PluggableService.java
new file mode 100644
index 0000000..60c64bf
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/PluggableService.java
@@ -0,0 +1,29 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.component;
+
+import java.util.List;
+
+// This interface defines methods for pluggable code within the Cloud Stack.
+public interface PluggableService {
+ // The config command properties filenames that lists allowed API commands
+ // and role masks supported by this pluggable service
+ List<Class<?>> getCommands();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/Registry.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/Registry.java b/utils/src/main/java/com/cloud/utils/component/Registry.java
new file mode 100644
index 0000000..d3a48df
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/Registry.java
@@ -0,0 +1,51 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.util.List;
+
+/**
+ * Simple interface to represents a registry of items
+ *
+ * @param <T>
+ */
+public interface Registry<T> extends Named {
+
+ /**
+ * Registers an item. If the item has already been registered the implementation
+ * should detect that it is registered and not re-register it.
+ *
+ * @param type
+ * @return true if register, false if not registered or already exists
+ */
+ boolean register(T type);
+
+ void unregister(T type);
+
+ /**
+ * Returns a list that will dynamically change as items are registered/unregister.
+ * The list is thread safe to iterate upon. Traversing the list using an index
+ * would not be safe as the size may changed during traversal.
+ *
+ * @return Unmodifiable list of registered items
+ */
+ List<T> getRegistered();
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/SystemIntegrityChecker.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/SystemIntegrityChecker.java b/utils/src/main/java/com/cloud/utils/component/SystemIntegrityChecker.java
new file mode 100644
index 0000000..a0e2581
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/SystemIntegrityChecker.java
@@ -0,0 +1,30 @@
+//
+// 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 com.cloud.utils.component;
+
+/**
+ * before any other components are loaded. Within ComponentLocator
+ * database upgrades and other verification to make sure it works.
+ */
+public interface SystemIntegrityChecker {
+ public static final String Name = "system-integrity-checker";
+
+ void check();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/concurrency/NamedThreadFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/concurrency/NamedThreadFactory.java b/utils/src/main/java/com/cloud/utils/concurrency/NamedThreadFactory.java
new file mode 100644
index 0000000..ed4d6b0
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/concurrency/NamedThreadFactory.java
@@ -0,0 +1,38 @@
+//
+// 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 com.cloud.utils.concurrency;
+
+import java.util.concurrent.ThreadFactory;
+
+public class NamedThreadFactory implements ThreadFactory {
+ private int _number;
+ private final String _name;
+
+ public NamedThreadFactory(String name) {
+ _name = name;
+ _number = 1;
+ }
+
+ @Override
+ public synchronized Thread newThread(Runnable r) {
+ return new Thread(r, _name + "-" + _number++);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/concurrency/Scheduler.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/concurrency/Scheduler.java b/utils/src/main/java/com/cloud/utils/concurrency/Scheduler.java
new file mode 100644
index 0000000..e0dba24
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/concurrency/Scheduler.java
@@ -0,0 +1,31 @@
+//
+// 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 com.cloud.utils.concurrency;
+
+import java.util.Date;
+
+public interface Scheduler {
+
+ /**
+ * This is called from the TimerTask thread periodically about every one minute.
+ *
+ */
+ public void poll(Date currentTimestamp);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java b/utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java
new file mode 100644
index 0000000..5207ad4
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java
@@ -0,0 +1,89 @@
+//
+// 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 com.cloud.utils.concurrency;
+
+import org.apache.log4j.Logger;
+
+public class SynchronizationEvent {
+ protected final static Logger s_logger = Logger.getLogger(SynchronizationEvent.class);
+
+ private boolean signalled;
+
+ public SynchronizationEvent() {
+ signalled = false;
+ }
+
+ public SynchronizationEvent(boolean signalled) {
+ this.signalled = signalled;
+ }
+
+ public void setEvent() {
+ synchronized (this) {
+ signalled = true;
+ notifyAll();
+ }
+ }
+
+ public void resetEvent() {
+ synchronized (this) {
+ signalled = false;
+ }
+ }
+
+ public boolean waitEvent() throws InterruptedException {
+ synchronized (this) {
+ if (signalled)
+ return true;
+
+ while (true) {
+ try {
+ wait();
+ assert (signalled);
+ return signalled;
+ } catch (InterruptedException e) {
+ s_logger.debug("unexpected awaken signal in wait()");
+ throw e;
+ }
+ }
+ }
+ }
+
+ public boolean waitEvent(long timeOutMiliseconds) throws InterruptedException {
+ synchronized (this) {
+ if (signalled)
+ return true;
+
+ try {
+ wait(timeOutMiliseconds);
+ return signalled;
+ } catch (InterruptedException e) {
+ // TODO, we don't honor time out semantics when the waiting thread is interrupted
+ s_logger.debug("unexpected awaken signal in wait(...)");
+ throw e;
+ }
+ }
+ }
+
+ public boolean isSignalled() {
+ synchronized (this) {
+ return signalled;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/concurrency/TestClock.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/concurrency/TestClock.java b/utils/src/main/java/com/cloud/utils/concurrency/TestClock.java
new file mode 100644
index 0000000..43fe56f
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/concurrency/TestClock.java
@@ -0,0 +1,161 @@
+//
+// 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 com.cloud.utils.concurrency;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimerTask;
+
+/**
+ * A test clock which is also a TimerTask. The task calls a Scheduler's poll method
+ *
+ */
+public class TestClock extends TimerTask {
+ private int _minute = 0;
+ private int _hour = 0;
+ private int _day = 0;
+ private int _week = 0;
+ private int _month = 0;
+ private int _year = 0;
+ private Calendar _cal = null;
+ private final int _minutesPerHour;
+ private final int _hoursPerDay;
+ private final int _daysPerWeek;
+ private final int _daysPerMonth;
+ private final int _weeksPerMonth;
+ private final int _monthsPerYear;
+ private final Scheduler _scheduler;
+
+ public TestClock(Scheduler scheduler, int minutesPerHour, int hoursPerDay, int daysPerWeek, int daysPerMonth, int weeksPerMonth, int monthsPerYear) {
+ _minutesPerHour = minutesPerHour;
+ _hoursPerDay = hoursPerDay;
+ _daysPerWeek = daysPerWeek;
+ _daysPerMonth = daysPerMonth;
+ _weeksPerMonth = weeksPerMonth;
+ _monthsPerYear = monthsPerYear;
+ _cal = Calendar.getInstance();
+ _year = _cal.get(Calendar.YEAR);
+ _month = _cal.get(Calendar.MONTH);
+ _day = _cal.get(Calendar.DAY_OF_MONTH);
+ _week = _cal.get(Calendar.WEEK_OF_MONTH);
+ _hour = _cal.get(Calendar.HOUR_OF_DAY);
+ _minute = _cal.get(Calendar.MINUTE);
+ _scheduler = scheduler;
+ }
+
+ public int getMinute() {
+ synchronized (this) {
+ return _minute;
+ }
+ }
+
+ public int getHour() {
+ synchronized (this) {
+ return _hour;
+ }
+ }
+
+ public int getDay() {
+ synchronized (this) {
+ return _day;
+ }
+ }
+
+ public int getWeek() {
+ synchronized (this) {
+ return _week;
+ }
+ }
+
+ public int getMonth() {
+ synchronized (this) {
+ return _month;
+ }
+ }
+
+ public int getYear() {
+ synchronized (this) {
+ return _year;
+ }
+ }
+
+ public int getMinutesPerHour() {
+ return _minutesPerHour;
+ }
+
+ public int getHoursPerDay() {
+ return _hoursPerDay;
+ }
+
+ public int getDaysPerMonth() {
+ return _daysPerMonth;
+ }
+
+ public int getDaysPerWeek() {
+ return _daysPerWeek;
+ }
+
+ public int getWeeksPerMonth() {
+ return _weeksPerMonth;
+ }
+
+ public int getMonthsPerYear() {
+ return _monthsPerYear;
+ }
+
+ @Override
+ public void run() {
+ synchronized (this) {
+ _minute++;
+ if ((_minute > 0) && ((_minute % _minutesPerHour) == 0)) {
+ _minute = 0;
+ _hour++;
+ }
+
+ if ((_hour > 0) && ((_hour % _hoursPerDay) == 0)) {
+ _hour = 0;
+ _day++;
+ }
+
+ if ((_day > 0) && ((_day % _daysPerWeek) == 0)) {
+ _week++;
+ }
+
+ if ((_day > 0) && ((_day % _daysPerMonth) == 0)) {
+ _day = 0;
+ _week = 0;
+ _month++;
+ }
+
+ if ((_month > 0) && ((_month % _monthsPerYear) == 0)) {
+ _month = 0;
+ _year++;
+ }
+ if (_scheduler != null) {
+ // XXX: Creating new date is hugely inefficient for every minute.
+ // Later the time in the database will be changed to currentTimeInMillis.
+ // Then we can use System.getCurrentTimeInMillis() which is damn cheap.
+ _cal.set(_year, _month, _day, _hour, _minute);
+ Date currentTimestamp = _cal.getTime();
+ _scheduler.poll(currentTimestamp);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/crypt/DBEncryptionUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/crypt/DBEncryptionUtil.java b/utils/src/main/java/com/cloud/utils/crypt/DBEncryptionUtil.java
new file mode 100644
index 0000000..52f2034
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/crypt/DBEncryptionUtil.java
@@ -0,0 +1,87 @@
+//
+// 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 com.cloud.utils.crypt;
+
+import java.util.Properties;
+
+import org.apache.log4j.Logger;
+import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
+import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
+
+import com.cloud.utils.db.DbProperties;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class DBEncryptionUtil {
+
+ public static final Logger s_logger = Logger.getLogger(DBEncryptionUtil.class);
+ private static StandardPBEStringEncryptor s_encryptor = null;
+
+ public static String encrypt(String plain) {
+ if (!EncryptionSecretKeyChecker.useEncryption() || (plain == null) || plain.isEmpty()) {
+ return plain;
+ }
+ if (s_encryptor == null) {
+ initialize();
+ }
+ String encryptedString = null;
+ try {
+ encryptedString = s_encryptor.encrypt(plain);
+ } catch (EncryptionOperationNotPossibleException e) {
+ s_logger.debug("Error while encrypting: " + plain);
+ throw e;
+ }
+ return encryptedString;
+ }
+
+ public static String decrypt(String encrypted) {
+ if (!EncryptionSecretKeyChecker.useEncryption() || (encrypted == null) || encrypted.isEmpty()) {
+ return encrypted;
+ }
+ if (s_encryptor == null) {
+ initialize();
+ }
+
+ String plain = null;
+ try {
+ plain = s_encryptor.decrypt(encrypted);
+ } catch (EncryptionOperationNotPossibleException e) {
+ s_logger.debug("Error while decrypting: " + encrypted);
+ throw e;
+ }
+ return plain;
+ }
+
+ private static void initialize() {
+ final Properties dbProps = DbProperties.getDbProperties();
+
+ if (EncryptionSecretKeyChecker.useEncryption()) {
+ String dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret");
+ if (dbSecretKey == null || dbSecretKey.isEmpty()) {
+ throw new CloudRuntimeException("Empty DB secret key in db.properties");
+ }
+
+ s_encryptor = new StandardPBEStringEncryptor();
+ s_encryptor.setAlgorithm("PBEWithMD5AndDES");
+ s_encryptor.setPassword(dbSecretKey);
+ } else {
+ throw new CloudRuntimeException("Trying to encrypt db values when encrytion is not enabled");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java b/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java
new file mode 100644
index 0000000..6524987
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java
@@ -0,0 +1,146 @@
+//
+// 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 com.cloud.utils.crypt;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Properties;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.log4j.Logger;
+import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
+import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
+
+import com.cloud.utils.db.DbProperties;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class EncryptionSecretKeyChecker {
+
+ private static final Logger s_logger = Logger.getLogger(EncryptionSecretKeyChecker.class);
+
+ // Two possible locations with the new packaging naming
+ private static final String s_altKeyFile = "key";
+ private static final String s_keyFile = "key";
+ private static final String s_envKey = "CLOUD_SECRET_KEY";
+ private static StandardPBEStringEncryptor s_encryptor = new StandardPBEStringEncryptor();
+ private static boolean s_useEncryption = false;
+
+ @PostConstruct
+ public void init() {
+ /* This will call DbProperties, which will call this to initialize the encryption. Yep,
+ * round about and annoying */
+ DbProperties.getDbProperties();
+ }
+
+ public void check(Properties dbProps) throws IOException {
+ String encryptionType = dbProps.getProperty("db.cloud.encryption.type");
+
+ s_logger.debug("Encryption Type: " + encryptionType);
+
+ if (encryptionType == null || encryptionType.equals("none")) {
+ return;
+ }
+
+ if (s_useEncryption) {
+ s_logger.warn("Encryption already enabled, is check() called twice?");
+ return;
+ }
+
+ s_encryptor.setAlgorithm("PBEWithMD5AndDES");
+ String secretKey = null;
+
+ SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig();
+
+ if (encryptionType.equals("file")) {
+ InputStream is = this.getClass().getClassLoader().getResourceAsStream(s_keyFile);
+ if (is == null) {
+ is = this.getClass().getClassLoader().getResourceAsStream(s_altKeyFile);
+ }
+ if(is == null) { //This is means we are not able to load key file from the classpath.
+ throw new CloudRuntimeException(s_keyFile + " File containing secret key not found in the classpath: ");
+ }
+
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(is));) {
+ secretKey = in.readLine();
+ //Check for null or empty secret key
+ } catch (IOException e) {
+ throw new CloudRuntimeException("Error while reading secret key from: " + s_keyFile, e);
+ }
+
+ if (secretKey == null || secretKey.isEmpty()) {
+ throw new CloudRuntimeException("Secret key is null or empty in file " + s_keyFile);
+ }
+
+ } else if (encryptionType.equals("env")) {
+ secretKey = System.getenv(s_envKey);
+ if (secretKey == null || secretKey.isEmpty()) {
+ throw new CloudRuntimeException("Environment variable " + s_envKey + " is not set or empty");
+ }
+ } else if (encryptionType.equals("web")) {
+ int port = 8097;
+ try (ServerSocket serverSocket = new ServerSocket(port);) {
+ s_logger.info("Waiting for admin to send secret key on port " + port);
+ try (
+ Socket clientSocket = serverSocket.accept();
+ PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
+ BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ ) {
+ String inputLine;
+ if ((inputLine = in.readLine()) != null) {
+ secretKey = inputLine;
+ }
+ } catch (IOException e) {
+ throw new CloudRuntimeException("Accept failed on " + port);
+ }
+ } catch (IOException ioex) {
+ throw new CloudRuntimeException("Error initializing secret key reciever", ioex);
+ }
+ } else {
+ throw new CloudRuntimeException("Invalid encryption type: " + encryptionType);
+ }
+
+ stringConfig.setPassword(secretKey);
+ s_encryptor.setConfig(stringConfig);
+ s_useEncryption = true;
+ }
+
+ public static StandardPBEStringEncryptor getEncryptor() {
+ return s_encryptor;
+ }
+
+ public static boolean useEncryption() {
+ return s_useEncryption;
+ }
+
+ //Initialize encryptor for migration during secret key change
+ public static void initEncryptorForMigration(String secretKey) {
+ s_encryptor.setAlgorithm("PBEWithMD5AndDES");
+ SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig();
+ stringConfig.setPassword(secretKey);
+ s_encryptor.setConfig(stringConfig);
+ s_useEncryption = true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeySender.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeySender.java b/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeySender.java
new file mode 100644
index 0000000..ed44ac6
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeySender.java
@@ -0,0 +1,65 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.crypt;
+
+
+import java.io.PrintWriter;
+import java.net.InetAddress;
+import java.net.Socket;
+import com.cloud.utils.NumbersUtil;
+
+
+public class EncryptionSecretKeySender {
+ public static void main(String args[]) {
+ try {
+ // Create a socket to the host
+ String hostname = "localhost";
+ int port = 8097;
+
+ if (args.length == 2) {
+ hostname = args[0];
+ port = NumbersUtil.parseInt(args[1], port);
+ }
+ InetAddress addr = InetAddress.getByName(hostname);
+ try(Socket socket = new Socket(addr, port);
+ PrintWriter out = new PrintWriter(socket.getOutputStream(), true);)
+ {
+ java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
+ String validationWord = "cloudnine";
+ String validationInput = "";
+ while (!validationWord.equals(validationInput)) {
+ System.out.print("Enter Validation Word:");
+ validationInput = stdin.readLine();
+ System.out.println();
+ }
+ System.out.print("Enter Secret Key:");
+ String input = stdin.readLine();
+ if (input != null) {
+ out.println(input);
+ }
+ }catch (Exception e)
+ {
+ System.out.println("Exception " + e.getMessage());
+ }
+ } catch (Exception e) {
+ System.out.print("Exception while sending secret key " + e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/crypt/RSAHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/crypt/RSAHelper.java b/utils/src/main/java/com/cloud/utils/crypt/RSAHelper.java
new file mode 100644
index 0000000..692ac22
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/crypt/RSAHelper.java
@@ -0,0 +1,90 @@
+//
+// 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 com.cloud.utils.crypt;
+
+import java.io.ByteArrayInputStream;
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.KeyFactory;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.KeySpec;
+import java.security.spec.RSAPublicKeySpec;
+
+import javax.crypto.Cipher;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+
+public class RSAHelper {
+ final static Logger s_logger = Logger.getLogger(RSAHelper.class);
+
+ static {
+ BouncyCastleProvider provider = new BouncyCastleProvider();
+ if (Security.getProvider(provider.getName()) == null)
+ Security.addProvider(provider);
+ }
+
+ private static RSAPublicKey readKey(String key) throws Exception {
+ byte[] encKey = Base64.decodeBase64(key.split(" ")[1]);
+ DataInputStream dis = new DataInputStream(new ByteArrayInputStream(encKey));
+
+ byte[] header = readElement(dis);
+ String pubKeyFormat = new String(header);
+ if (!pubKeyFormat.equals("ssh-rsa"))
+ throw new RuntimeException("Unsupported format");
+
+ byte[] publicExponent = readElement(dis);
+ byte[] modulus = readElement(dis);
+
+ KeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
+ RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(spec);
+
+ return pubKey;
+ }
+
+ private static byte[] readElement(DataInput dis) throws IOException {
+ int len = dis.readInt();
+ byte[] buf = new byte[len];
+ dis.readFully(buf);
+ return buf;
+ }
+
+ public static String encryptWithSSHPublicKey(String sshPublicKey, String content) {
+ String returnString = null;
+ try {
+ RSAPublicKey publicKey = readKey(sshPublicKey);
+ Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
+ cipher.init(Cipher.ENCRYPT_MODE, publicKey, new SecureRandom());
+ byte[] encrypted = cipher.doFinal(content.getBytes());
+ returnString = Base64.encodeBase64String(encrypted);
+ } catch (Exception e) {
+ s_logger.info("[ignored]"
+ + "error during public key encryption: " + e.getLocalizedMessage());
+ }
+
+ return returnString;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/db/DbProperties.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/db/DbProperties.java b/utils/src/main/java/com/cloud/utils/db/DbProperties.java
new file mode 100644
index 0000000..8420614
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/db/DbProperties.java
@@ -0,0 +1,109 @@
+//
+// 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 com.cloud.utils.db;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
+import org.jasypt.properties.EncryptableProperties;
+
+import com.cloud.utils.PropertiesUtil;
+import com.cloud.utils.crypt.EncryptionSecretKeyChecker;
+
+public class DbProperties {
+
+ private static final Logger log = Logger.getLogger(DbProperties.class);
+
+ private static Properties properties = new Properties();
+ private static boolean loaded = false;
+
+ protected static Properties wrapEncryption(Properties dbProps) throws IOException {
+ EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker();
+ checker.check(dbProps);
+
+ if (EncryptionSecretKeyChecker.useEncryption()) {
+ return dbProps;
+ } else {
+ EncryptableProperties encrProps = new EncryptableProperties(EncryptionSecretKeyChecker.getEncryptor());
+ encrProps.putAll(dbProps);
+ return encrProps;
+ }
+ }
+
+ public synchronized static Properties getDbProperties() {
+ if (!loaded) {
+ Properties dbProps = new Properties();
+ InputStream is = null;
+ try {
+ File props = PropertiesUtil.findConfigFile("db.properties");
+ if (props != null && props.exists()) {
+ is = new FileInputStream(props);
+ }
+
+ if (is == null) {
+ is = PropertiesUtil.openStreamFromURL("db.properties");
+ }
+
+ if (is == null) {
+ System.err.println("Failed to find db.properties");
+ log.error("Failed to find db.properties");
+ }
+
+ if (is != null) {
+ dbProps.load(is);
+ }
+
+ EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker();
+ checker.check(dbProps);
+
+ if (EncryptionSecretKeyChecker.useEncryption()) {
+ StandardPBEStringEncryptor encryptor = EncryptionSecretKeyChecker.getEncryptor();
+ EncryptableProperties encrDbProps = new EncryptableProperties(encryptor);
+ encrDbProps.putAll(dbProps);
+ dbProps = encrDbProps;
+ }
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to load db.properties", e);
+ } finally {
+ IOUtils.closeQuietly(is);
+ }
+
+ properties = dbProps;
+ loaded = true;
+ }
+
+ return properties;
+ }
+
+ public synchronized static Properties setDbProperties(Properties props) throws IOException {
+ if (loaded) {
+ throw new IllegalStateException("DbProperties has already been loaded");
+ }
+ properties = wrapEncryption(props);
+ loaded = true;
+ return properties;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/db/EntityManager.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/db/EntityManager.java b/utils/src/main/java/com/cloud/utils/db/EntityManager.java
new file mode 100644
index 0000000..8f4e385
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/db/EntityManager.java
@@ -0,0 +1,84 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.db;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * Generic Entity Manager to retrieve database objects.
+ *
+ */
+public interface EntityManager {
+ /**
+ * Finds an entity by its id.
+ * @param <T> class of the entity you're trying to find.
+ * @param <K> class of the id that the entity uses.
+ * @param entityType Type of the entity.
+ * @param id id value
+ * @return T if found; null if not.
+ */
+ public <T, K extends Serializable> T findById(Class<T> entityType, K id);
+
+ /**
+ * Finds a unique entity by uuid string
+ * @param <T> entity class
+ * @param entityType type of entity you're looking for.
+ * @param uuid the unique id
+ * @return T if found, null if not.
+ */
+ public <T> T findByUuid(Class<T> entityType, String uuid);
+
+ /**
+ * Finds a unique entity by uuid string, including those removed entries
+ * @param <T> entity class
+ * @param entityType type of entity you're looking for.
+ * @param uuid the unique id
+ * @return T if found, null if not.
+ */
+ public <T> T findByUuidIncludingRemoved(Class<T> entityType, String uuid);
+
+ /**
+ * Finds an entity by external id which is always String
+ * @param <T> entity class
+ * @param entityType type of entity you're looking for.
+ * @param xid external id
+ * @return T if found, null if not.
+ */
+ public <T> T findByXId(Class<T> entityType, String xid);
+
+ /**
+ * Lists all entities. Use this method at your own risk.
+ * @param <T> entity class
+ * @param entityType type of entity you're looking for.
+ * @return List<T>
+ */
+ public <T> List<? extends T> list(Class<T> entityType);
+
+ public <T, K extends Serializable> void remove(Class<T> entityType, K id);
+
+ public <T, K extends Serializable> T findByIdIncludingRemoved(Class<T> entityType, K id);
+
+ public static final String MESSAGE_REMOVE_ENTITY_EVENT = "Message.RemoveEntity.Event";
+
+ public static final String MESSAGE_GRANT_ENTITY_EVENT = "Message.GrantEntity.Event";
+ public static final String MESSAGE_REVOKE_ENTITY_EVENT = "Message.RevokeEntity.Event";
+ public static final String MESSAGE_ADD_DOMAIN_WIDE_ENTITY_EVENT = "Message.AddDomainWideEntity.Event";
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/db/UUIDManager.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/db/UUIDManager.java b/utils/src/main/java/com/cloud/utils/db/UUIDManager.java
new file mode 100644
index 0000000..cac1876
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/db/UUIDManager.java
@@ -0,0 +1,48 @@
+//
+// 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 com.cloud.utils.db;
+
+
+public interface UUIDManager {
+
+ /**
+ * Generates a new uuid or uses the customId
+ * @param entityType the type of entity
+ * @param customId optional custom uuid of the object.
+ * @return newly created uuid.
+ */
+ public <T> String generateUuid(Class<T> entityType, String customId);
+
+ /**
+ * Checks the uuid for correct format, uniqueness and permissions.
+ * @param uuid uuid to check
+ * @param entityType the type of entity
+ * .
+ */
+ <T> void checkUuid(String uuid, Class<T> entityType);
+
+ /**
+ * Checks the uuid for correct format, uniqueness, without checking permissions
+ * @param uuid uuid to check
+ * @param entityType the type of entity
+ * .
+ */
+ <T> void checkUuidSimple(String uuid, Class<T> entityType);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/encoding/URLEncoder.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/encoding/URLEncoder.java b/utils/src/main/java/com/cloud/utils/encoding/URLEncoder.java
new file mode 100644
index 0000000..58971e7
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/encoding/URLEncoder.java
@@ -0,0 +1,113 @@
+//
+// 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 com.cloud.utils.encoding;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.util.BitSet;
+
+/**
+ *
+ * This class is very similar to the java.net.URLEncoder class.
+ *
+ * Unfortunately, with java.net.URLEncoder there is no way to specify to the
+ * java.net.URLEncoder which characters should NOT be encoded.
+ *
+ * This code was moved from DefaultServlet.java
+ *
+ * @author Craig R. McClanahan
+ * @author Remy Maucherat
+ */
+
+public class URLEncoder {
+ protected static final char[] hexadecimal = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+ static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder(); // or "ISO-8859-1" for ISO Latin 1
+
+ //Array containing the safe characters set.
+ protected BitSet safeCharacters = new BitSet(256);
+
+ public URLEncoder() {
+ for (char i = 'a'; i <= 'z'; i++) {
+ addSafeCharacter(i);
+ }
+ for (char i = 'A'; i <= 'Z'; i++) {
+ addSafeCharacter(i);
+ }
+ for (char i = '0'; i <= '9'; i++) {
+ addSafeCharacter(i);
+ }
+ }
+
+ private void addSafeCharacter(char c) {
+ safeCharacters.set(c);
+ }
+
+ public String encode(String path) {
+ int maxBytesPerChar = 10;
+ StringBuffer rewrittenPath = new StringBuffer(path.length());
+ ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
+ OutputStreamWriter writer = null;
+ try {
+ writer = new OutputStreamWriter(buf, "UTF8");
+ } catch (Exception e) {
+ e.printStackTrace();
+ writer = new OutputStreamWriter(buf);
+ }
+
+ for (int i = 0; i < path.length(); i++) {
+ int c = path.charAt(i);
+ // NOTICE - !isPureAscii(path.charAt(i)) check was added by
+ // CloudStack
+ if (safeCharacters.get(c) || !isPureAscii(path.charAt(i))) {
+ rewrittenPath.append((char)c);
+ } else {
+ // convert to external encoding before hex conversion
+ try {
+ writer.write((char)c);
+ writer.flush();
+ } catch (IOException e) {
+ buf.reset();
+ continue;
+ }
+ byte[] ba = buf.toByteArray();
+ for (int j = 0; j < ba.length; j++) {
+ // Converting each byte in the buffer
+ byte toEncode = ba[j];
+ rewrittenPath.append('%');
+ int low = toEncode & 0x0f;
+ int high = (toEncode & 0xf0) >> 4;
+ rewrittenPath.append(hexadecimal[high]);
+ rewrittenPath.append(hexadecimal[low]);
+ }
+ buf.reset();
+ }
+ }
+ return rewrittenPath.toString();
+ }
+
+ // NOTICE - this part was added by CloudStack
+ public static boolean isPureAscii(Character v) {
+ return asciiEncoder.canEncode(v);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/events/EventArgs.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/events/EventArgs.java b/utils/src/main/java/com/cloud/utils/events/EventArgs.java
new file mode 100644
index 0000000..5c06b4b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/events/EventArgs.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.events;
+
+import java.io.Serializable;
+
+public class EventArgs implements Serializable {
+ private static final long serialVersionUID = 30659016120504139L;
+ public static final EventArgs Empty = new EventArgs();
+
+ private String subject;
+
+ public EventArgs() {
+ }
+
+ public EventArgs(String subject) {
+ this.subject = subject;
+ }
+
+ public String getSubject() {
+ return subject;
+ }
+
+ public void setSubject(String subject) {
+ this.subject = subject;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/events/SubscriptionMgr.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/events/SubscriptionMgr.java b/utils/src/main/java/com/cloud/utils/events/SubscriptionMgr.java
new file mode 100644
index 0000000..254c27d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/events/SubscriptionMgr.java
@@ -0,0 +1,164 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.events;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+
+public class SubscriptionMgr {
+ protected final static Logger s_logger = Logger.getLogger(SubscriptionMgr.class);
+
+ private static SubscriptionMgr s_instance = new SubscriptionMgr();
+
+ private Map<String, List<SubscriberInfo>> registry;
+
+ private SubscriptionMgr() {
+ registry = new HashMap<String, List<SubscriberInfo>>();
+ }
+
+ public static SubscriptionMgr getInstance() {
+ return s_instance;
+ }
+
+ public <T> void subscribe(String subject, T subscriber, String listenerMethod) throws SecurityException, NoSuchMethodException {
+
+ synchronized (this) {
+ List<SubscriberInfo> l = getAndSetSubscriberList(subject);
+
+ Class<?> clazz = subscriber.getClass();
+ SubscriberInfo subscribeInfo = new SubscriberInfo(clazz, subscriber, listenerMethod);
+
+ if (!l.contains(subscribeInfo))
+ l.add(subscribeInfo);
+ }
+ }
+
+ public <T> void unsubscribe(String subject, T subscriber, String listenerMethod) {
+ synchronized (this) {
+ List<SubscriberInfo> l = getSubscriberList(subject);
+ if (l != null) {
+ for (SubscriberInfo info : l) {
+ if (info.isMe(subscriber.getClass(), subscriber, listenerMethod)) {
+ l.remove(info);
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ public void notifySubscribers(String subject, Object sender, EventArgs args) {
+
+ List<SubscriberInfo> l = getExecutableSubscriberList(subject);
+ if (l != null) {
+ for (SubscriberInfo info : l) {
+ try {
+ info.execute(sender, args);
+ } catch (IllegalArgumentException e) {
+ s_logger.warn("Exception on notifying event subscribers: ", e);
+ } catch (IllegalAccessException e) {
+ s_logger.warn("Exception on notifying event subscribers: ", e);
+ } catch (InvocationTargetException e) {
+ s_logger.warn("Exception on notifying event subscribers: ", e);
+ }
+ }
+ }
+ }
+
+ private List<SubscriberInfo> getAndSetSubscriberList(String subject) {
+ List<SubscriberInfo> l = registry.get(subject);
+ if (l == null) {
+ l = new ArrayList<SubscriberInfo>();
+ registry.put(subject, l);
+ }
+
+ return l;
+ }
+
+ private List<SubscriberInfo> getSubscriberList(String subject) {
+ return registry.get(subject);
+ }
+
+ private synchronized List<SubscriberInfo> getExecutableSubscriberList(String subject) {
+ List<SubscriberInfo> l = registry.get(subject);
+ if (l != null) {
+ // do a shadow clone
+ ArrayList<SubscriberInfo> clonedList = new ArrayList<SubscriberInfo>(l.size());
+ for (SubscriberInfo info : l)
+ clonedList.add(info);
+
+ return clonedList;
+ }
+ return null;
+ }
+
+ private static class SubscriberInfo {
+ private Class<?> clazz;
+ private Object subscriber;
+ private String methodName;
+ private Method method;
+
+ public SubscriberInfo(Class<?> clazz, Object subscriber, String methodName) throws SecurityException, NoSuchMethodException {
+
+ this.clazz = clazz;
+ this.subscriber = subscriber;
+ this.methodName = methodName;
+ for (Method method : clazz.getMethods()) {
+ if (method.getName().equals(methodName)) {
+ Class<?>[] paramTypes = method.getParameterTypes();
+ if (paramTypes != null && paramTypes.length == 2 && paramTypes[0] == Object.class && EventArgs.class.isAssignableFrom(paramTypes[1])) {
+ this.method = method;
+
+ break;
+ }
+ }
+ }
+ if (this.method == null)
+ throw new NoSuchMethodException();
+ }
+
+ public void execute(Object sender, EventArgs args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
+
+ method.invoke(subscriber, sender, args);
+ }
+
+ public boolean isMe(Class<?> clazz, Object subscriber, String methodName) {
+ return this.clazz == clazz && this.subscriber == subscriber && this.methodName.equals(methodName);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null)
+ return false;
+
+ if (o instanceof SubscriberInfo) {
+ return this.clazz == ((SubscriberInfo)o).clazz && this.subscriber == ((SubscriberInfo)o).subscriber &&
+ this.methodName.equals(((SubscriberInfo)o).methodName);
+ }
+ return false;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java b/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java
new file mode 100644
index 0000000..62af14e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java
@@ -0,0 +1,100 @@
+//
+// 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 com.cloud.utils.exception;
+
+import java.util.HashMap;
+
+import org.apache.log4j.Logger;
+
+/**
+ * CSExceptionErrorCode lists the CloudStack error codes that correspond
+ * to a each exception thrown by the CloudStack API.
+ */
+
+public class CSExceptionErrorCode {
+
+ public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName());
+
+ // Declare a hashmap of CloudStack Error Codes for Exceptions.
+ protected static final HashMap<String, Integer> ExceptionErrorCodeMap;
+
+ static {
+ try {
+ ExceptionErrorCodeMap = new HashMap<String, Integer>();
+ ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250);
+ ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260);
+ ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265);
+ ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275);
+ ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280);
+ ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285);
+ ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290);
+ ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300);
+ ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305);
+ ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310);
+ ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapacityException", 4331);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345);
+ ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350);
+ ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355);
+ ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360);
+ ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365);
+ ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370);
+ ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375);
+ ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380);
+ ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385);
+ ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390);
+ ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395);
+ ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540);
+ ExceptionErrorCodeMap.put("com.cloud.exception.RequestLimitException", 4545);
+ ExceptionErrorCodeMap.put("com.cloud.exception.StorageConflictException", 4550);
+
+ // Have a special error code for ServerApiException when it is
+ // thrown in a standalone manner when failing to detect any of the above
+ // standard exceptions.
+ ExceptionErrorCodeMap.put("org.apache.cloudstack.api.ServerApiException", 9999);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+ public static HashMap<String, Integer> getErrCodeList() {
+ return ExceptionErrorCodeMap;
+ }
+
+ public static int getCSErrCode(String exceptionName) {
+ if (ExceptionErrorCodeMap.containsKey(exceptionName)) {
+ return ExceptionErrorCodeMap.get(exceptionName);
+ } else {
+ s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions");
+ return -1;
+ }
+ }
+
+ public static String getCurMethodName() {
+ StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace();
+ return stackTraceCalls[1].toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/CloudRuntimeException.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/CloudRuntimeException.java b/utils/src/main/java/com/cloud/utils/exception/CloudRuntimeException.java
new file mode 100644
index 0000000..dd5abc8
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/CloudRuntimeException.java
@@ -0,0 +1,141 @@
+//
+// 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 com.cloud.utils.exception;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.utils.Pair;
+import com.cloud.utils.SerialVersionUID;
+
+/**
+ * wrap exceptions that you know there's no point in dealing with.
+ */
+public class CloudRuntimeException extends RuntimeException implements ErrorContext {
+
+ private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException;
+
+ // This holds a list of uuids and their descriptive names.
+ transient protected ArrayList<ExceptionProxyObject> idList = new ArrayList<ExceptionProxyObject>();
+
+ transient protected ArrayList<Pair<Class<?>, String>> uuidList = new ArrayList<Pair<Class<?>, String>>();
+
+ protected int csErrorCode;
+
+ public CloudRuntimeException(String message) {
+ super(message);
+ setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
+ }
+
+ public CloudRuntimeException(String message, Throwable th) {
+ super(message, th);
+ setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
+ }
+
+ protected CloudRuntimeException() {
+ super();
+
+ setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
+ }
+
+ public void addProxyObject(ExceptionProxyObject obj) {
+ idList.add(obj);
+ }
+
+ public void addProxyObject(String uuid) {
+ idList.add(new ExceptionProxyObject(uuid, null));
+ }
+
+ public void addProxyObject(String voObjUuid, String description) {
+ ExceptionProxyObject proxy = new ExceptionProxyObject(voObjUuid, description);
+ idList.add(proxy);
+ }
+
+ @Override
+ public CloudRuntimeException add(Class<?> entity, String uuid) {
+ uuidList.add(new Pair<Class<?>, String>(entity, uuid));
+ return this;
+ }
+
+ public ArrayList<ExceptionProxyObject> getIdProxyList() {
+ return idList;
+ }
+
+ public void setCSErrorCode(int cserrcode) {
+ csErrorCode = cserrcode;
+ }
+
+ public int getCSErrorCode() {
+ return csErrorCode;
+ }
+
+ public CloudRuntimeException(Throwable t) {
+ super(t.getMessage(), t);
+ }
+
+ @Override
+ public List<Pair<Class<?>, String>> getEntitiesInError() {
+ return uuidList;
+ }
+
+ private void writeObject(ObjectOutputStream out) throws IOException {
+ out.defaultWriteObject();
+
+ int idListSize = idList.size();
+ out.writeInt(idListSize);
+ for (ExceptionProxyObject proxy : idList) {
+ out.writeObject(proxy);
+ }
+
+ int uuidListSize = uuidList.size();
+ out.writeInt(uuidListSize);
+ for (Pair<Class<?>, String> entry : uuidList) {
+ out.writeObject(entry.first().getCanonicalName());
+ out.writeObject(entry.second());
+ }
+ }
+
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ in.defaultReadObject();
+
+ int idListSize = in.readInt();
+ if (idList == null)
+ idList = new ArrayList<ExceptionProxyObject>();
+ if (uuidList == null)
+ uuidList = new ArrayList<Pair<Class<?>, String>>();
+
+ for (int i = 0; i < idListSize; i++) {
+ ExceptionProxyObject proxy = (ExceptionProxyObject)in.readObject();
+
+ idList.add(proxy);
+ }
+
+ int uuidListSize = in.readInt();
+ for (int i = 0; i < uuidListSize; i++) {
+ String clzName = (String)in.readObject();
+ String val = (String)in.readObject();
+
+ uuidList.add(new Pair<Class<?>, String>(Class.forName(clzName), val));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/ErrorContext.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/ErrorContext.java b/utils/src/main/java/com/cloud/utils/exception/ErrorContext.java
new file mode 100644
index 0000000..5391373
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/ErrorContext.java
@@ -0,0 +1,31 @@
+//
+// 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 com.cloud.utils.exception;
+
+import java.util.List;
+
+import com.cloud.utils.Pair;
+
+public interface ErrorContext {
+
+ ErrorContext add(Class<?> entity, String uuid);
+
+ List<Pair<Class<?>, String>> getEntitiesInError();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/exception/ExceptionProxyObject.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/exception/ExceptionProxyObject.java b/utils/src/main/java/com/cloud/utils/exception/ExceptionProxyObject.java
new file mode 100644
index 0000000..5a689d4
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/exception/ExceptionProxyObject.java
@@ -0,0 +1,55 @@
+//
+// 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 com.cloud.utils.exception;
+
+import java.io.Serializable;
+
+
+public class ExceptionProxyObject implements Serializable {
+ private static final long serialVersionUID = -7514266713085362352L;
+
+ private String uuid;
+ private String description;
+
+ public ExceptionProxyObject(){
+
+ }
+
+ public ExceptionProxyObject(String uuid, String desc){
+ this.uuid = uuid;
+ description = desc;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+}
[02/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
fixed hardcoded merge message location
This would be empty if run from another directory, resulting
in a merge message with only a 'signed-off by' line.
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/1e6df1b7
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/1e6df1b7
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/1e6df1b7
Branch: refs/heads/deploy-from-snapshot
Commit: 1e6df1b77500dff40c24245227658f7c85c1835c
Parents: 9a24109
Author: Remi Bergsma <gi...@remi.nl>
Authored: Mon Aug 24 16:16:16 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Mon Aug 24 16:16:16 2015 +0200
----------------------------------------------------------------------
tools/git/git-pr | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/1e6df1b7/tools/git/git-pr
----------------------------------------------------------------------
diff --git a/tools/git/git-pr b/tools/git/git-pr
index 2e0b275..2bd58f6 100755
--- a/tools/git/git-pr
+++ b/tools/git/git-pr
@@ -217,7 +217,7 @@ echo "INFO: ********************************************************************
# Do the actual merge
git fetch ${github_remote} pull/${prId}/head:pr/${prId}
-git merge --no-ff --log -m "$(cat .git-tmp-message.txt)" pr/${prId}
+git merge --no-ff --log -m "$(cat ${tmpMessageFile})" pr/${prId}
if [ $? -eq 0 ]; then
git commit --amend -s --allow-empty-message -m ''
else
[43/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Code clean up in cloud-plugin-network-nvp project
- Code formatting
- Declare final where possible
- Remove unused methods
- Remove throws declarations where not needed
- Remove generated comments (e.g. "TODO Auto-generated method stub")
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6e74ef8e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6e74ef8e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6e74ef8e
Branch: refs/heads/deploy-from-snapshot
Commit: 6e74ef8e40c408511e4ec247a058c3d27fb3209d
Parents: 5fc953e
Author: Miguel Ferreira <mi...@me.com>
Authored: Sat Aug 22 20:53:28 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:12 2015 +0200
----------------------------------------------------------------------
plugins/network-elements/nicira-nvp/pom.xml | 3 +-
.../network/guru/NiciraNvpGuestNetworkGuru.java | 65 +++---
.../com/cloud/network/nicira/NiciraNvpApi.java | 71 ++----
.../network/resource/NiciraNvpResource.java | 36 +--
...figurePortForwardingRulesCommandWrapper.java | 5 +-
...ciraNvpConfigurePublicIpsCommandWrapper.java | 4 +-
...vpConfigureStaticNatRulesCommandWrapper.java | 2 +-
...aNvpFindLogicalSwitchPortCommandWrapper.java | 2 +-
.../resource/NiciraNvpRequestWrapperTest.java | 4 +-
.../network/resource/NiciraNvpResourceTest.java | 223 +++++++++----------
10 files changed, 190 insertions(+), 225 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml
index 8567482..2d20ae2 100644
--- a/plugins/network-elements/nicira-nvp/pom.xml
+++ b/plugins/network-elements/nicira-nvp/pom.xml
@@ -18,7 +18,8 @@
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/xsd/maven-4.0.0.xsd">
+<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-plugin-network-nvp</artifactId>
<name>Apache CloudStack Plugin - Network Nicira NVP</name>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
index 640d8a5..975ebd1 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
@@ -98,14 +98,14 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
public NiciraNvpGuestNetworkGuru() {
super();
- _isolationMethods = new IsolationMethod[] {IsolationMethod.STT, IsolationMethod.VXLAN};
+ _isolationMethods = new IsolationMethod[] { IsolationMethod.STT, IsolationMethod.VXLAN };
}
@Override
protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
// This guru handles only Guest Isolated network that supports Source nat service
- if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated &&
- isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) {
+ if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated
+ && isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) {
return true;
} else {
s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced);
@@ -116,14 +116,14 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
@Override
public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final Account owner) {
// Check of the isolation type of the related physical network is supported
- PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId());
- DataCenter dc = _dcDao.findById(plan.getDataCenterId());
+ final PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId());
+ final DataCenter dc = _dcDao.findById(plan.getDataCenterId());
if (!canHandle(offering, dc.getNetworkType(), physnet)) {
s_logger.debug("Refusing to design this network");
return null;
}
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId());
+ final List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId());
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + physnet.getName());
return null;
@@ -131,11 +131,10 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId());
s_logger.debug("Physical isolation type is supported, asking GuestNetworkGuru to design this network");
- NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner);
+ final NetworkVO networkObject = (NetworkVO) super.design(offering, plan, userSpecified, owner);
if (networkObject == null) {
return null;
}
- // Override the broadcast domain type
networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch);
return networkObject;
@@ -143,12 +142,11 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
@Override
public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context)
- throws InsufficientVirtualNetworkCapacityException {
- assert (network.getState() == State.Implementing) : "Why are we implementing " + network;
+ throws InsufficientVirtualNetworkCapacityException {
+ assert network.getState() == State.Implementing : "Why are we implementing " + network;
- long dcId = dest.getDataCenter().getId();
+ final long dcId = dest.getDataCenter().getId();
- //get physical network id
Long physicalNetworkId = network.getPhysicalNetworkId();
// physical network id can be null in Guest Network in Basic zone, so locate the physical network
@@ -156,9 +154,8 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
physicalNetworkId = networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType());
}
- NetworkVO implemented =
- new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated,
- network.getDataCenterId(), physicalNetworkId, offering.getRedundantRouter());
+ final NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(),
+ State.Allocated, network.getDataCenterId(), physicalNetworkId, offering.getRedundantRouter());
if (network.getGateway() != null) {
implemented.setGateway(network.getGateway());
@@ -171,26 +168,26 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
// Name is either the given name or the uuid
String name = network.getName();
if (name == null || name.isEmpty()) {
- name = ((NetworkVO)network).getUuid();
+ name = ((NetworkVO) network).getUuid();
}
if (name.length() > MAX_NAME_LENGTH) {
- name = name.substring(0, MAX_NAME_LENGTH - 1); // max length 40
+ name = name.substring(0, MAX_NAME_LENGTH - 1);
}
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
+ final List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + physicalNetworkId);
return null;
}
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+ final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
hostDao.loadDetails(niciraNvpHost);
- String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid");
- String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype");
+ final String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid");
+ final String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype");
- CreateLogicalSwitchCommand cmd =
- new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-" + context.getAccount().getAccountName());
- CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+ final CreateLogicalSwitchCommand cmd = new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-"
+ + context.getAccount().getAccountName());
+ final CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error("CreateLogicalSwitchCommand failed");
@@ -201,7 +198,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
implemented.setBroadcastUri(new URI("lswitch", answer.getLogicalSwitchUuid(), null));
implemented.setBroadcastDomainType(BroadcastDomainType.Lswitch);
s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString());
- } catch (URISyntaxException e) {
+ } catch (final URISyntaxException e) {
s_logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e);
return null;
}
@@ -211,35 +208,33 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
@Override
public void reserve(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context)
- throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
- // TODO Auto-generated method stub
+ throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
super.reserve(nic, network, vm, dest, context);
}
@Override
public boolean release(final NicProfile nic, final VirtualMachineProfile vm, final String reservationId) {
- // TODO Auto-generated method stub
return super.release(nic, vm, reservationId);
}
@Override
public void shutdown(final NetworkProfile profile, final NetworkOffering offering) {
- NetworkVO networkObject = networkDao.findById(profile.getId());
+ final NetworkVO networkObject = networkDao.findById(profile.getId());
if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch || networkObject.getBroadcastUri() == null) {
s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText());
return;
}
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
+ final List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId());
return;
}
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+ final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
- DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
- DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+ final DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
+ final DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error("DeleteLogicalSwitchCommand failed");
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
index 810453c..06446a7 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
@@ -18,6 +18,7 @@
//
package com.cloud.network.nicira;
+
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
@@ -26,6 +27,9 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
+import com.cloud.utils.rest.CloudstackRESTException;
+import com.cloud.utils.rest.RESTServiceConnector;
+import com.cloud.utils.rest.RESTValidationStrategy;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
@@ -33,10 +37,6 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
-import com.cloud.utils.rest.CloudstackRESTException;
-import com.cloud.utils.rest.RESTServiceConnector;
-import com.cloud.utils.rest.RESTValidationStrategy;
-
@SuppressWarnings("rawtypes")
public class NiciraNvpApi {
protected static final String GET_METHOD_TYPE = "get";
@@ -175,29 +175,25 @@ public class NiciraNvpApi {
}
/**
- * PUT item given a UUID as key and an item object
- * with the new data
+ * PUT item given a UUID as key and an item object with the new data
*
* @param item
* @param uuid
* @throws NiciraNvpApiException
*/
- public <T> void update(final T item, final String uuid)
- throws NiciraNvpApiException {
+ public <T> void update(final T item, final String uuid) throws NiciraNvpApiException {
final String uri = prefixMap.get(item.getClass()) + "/" + uuid;
updateWithUri(item, uri);
}
/**
- * PUT item given a UUID as key and an item object
- * with the new data
+ * PUT item given a UUID as key and an item object with the new data
*
* @param item
* @param uuid
* @throws NiciraNvpApiException
*/
- public <T> void updateWithUri(final T item, final String uri)
- throws NiciraNvpApiException {
+ public <T> void updateWithUri(final T item, final String uri) throws NiciraNvpApiException {
try {
restConnector.executeUpdateObject(item, uri, Collections.<String, String> emptyMap());
} catch (final CloudstackRESTException e) {
@@ -211,8 +207,7 @@ public class NiciraNvpApi {
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
- public <T> void delete(final String uuid, final Class<T> clazz)
- throws NiciraNvpApiException {
+ public <T> void delete(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz) + "/" + uuid;
deleteWithUri(uri);
}
@@ -223,8 +218,7 @@ public class NiciraNvpApi {
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
- public <T> void deleteWithUri(final String uri)
- throws NiciraNvpApiException {
+ public void deleteWithUri(final String uri) throws NiciraNvpApiException {
try {
restConnector.executeDeleteObject(uri);
} catch (final CloudstackRESTException e) {
@@ -256,9 +250,7 @@ public class NiciraNvpApi {
/**
* GET list of {@link SecurityProfile} filtered by UUID
*
- * We could have invoked the service:
- * SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid
- * but it is not working currently
+ * We could have invoked the service: SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid but it is not working currently
*
* @param uuid
* @return
@@ -269,16 +261,13 @@ public class NiciraNvpApi {
}
/**
- * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile}
- * with the new data
+ * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile} with the new data
*
* @param securityProfile
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
- public void updateSecurityProfile(final SecurityProfile securityProfile,
- final String securityProfileUuid)
- throws NiciraNvpApiException {
+ public void updateSecurityProfile(final SecurityProfile securityProfile, final String securityProfileUuid) throws NiciraNvpApiException {
update(securityProfile, securityProfileUuid);
}
@@ -288,12 +277,10 @@ public class NiciraNvpApi {
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
- public void deleteSecurityProfile(final String securityProfileUuid)
- throws NiciraNvpApiException {
+ public void deleteSecurityProfile(final String securityProfileUuid) throws NiciraNvpApiException {
delete(securityProfileUuid, SecurityProfile.class);
}
-
/**
* POST {@link Acl}
*
@@ -327,16 +314,13 @@ public class NiciraNvpApi {
}
/**
- * PUT {@link Acl} given a UUID as key and a {@link Acl}
- * with the new data
+ * PUT {@link Acl} given a UUID as key and a {@link Acl} with the new data
*
* @param acl
* @param aclUuid
* @throws NiciraNvpApiException
*/
- public void updateAcl(final Acl acl,
- final String aclUuid)
- throws NiciraNvpApiException {
+ public void updateAcl(final Acl acl, final String aclUuid) throws NiciraNvpApiException {
update(acl, aclUuid);
}
@@ -376,16 +360,13 @@ public class NiciraNvpApi {
}
/**
- * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch}
- * with the new data
+ * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch} with the new data
*
* @param logicalSwitch
* @param logicalSwitchUuid
* @throws NiciraNvpApiException
*/
- public void updateLogicalSwitch(final LogicalSwitch logicalSwitch,
- final String logicalSwitchUuid)
- throws NiciraNvpApiException {
+ public void updateLogicalSwitch(final LogicalSwitch logicalSwitch, final String logicalSwitchUuid) throws NiciraNvpApiException {
update(logicalSwitch, logicalSwitchUuid);
}
@@ -403,8 +384,7 @@ public class NiciraNvpApi {
updateWithUri(logicalSwitchPort, uri);
}
- public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid,
- final Attachment attachment) throws NiciraNvpApiException {
+ public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment";
updateWithUri(attachment, uri);
}
@@ -520,9 +500,7 @@ public class NiciraNvpApi {
return findLogicalRouter(logicalRouterUuid).getResults().get(0);
}
- public void updateLogicalRouter(final LogicalRouter logicalRouter,
- final String logicalRouterUuid)
- throws NiciraNvpApiException {
+ public void updateLogicalRouter(final LogicalRouter logicalRouter, final String logicalRouterUuid) throws NiciraNvpApiException {
update(logicalRouter, logicalRouterUuid);
}
@@ -546,8 +524,7 @@ public class NiciraNvpApi {
updateWithUri(logicalRouterPort, uri);
}
- public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment)
- throws NiciraNvpApiException {
+ public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment";
updateWithUri(attachment, uri);
}
@@ -567,12 +544,12 @@ public class NiciraNvpApi {
deleteWithUri(uri);
}
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid,
- final long vlanId) throws NiciraNvpApiException {
+ public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, final long vlanId)
+ throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
final Map<String, String> params = new HashMap<String, String>();
params.put("attachment_gwsvc_uuid", gatewayServiceUuid);
- params.put("attachment_vlan", "0");
+ params.put("attachment_vlan", Long.toString(vlanId));
params.put("fields", "*");
try {
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
index df40db4..af5812d 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
@@ -65,32 +65,32 @@ public class NiciraNvpResource implements ServerResource {
@Override
public boolean configure(final String ignoredName, final Map<String, Object> params) throws ConfigurationException {
- name = (String)params.get("name");
+ name = (String) params.get("name");
if (name == null) {
throw new ConfigurationException("Unable to find name");
}
- guid = (String)params.get("guid");
+ guid = (String) params.get("guid");
if (guid == null) {
throw new ConfigurationException("Unable to find the guid");
}
- zoneId = (String)params.get("zoneId");
+ zoneId = (String) params.get("zoneId");
if (zoneId == null) {
throw new ConfigurationException("Unable to find zone");
}
- final String ip = (String)params.get("ip");
+ final String ip = (String) params.get("ip");
if (ip == null) {
throw new ConfigurationException("Unable to find IP");
}
- final String adminuser = (String)params.get("adminuser");
+ final String adminuser = (String) params.get("adminuser");
if (adminuser == null) {
throw new ConfigurationException("Unable to find admin username");
}
- final String adminpass = (String)params.get("adminpass");
+ final String adminpass = (String) params.get("adminpass");
if (adminpass == null) {
throw new ConfigurationException("Unable to find admin password");
}
@@ -149,7 +149,7 @@ public class NiciraNvpResource implements ServerResource {
sc.setPrivateIpAddress("");
sc.setStorageIpAddress("");
sc.setVersion(NiciraNvpResource.class.getPackage().getImplementationVersion());
- return new StartupCommand[] {sc};
+ return new StartupCommand[] { sc };
}
@Override
@@ -212,16 +212,16 @@ public class NiciraNvpResource implements ServerResource {
natRuleStr.append(m.getDestinationPort());
natRuleStr.append(" ]) -->");
if ("SourceNatRule".equals(rule.getType())) {
- natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMin());
+ natRuleStr.append(((SourceNatRule) rule).getToSourceIpAddressMin());
natRuleStr.append("-");
- natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMax());
+ natRuleStr.append(((SourceNatRule) rule).getToSourceIpAddressMax());
natRuleStr.append(" [");
- natRuleStr.append(((SourceNatRule)rule).getToSourcePort());
+ natRuleStr.append(((SourceNatRule) rule).getToSourcePort());
natRuleStr.append(" ])");
} else {
- natRuleStr.append(((DestinationNatRule)rule).getToDestinationIpAddress());
+ natRuleStr.append(((DestinationNatRule) rule).getToDestinationIpAddress());
natRuleStr.append(" [");
- natRuleStr.append(((DestinationNatRule)rule).getToDestinationPort());
+ natRuleStr.append(((DestinationNatRule) rule).getToDestinationPort());
natRuleStr.append(" ])");
}
return natRuleStr.toString();
@@ -247,25 +247,25 @@ public class NiciraNvpResource implements ServerResource {
Match m = new Match();
m.setDestinationIpAddresses(outsideIp);
rulepair[0].setMatch(m);
- ((DestinationNatRule)rulepair[0]).setToDestinationIpAddress(insideIp);
+ ((DestinationNatRule) rulepair[0]).setToDestinationIpAddress(insideIp);
// create matching snat rule
m = new Match();
m.setSourceIpAddresses(insideIp);
rulepair[1].setMatch(m);
- ((SourceNatRule)rulepair[1]).setToSourceIpAddressMin(outsideIp);
- ((SourceNatRule)rulepair[1]).setToSourceIpAddressMax(outsideIp);
+ ((SourceNatRule) rulepair[1]).setToSourceIpAddressMin(outsideIp);
+ ((SourceNatRule) rulepair[1]).setToSourceIpAddressMax(outsideIp);
return rulepair;
}
public NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts,
- final String protocol) {
+ final String protocol) {
// Start with a basic static nat rule, then add port and protocol details
final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp);
- ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]);
+ ((DestinationNatRule) rulepair[0]).setToDestinationPort(insidePorts[0]);
rulepair[0].getMatch().setDestinationPort(outsidePorts[0]);
rulepair[0].setOrder(50);
rulepair[0].getMatch().setEthertype("IPv4");
@@ -275,7 +275,7 @@ public class NiciraNvpResource implements ServerResource {
rulepair[0].getMatch().setProtocol(17);
}
- ((SourceNatRule)rulepair[1]).setToSourcePort(outsidePorts[0]);
+ ((SourceNatRule) rulepair[1]).setToSourcePort(outsidePorts[0]);
rulepair[1].getMatch().setSourcePort(insidePorts[0]);
rulepair[1].setOrder(50);
rulepair[1].getMatch().setEthertype("IPv4");
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
index 89e7a6e..35ab04c 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
@@ -36,7 +36,7 @@ import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
-@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class)
+@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class)
public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends CommandWrapper<ConfigurePortForwardingRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigurePortForwardingRulesCommandWrapper.class);
@@ -60,7 +60,8 @@ public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends C
return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, false, "Nicira NVP doesn't support port ranges for port forwarding");
}
- final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
+ final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(),
+ rule.getProtocol());
NatRule incoming = null;
NatRule outgoing = null;
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
index e5d2dcd..9d4c711 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
@@ -33,7 +33,7 @@ import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
-@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class)
+@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class)
public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrapper<ConfigurePublicIpsOnLogicalRouterCommand, Answer, NiciraNvpResource> {
@Override
@@ -50,7 +50,7 @@ public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrap
niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp);
return new ConfigurePublicIpsOnLogicalRouterAnswer(command, true, "Configured " + command.getPublicCidrs().size() + " ip addresses on logical router uuid " +
- command.getLogicalRouterUuid());
+ command.getLogicalRouterUuid());
} catch (final NiciraNvpApiException e) {
final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
retryUtility.addRetry(command, NUM_RETRIES);
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
index 1ce3ceb..e576db9 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
@@ -36,7 +36,7 @@ import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
-@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class)
+@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class)
public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends CommandWrapper<ConfigureStaticNatRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigureStaticNatRulesCommandWrapper.class);
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
index 40d58fc..ea68538 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
@@ -33,7 +33,7 @@ import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
-@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class)
+@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class)
public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandWrapper<FindLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
@Override
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
index 7fe6287..25157a1 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -149,7 +149,7 @@ public class NiciraNvpRequestWrapperTest {
ports.setResultCount(1);
final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
final List<String> publicCidrs = new ArrayList<String>();
publicCidrs.add("10.1.1.0/24");
@@ -177,7 +177,7 @@ public class NiciraNvpRequestWrapperTest {
final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
final DeleteLogicalSwitchPortCommand command = new DeleteLogicalSwitchPortCommand(logicalSwitchUuid, logicalSwitchPortUuid);
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6e74ef8e/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
index ddf2993..67d1a96 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -189,10 +189,10 @@ public class NiciraNvpResourceTest {
final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
- when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls);
+ when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls);
- final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc);
assertTrue(clsa.getResult());
}
@@ -202,10 +202,10 @@ public class NiciraNvpResourceTest {
final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
- when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls);
+ when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenReturn(ls);
- final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc);
assertTrue(clsa.getResult());
assertTrue("cccc".equals(clsa.getLogicalSwitchUuid()));
}
@@ -216,19 +216,19 @@ public class NiciraNvpResourceTest {
final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
- when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException());
- final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc);
assertFalse(clsa.getResult());
}
@Test
- public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
+ public void testDeleteLogicalSwitch() throws ConfigurationException {
resource.configure("NiciraNvpResource", parameters);
final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
- final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
+ final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) resource.executeRequest(dlsc);
assertTrue(dlsa.getResult());
}
@@ -236,10 +236,10 @@ public class NiciraNvpResourceTest {
public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any());
+ doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String) any());
final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
- final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
+ final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) resource.executeRequest(dlsc);
assertFalse(dlsa.getResult());
}
@@ -249,10 +249,10 @@ public class NiciraNvpResourceTest {
final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee");
- when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
+ when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp);
final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc);
assertTrue(clspa.getResult());
assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid()));
@@ -264,10 +264,10 @@ public class NiciraNvpResourceTest {
final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee");
- when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenThrow(new NiciraNvpApiException());
final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc);
assertFalse(clspa.getResult());
}
@@ -277,21 +277,21 @@ public class NiciraNvpResourceTest {
final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee");
- when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
- doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
+ when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp);
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any());
final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc);
assertFalse(clspa.getResult());
- verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any());
+ verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String) any(), (String) any());
}
@Test
public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any());
- final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
+ doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String) any(), (String) any());
+ final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer) resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(dlspa.getResult());
}
@@ -299,9 +299,9 @@ public class NiciraNvpResourceTest {
public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any());
final UpdateLogicalSwitchPortAnswer dlspa =
- (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
+ (UpdateLogicalSwitchPortAnswer) resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
assertFalse(dlspa.getResult());
}
@@ -315,7 +315,7 @@ public class NiciraNvpResourceTest {
when(lspl.getResultCount()).thenReturn(1);
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
- final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertTrue(flspa.getResult());
}
@@ -329,7 +329,7 @@ public class NiciraNvpResourceTest {
when(lspl.getResultCount()).thenReturn(0);
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
- final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(flspa.getResult());
}
@@ -339,7 +339,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException());
- final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(flspa.getResult());
}
@@ -353,24 +353,24 @@ public class NiciraNvpResourceTest {
when(lrc.getUuid()).thenReturn("ccccc");
when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
when(lsp.getUuid()).thenReturn("fffff");
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
- when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
- when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
+ when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenReturn(lrp);
+ when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort) any())).thenReturn(lsp);
final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc);
assertTrue(clra.getResult());
assertTrue("ccccc".equals(clra.getLogicalRouterUuid()));
- verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String)any(), (NatRule)any());
+ verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String) any(), (NatRule) any());
}
@Test
public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenThrow(new NiciraNvpApiException());
final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc);
assertFalse(clra.getResult());
}
@@ -381,10 +381,10 @@ public class NiciraNvpResourceTest {
final LogicalRouter lrc = mock(LogicalRouter.class);
when(lrc.getUuid()).thenReturn("ccccc");
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
- when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenThrow(new NiciraNvpApiException());
final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc);
assertFalse(clra.getResult());
verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
@@ -400,12 +400,12 @@ public class NiciraNvpResourceTest {
when(lrc.getUuid()).thenReturn("ccccc");
when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
when(lsp.getUuid()).thenReturn("fffff");
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
- when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
- when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
- when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenReturn(lrp);
+ when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort) any())).thenReturn(lsp);
+ when(nvpApi.createLogicalRouterNatRule((String) any(), (NatRule) any())).thenThrow(new NiciraNvpApiException());
final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc);
assertFalse(clra.getResult());
verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
@@ -417,7 +417,7 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters);
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa"));
- final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
+ final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer) resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
assertFalse(dlspa.getResult());
}
@@ -433,9 +433,9 @@ public class NiciraNvpResourceTest {
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list);
- doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String) any(), (LogicalRouterPort) any());
- final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertFalse(answer.getResult());
}
@@ -450,7 +450,7 @@ public class NiciraNvpResourceTest {
when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenThrow(new NiciraNvpApiException("retry 1")).thenThrow(new NiciraNvpApiException("retry 2"));
- final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertFalse(answer.getResult());
}
@@ -458,9 +458,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -481,19 +480,19 @@ public class NiciraNvpResourceTest {
final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ final NatRule rule = (NatRule) argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
return true;
}
return false;
@@ -504,9 +503,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -521,7 +519,7 @@ public class NiciraNvpResourceTest {
final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
@SuppressWarnings("unchecked")
@@ -531,17 +529,17 @@ public class NiciraNvpResourceTest {
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ final NatRule rule = (NatRule) argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
return true;
}
return false;
@@ -552,9 +550,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -571,7 +568,7 @@ public class NiciraNvpResourceTest {
final UUID rule1Uuid = UUID.randomUUID();
rulepair[0].setUuid(rule0Uuid);
rulepair[1].setUuid(rule1Uuid);
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
@SuppressWarnings("unchecked")
@@ -581,13 +578,13 @@ public class NiciraNvpResourceTest {
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override
public boolean matches(final Object argument) {
- final UUID uuid = (UUID)argument;
+ final UUID uuid = (UUID) argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true;
}
@@ -599,9 +596,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -616,7 +612,7 @@ public class NiciraNvpResourceTest {
final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
// Mock the api find call
@SuppressWarnings("unchecked")
@@ -625,7 +621,7 @@ public class NiciraNvpResourceTest {
when(storedRules.getResultCount()).thenReturn(0);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertFalse(a.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
@@ -634,9 +630,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -654,22 +649,22 @@ public class NiciraNvpResourceTest {
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ final NatRule rule = (NatRule) argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
return true;
}
return false;
@@ -680,9 +675,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -694,10 +688,10 @@ public class NiciraNvpResourceTest {
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
@SuppressWarnings("unchecked")
@@ -707,17 +701,17 @@ public class NiciraNvpResourceTest {
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ final NatRule rule = (NatRule) argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
return true;
}
return false;
@@ -728,9 +722,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -742,12 +735,12 @@ public class NiciraNvpResourceTest {
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp");
final UUID rule0Uuid = UUID.randomUUID();
final UUID rule1Uuid = UUID.randomUUID();
rulepair[0].setUuid(rule0Uuid);
rulepair[1].setUuid(rule1Uuid);
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
@SuppressWarnings("unchecked")
@@ -757,13 +750,13 @@ public class NiciraNvpResourceTest {
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override
public boolean matches(final Object argument) {
- final UUID uuid = (UUID)argument;
+ final UUID uuid = (UUID) argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true;
}
@@ -775,9 +768,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -789,10 +781,10 @@ public class NiciraNvpResourceTest {
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
// Mock the api find call
@SuppressWarnings("unchecked")
@@ -801,7 +793,7 @@ public class NiciraNvpResourceTest {
when(storedRules.getResultCount()).thenReturn(0);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
assertFalse(a.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
@@ -810,9 +802,8 @@ public class NiciraNvpResourceTest {
@Test
public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
+ /*
+ * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10
*/
// Mock the command
@@ -830,12 +821,12 @@ public class NiciraNvpResourceTest {
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 80, 85 }, "11.11.11.11", new int[] { 80, 85 }, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd);
// The expected result is false, Nicira does not support port ranges in DNAT
assertFalse(a.getResult());
@@ -848,12 +839,12 @@ public class NiciraNvpResourceTest {
assertTrue("DestinationNatRule".equals(rules[0].getType()));
assertTrue("SourceNatRule".equals(rules[1].getType()));
- final DestinationNatRule dnr = (DestinationNatRule)rules[0];
+ final DestinationNatRule dnr = (DestinationNatRule) rules[0];
assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
assertTrue(dnr.getToDestinationPort() == null);
assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
- final SourceNatRule snr = (SourceNatRule)rules[1];
+ final SourceNatRule snr = (SourceNatRule) rules[1];
assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
assertTrue(snr.getToSourcePort() == null);
assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
@@ -861,18 +852,18 @@ public class NiciraNvpResourceTest {
@Test
public void testGeneratePortForwardingRulePair() {
- final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp");
assertTrue("DestinationNatRule".equals(rules[0].getType()));
assertTrue("SourceNatRule".equals(rules[1].getType()));
- final DestinationNatRule dnr = (DestinationNatRule)rules[0];
+ final DestinationNatRule dnr = (DestinationNatRule) rules[0];
assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
assertTrue(dnr.getToDestinationPort() == 8080);
assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
assertTrue(dnr.getMatch().getDestinationPort() == 80);
assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6);
- final SourceNatRule snr = (SourceNatRule)rules[1];
+ final SourceNatRule snr = (SourceNatRule) rules[1];
assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
assertTrue(snr.getToSourcePort() == 80);
assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
[30/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
deleted file mode 100644
index ddf2993..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ /dev/null
@@ -1,882 +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 com.cloud.network.resource;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.atLeast;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.naming.ConfigurationException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentMatcher;
-
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalRouterAnswer;
-import com.cloud.agent.api.CreateLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalSwitchAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchCommand;
-import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
-import com.cloud.agent.api.DeleteLogicalRouterAnswer;
-import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
-import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
-import com.cloud.agent.api.FindLogicalSwitchPortCommand;
-import com.cloud.agent.api.PingCommand;
-import com.cloud.agent.api.StartupCommand;
-import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
-import com.cloud.agent.api.to.PortForwardingRuleTO;
-import com.cloud.agent.api.to.StaticNatRuleTO;
-import com.cloud.host.Host;
-import com.cloud.network.nicira.Attachment;
-import com.cloud.network.nicira.ControlClusterStatus;
-import com.cloud.network.nicira.DestinationNatRule;
-import com.cloud.network.nicira.LogicalRouter;
-import com.cloud.network.nicira.LogicalRouterPort;
-import com.cloud.network.nicira.LogicalSwitch;
-import com.cloud.network.nicira.LogicalSwitchPort;
-import com.cloud.network.nicira.NatRule;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.nicira.SourceNatRule;
-import com.cloud.network.utils.CommandRetryUtility;
-
-public class NiciraNvpResourceTest {
- NiciraNvpApi nvpApi = mock(NiciraNvpApi.class);
- NiciraNvpResource resource;
- Map<String, Object> parameters;
-
- private CommandRetryUtility retryUtility;
-
- @Before
- public void setUp() throws ConfigurationException {
- resource = new NiciraNvpResource() {
- @Override
- protected NiciraNvpApi createNiciraNvpApi() {
- return nvpApi;
- }
- };
-
- parameters = new HashMap<String, Object>();
- parameters.put("name", "nvptestdevice");
- parameters.put("ip", "127.0.0.1");
- parameters.put("adminuser", "adminuser");
- parameters.put("guid", "aaaaa-bbbbb-ccccc");
- parameters.put("zoneId", "blublub");
- parameters.put("adminpass", "adminpass");
-
- retryUtility = CommandRetryUtility.getInstance();
- retryUtility.setServerResource(resource);
- }
-
- @Test(expected = ConfigurationException.class)
- public void resourceConfigureFailure() throws ConfigurationException {
- resource.configure("NiciraNvpResource", Collections.<String, Object> emptyMap());
- }
-
- @Test
- public void resourceConfigure() throws ConfigurationException {
- resource.configure("NiciraNvpResource", parameters);
-
- verify(nvpApi).setAdminCredentials("adminuser", "adminpass");
- verify(nvpApi).setControllerAddress("127.0.0.1");
- assertTrue("Incorrect resource name", "nvptestdevice".equals(resource.getName()));
-
- /* Pretty lame test, but here to assure this plugin fails
- * if the type name ever changes from L2Networking
- */
- assertTrue("Incorrect resource type", resource.getType() == Host.Type.L2Networking);
- }
-
- @Test
- public void testInitialization() throws ConfigurationException {
- resource.configure("NiciraNvpResource", parameters);
-
- final StartupCommand[] sc = resource.initialize();
- assertTrue(sc.length == 1);
- assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid()));
- assertTrue("Incorrect NVP device name", "nvptestdevice".equals(sc[0].getName()));
- assertTrue("Incorrect Data Center", "blublub".equals(sc[0].getDataCenter()));
- }
-
- @Test
- public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
- when(ccs.getClusterStatus()).thenReturn("stable");
- when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
-
- final PingCommand ping = resource.getCurrentStatus(42);
- assertTrue(ping != null);
- assertTrue(ping.getHostId() == 42);
- assertTrue(ping.getHostType() == Host.Type.L2Networking);
- }
-
- @Test
- public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
- when(ccs.getClusterStatus()).thenReturn("unstable");
- when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
-
- final PingCommand ping = resource.getCurrentStatus(42);
- assertTrue(ping == null);
- }
-
- @Test
- public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
- when(ccs.getClusterStatus()).thenReturn("unstable");
- when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException());
-
- final PingCommand ping = resource.getCurrentStatus(42);
- assertTrue(ping == null);
- }
-
- @Test
- public void testRetries() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalSwitch ls = mock(LogicalSwitch.class);
- when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
- when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls);
-
- final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
- assertTrue(clsa.getResult());
- }
-
- @Test
- public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalSwitch ls = mock(LogicalSwitch.class);
- when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
- when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls);
-
- final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
- assertTrue(clsa.getResult());
- assertTrue("cccc".equals(clsa.getLogicalSwitchUuid()));
- }
-
- @Test
- public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalSwitch ls = mock(LogicalSwitch.class);
- when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
- when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException());
-
- final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
- assertFalse(clsa.getResult());
- }
-
- @Test
- public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
- final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
- assertTrue(dlsa.getResult());
- }
-
- @Test
- public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any());
-
- final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
- final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
- assertFalse(dlsa.getResult());
- }
-
- @Test
- public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
- when(lsp.getUuid()).thenReturn("eeee");
- when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
-
- final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
- assertTrue(clspa.getResult());
- assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid()));
-
- }
-
- @Test
- public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
- when(lsp.getUuid()).thenReturn("eeee");
- when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException());
-
- final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
- assertFalse(clspa.getResult());
- }
-
- @Test
- public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
- when(lsp.getUuid()).thenReturn("eeee");
- when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
- doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
-
- final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
- assertFalse(clspa.getResult());
- verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any());
- }
-
- @Test
- public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any());
- final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
- assertFalse(dlspa.getResult());
- }
-
- @Test
- public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
- final UpdateLogicalSwitchPortAnswer dlspa =
- (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
- assertFalse(dlspa.getResult());
- }
-
- @Test
- public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
- when(lspl.getResultCount()).thenReturn(1);
- when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
-
- final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
- assertTrue(flspa.getResult());
- }
-
- @Test
- public void testFindLogicalSwitchPortNotFound() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
- when(lspl.getResultCount()).thenReturn(0);
- when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
-
- final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
- assertFalse(flspa.getResult());
- }
-
- @Test
- public void testFindLogicalSwitchPortApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException());
-
- final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
- assertFalse(flspa.getResult());
- }
-
- @Test
- public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalRouter lrc = mock(LogicalRouter.class);
- final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
- final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
- when(lrc.getUuid()).thenReturn("ccccc");
- when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
- when(lsp.getUuid()).thenReturn("fffff");
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
- when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
- when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
- final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
-
- assertTrue(clra.getResult());
- assertTrue("ccccc".equals(clra.getLogicalRouterUuid()));
- verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String)any(), (NatRule)any());
- }
-
- @Test
- public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenThrow(new NiciraNvpApiException());
- final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
-
- assertFalse(clra.getResult());
- }
-
- @Test
- public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalRouter lrc = mock(LogicalRouter.class);
- when(lrc.getUuid()).thenReturn("ccccc");
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
- when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException());
- final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
-
- assertFalse(clra.getResult());
- verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
- }
-
- @Test
- public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final LogicalRouter lrc = mock(LogicalRouter.class);
- final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
- final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
- when(lrc.getUuid()).thenReturn("ccccc");
- when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
- when(lsp.getUuid()).thenReturn("fffff");
- when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
- when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
- when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
- when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException());
- final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
-
- assertFalse(clra.getResult());
- verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
- verify(nvpApi, atLeast(1)).deleteLogicalSwitchPort(eq("bbbbb"), eq("fffff"));
- }
-
- @Test
- public void testDeleteLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa"));
- final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
- assertFalse(dlspa.getResult());
- }
-
- @Test
- public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<LogicalRouterPort> list = mock(NiciraNvpList.class);
-
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
- when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
- when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list);
- doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
-
- final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
- assertFalse(answer.getResult());
-
- }
-
- @Test
- public void testConfigurePublicIpsOnLogicalRouterRetry() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
-
- final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
-
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
- when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
- when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenThrow(new NiciraNvpApiException("retry 1")).thenThrow(new NiciraNvpApiException("retry 2"));
-
- final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
- assertFalse(answer.getResult());
-
- }
-
- @Test
- public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
- final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertTrue(a.getResult());
- verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
- @Override
- public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
- return true;
- }
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
- return true;
- }
- return false;
- }
- }));
- }
-
- @Test
- public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
- final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertTrue(a.getResult());
- verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
- @Override
- public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
- return true;
- }
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
- return true;
- }
- return false;
- }
- }));
- }
-
- @Test
- public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false);
- final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
- final UUID rule0Uuid = UUID.randomUUID();
- final UUID rule1Uuid = UUID.randomUUID();
- rulepair[0].setUuid(rule0Uuid);
- rulepair[1].setUuid(rule1Uuid);
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertTrue(a.getResult());
- verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
- @Override
- public boolean matches(final Object argument) {
- final UUID uuid = (UUID)argument;
- if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
- return true;
- }
- return false;
- }
- }));
- }
-
- @Test
- public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
- final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(0);
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertFalse(a.getResult());
- verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
- }
-
- @Test
- public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
- final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertTrue(a.getResult());
- verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
- @Override
- public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
- return true;
- }
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
- return true;
- }
- return false;
- }
- }));
- }
-
- @Test
- public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true);
- final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertTrue(a.getResult());
- verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
- @Override
- public boolean matches(final Object argument) {
- final NatRule rule = (NatRule)argument;
- if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
- return true;
- }
- if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
- return true;
- }
- return false;
- }
- }));
- }
-
- @Test
- public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true);
- final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
- final UUID rule0Uuid = UUID.randomUUID();
- final UUID rule1Uuid = UUID.randomUUID();
- rulepair[0].setUuid(rule0Uuid);
- rulepair[1].setUuid(rule1Uuid);
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(2);
- when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertTrue(a.getResult());
- verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
- @Override
- public boolean matches(final Object argument) {
- final UUID uuid = (UUID)argument;
- if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
- return true;
- }
- return false;
- }
- }));
- }
-
- @Test
- public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
- final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(storedRules.getResultCount()).thenReturn(0);
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- assertFalse(a.getResult());
- verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
- }
-
- @Test
- public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException {
- resource.configure("NiciraNvpResource", parameters);
- /* StaticNat
- * Outside IP: 11.11.11.11
- * Inside IP: 10.10.10.10
- */
-
- // Mock the command
- final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false);
- final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
- rules.add(rule);
- when(cmd.getRules()).thenReturn(rules);
- when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
-
- // Mock the api find call
- @SuppressWarnings("unchecked")
- final
- NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
- when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
-
- // Mock the api create calls
- final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp");
- rulepair[0].setUuid(UUID.randomUUID());
- rulepair[1].setUuid(UUID.randomUUID());
- when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
-
- final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
-
- // The expected result is false, Nicira does not support port ranges in DNAT
- assertFalse(a.getResult());
-
- }
-
- @Test
- public void testGenerateStaticNatRulePair() {
- final NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
- assertTrue("DestinationNatRule".equals(rules[0].getType()));
- assertTrue("SourceNatRule".equals(rules[1].getType()));
-
- final DestinationNatRule dnr = (DestinationNatRule)rules[0];
- assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
- assertTrue(dnr.getToDestinationPort() == null);
- assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
-
- final SourceNatRule snr = (SourceNatRule)rules[1];
- assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
- assertTrue(snr.getToSourcePort() == null);
- assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
- }
-
- @Test
- public void testGeneratePortForwardingRulePair() {
- final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
- assertTrue("DestinationNatRule".equals(rules[0].getType()));
- assertTrue("SourceNatRule".equals(rules[1].getType()));
-
- final DestinationNatRule dnr = (DestinationNatRule)rules[0];
- assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
- assertTrue(dnr.getToDestinationPort() == 8080);
- assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
- assertTrue(dnr.getMatch().getDestinationPort() == 80);
- assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6);
-
- final SourceNatRule snr = (SourceNatRule)rules[1];
- assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
- assertTrue(snr.getToSourcePort() == 80);
- assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
- assertTrue(snr.getMatch().getSourcePort() == 8080);
- assertTrue(snr.getMatch().getEthertype().equals("IPv4") && rules[1].getMatch().getProtocol() == 6);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/resources/config.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/resources/config.properties b/plugins/network-elements/nicira-nvp/test/resources/config.properties
deleted file mode 100644
index 4006e38d..0000000
--- a/plugins/network-elements/nicira-nvp/test/resources/config.properties
+++ /dev/null
@@ -1,23 +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.
-#
-
-
-nvp.host=${nvp-host}
-nvp.admin.user=${nvp-admin-user}
-nvp.admin.pwd=${nvp-admin-pwd}
[33/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java
new file mode 100644
index 0000000..92c198a
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java
@@ -0,0 +1,89 @@
+//
+// 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 com.cloud.network.utils;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.resource.ServerResource;
+
+public class CommandRetryUtility {
+
+ private static final Logger s_logger = Logger.getLogger(CommandRetryUtility.class);
+
+ private static final int ZERO = 0;
+ private static CommandRetryUtility instance;
+
+ static {
+ instance = new CommandRetryUtility();
+ }
+
+ private final ConcurrentHashMap<Command, Integer> commandsToRetry;
+ private ServerResource serverResource;
+
+ private CommandRetryUtility() {
+ commandsToRetry = new ConcurrentHashMap<Command, Integer>();
+ }
+
+ public static CommandRetryUtility getInstance() {
+ return instance;
+ }
+
+ public void setServerResource(final ServerResource serverResource) {
+ this.serverResource = serverResource;
+ }
+
+ public boolean addRetry(final Command command, final int retries) {
+ if (commandsToRetry.containsKey(command)) {
+ // A retry already exists for this command, do not add it again.
+ // Once all retries are executed, the command will be removed from the map.
+ return false;
+ }
+ commandsToRetry.put(command, retries);
+ return true;
+ }
+
+ public Answer retry(final Command command, final Class<? extends Answer> answerClass, final Exception error) {
+ if (commandsToRetry.containsKey(command)) {
+ Integer numRetries = commandsToRetry.get(command);
+
+ if (numRetries > ZERO) {
+ commandsToRetry.put(command, --numRetries);
+
+ s_logger.warn("Retrying " + command.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
+
+ return serverResource.executeRequest(command);
+ } else {
+ commandsToRetry.remove(command);
+ }
+ }
+ try {
+ final Constructor<? extends Answer> answerConstructor = answerClass.getConstructor(Command.class, Exception.class);
+ return answerConstructor.newInstance(command, error);
+ } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ return Answer.createUnsupportedCommandAnswer(command);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties
new file mode 100644
index 0000000..5085fce
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties
@@ -0,0 +1,21 @@
+#
+# 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.
+#
+
+name=nvp
+parent=network
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml
new file mode 100644
index 0000000..cd8a2c9
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml
@@ -0,0 +1,42 @@
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd"
+ >
+
+ <bean id="niciraNvpDaoImpl" class="com.cloud.network.dao.NiciraNvpDaoImpl" />
+ <bean id="niciraNvpNicMappingDaoImpl" class="com.cloud.network.dao.NiciraNvpNicMappingDaoImpl" />
+ <bean id="niciraNvpRouterMappingDaoImpl" class="com.cloud.network.dao.NiciraNvpRouterMappingDaoImpl" />
+ <bean id="NiciraNvpGuestNetworkGuru" class="com.cloud.network.guru.NiciraNvpGuestNetworkGuru">
+ <property name="name" value="NiciraNvpGuestNetworkGuru" />
+ </bean>
+ <bean id="NiciraNvp" class="com.cloud.network.element.NiciraNvpElement">
+ <property name="name" value="NiciraNvp" />
+ </bean>
+
+</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java
new file mode 100644
index 0000000..bf8ce18
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java
@@ -0,0 +1,217 @@
+//
+// 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 com.cloud.network.element;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.naming.ConfigurationException;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+
+import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.domain.Domain;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.network.IpAddress;
+import com.cloud.network.Network;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.network.NiciraNvpRouterMappingVO;
+import com.cloud.network.PublicIpAddress;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.dao.NiciraNvpDao;
+import com.cloud.network.dao.NiciraNvpRouterMappingDao;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.resource.ResourceManager;
+import com.cloud.user.Account;
+import com.cloud.utils.net.Ip;
+import com.cloud.vm.ReservationContext;
+
+public class NiciraNvpElementTest {
+
+ private static final long NETWORK_ID = 42L;
+ NiciraNvpElement element = new NiciraNvpElement();
+ NetworkOrchestrationService networkManager = mock(NetworkOrchestrationService.class);
+ NetworkModel networkModel = mock(NetworkModel.class);
+ NetworkServiceMapDao ntwkSrvcDao = mock(NetworkServiceMapDao.class);
+ AgentManager agentManager = mock(AgentManager.class);
+ HostDao hostDao = mock(HostDao.class);
+ NiciraNvpDao niciraNvpDao = mock(NiciraNvpDao.class);
+ NiciraNvpRouterMappingDao niciraNvpRouterMappingDao = mock(NiciraNvpRouterMappingDao.class);
+
+ @Before
+ public void setUp() throws ConfigurationException {
+ element.resourceMgr = mock(ResourceManager.class);
+ element.networkManager = networkManager;
+ element.ntwkSrvcDao = ntwkSrvcDao;
+ element.networkModel = networkModel;
+ element.agentMgr = agentManager;
+ element.hostDao = hostDao;
+ element.niciraNvpDao = niciraNvpDao;
+ element.niciraNvpRouterMappingDao = niciraNvpRouterMappingDao;
+
+ // Standard responses
+ when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true);
+
+ element.configure("NiciraNvpTestElement", Collections.<String, Object> emptyMap());
+ }
+
+ @Test
+ public void canHandleTest() {
+ final Network net = mock(Network.class);
+ when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
+ when(net.getId()).thenReturn(NETWORK_ID);
+
+ when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true);
+ // Golden path
+ assertTrue(element.canHandle(net, Service.Connectivity));
+
+ when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+ // Only broadcastdomaintype lswitch is supported
+ assertFalse(element.canHandle(net, Service.Connectivity));
+
+ when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
+ when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(false);
+ // No nvp provider in the network
+ assertFalse(element.canHandle(net, Service.Connectivity));
+
+ when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(false);
+ when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true);
+ // NVP provider does not provide Connectivity for this network
+ assertFalse(element.canHandle(net, Service.Connectivity));
+
+ when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true);
+ // Only service Connectivity is supported
+ assertFalse(element.canHandle(net, Service.Dhcp));
+
+ }
+
+ @Test
+ public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+ final Network network = mock(Network.class);
+ when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
+ when(network.getId()).thenReturn(NETWORK_ID);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ mock(DeployDestination.class);
+
+ final Domain dom = mock(Domain.class);
+ when(dom.getName()).thenReturn("domain");
+ final Account acc = mock(Account.class);
+ when(acc.getAccountName()).thenReturn("accountname");
+ final ReservationContext context = mock(ReservationContext.class);
+ when(context.getDomain()).thenReturn(dom);
+ when(context.getAccount()).thenReturn(acc);
+ }
+
+ @Test
+ public void applyIpTest() throws ResourceUnavailableException {
+ final Network network = mock(Network.class);
+ when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
+ when(network.getId()).thenReturn(NETWORK_ID);
+ when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ final List<PublicIpAddress> ipAddresses = new ArrayList<PublicIpAddress>();
+ final PublicIpAddress pipReleased = mock(PublicIpAddress.class);
+ final PublicIpAddress pipAllocated = mock(PublicIpAddress.class);
+ final Ip ipReleased = new Ip("42.10.10.10");
+ final Ip ipAllocated = new Ip("10.10.10.10");
+ when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated);
+ when(pipAllocated.getAddress()).thenReturn(ipAllocated);
+ when(pipAllocated.getNetmask()).thenReturn("255.255.255.0");
+ when(pipReleased.getState()).thenReturn(IpAddress.State.Releasing);
+ when(pipReleased.getAddress()).thenReturn(ipReleased);
+ when(pipReleased.getNetmask()).thenReturn("255.255.255.0");
+ ipAddresses.add(pipAllocated);
+ ipAddresses.add(pipReleased);
+
+ final Set<Service> services = new HashSet<Service>();
+ services.add(Service.SourceNat);
+ services.add(Service.StaticNat);
+ services.add(Service.PortForwarding);
+
+ final List<NiciraNvpDeviceVO> deviceList = new ArrayList<NiciraNvpDeviceVO>();
+ final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class);
+ final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class);
+ when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO);
+ when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde");
+ when(nndVO.getHostId()).thenReturn(NETWORK_ID);
+ final HostVO hvo = mock(HostVO.class);
+ when(hvo.getId()).thenReturn(NETWORK_ID);
+ when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde");
+ when(hostDao.findById(NETWORK_ID)).thenReturn(hvo);
+ deviceList.add(nndVO);
+ when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList);
+
+ final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class);
+ when(answer.getResult()).thenReturn(true);
+ when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer);
+
+ assertTrue(element.applyIps(network, ipAddresses, services));
+
+ verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument;
+ if (command.getPublicCidrs().size() == 1)
+ return true;
+ return false;
+ }
+ }));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java
new file mode 100644
index 0000000..36e4643
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java
@@ -0,0 +1,476 @@
+//
+// 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 com.cloud.network.guru;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collections;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.CreateLogicalSwitchAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.domain.Domain;
+import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.network.Network;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network.Service;
+import com.cloud.network.Network.State;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.NetworkProfile;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.NiciraNvpDao;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
+import com.cloud.user.Account;
+import com.cloud.vm.ReservationContext;
+
+public class NiciraNvpGuestNetworkGuruTest {
+ private static final long NETWORK_ID = 42L;
+ PhysicalNetworkDao physnetdao = mock(PhysicalNetworkDao.class);
+ NiciraNvpDao nvpdao = mock(NiciraNvpDao.class);
+ DataCenterDao dcdao = mock(DataCenterDao.class);
+ NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class);
+ AgentManager agentmgr = mock(AgentManager.class);
+ NetworkOrchestrationService netmgr = mock(NetworkOrchestrationService.class);
+ NetworkModel netmodel = mock(NetworkModel.class);
+
+ HostDao hostdao = mock(HostDao.class);
+ NetworkDao netdao = mock(NetworkDao.class);
+ NiciraNvpGuestNetworkGuru guru;
+
+ @Before
+ public void setUp() {
+ guru = new NiciraNvpGuestNetworkGuru();
+ ((GuestNetworkGuru)guru)._physicalNetworkDao = physnetdao;
+ guru.physicalNetworkDao = physnetdao;
+ guru.niciraNvpDao = nvpdao;
+ guru._dcDao = dcdao;
+ guru.ntwkOfferingSrvcDao = nosd;
+ guru.networkModel = netmodel;
+ guru.hostDao = hostdao;
+ guru.agentMgr = agentmgr;
+ guru.networkDao = netdao;
+
+ final DataCenterVO dc = mock(DataCenterVO.class);
+ when(dc.getNetworkType()).thenReturn(NetworkType.Advanced);
+ when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24");
+
+ when(dcdao.findById((Long)any())).thenReturn(dc);
+ }
+
+ @Test
+ public void testCanHandle() {
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true);
+
+ assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
+
+ // Supported: IsolationMethod == VXLAN
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VXLAN"}));
+ assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
+
+ // Not supported TrafficType != Guest
+ when(offering.getTrafficType()).thenReturn(TrafficType.Management);
+ assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
+
+ // Not supported: GuestType Shared
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Shared);
+ assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
+
+ // Not supported: Basic networking
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+ assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true);
+
+ // Not supported: IsolationMethod != STT, VXLAN
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"}));
+ assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
+
+ }
+
+ @Test
+ public void testDesign() {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
+ when(device.getId()).thenReturn(1L);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true);
+
+ final DeploymentPlan plan = mock(DeploymentPlan.class);
+ final Network network = mock(Network.class);
+ final Account account = mock(Account.class);
+
+ final Network designednetwork = guru.design(offering, plan, network, account);
+ assertTrue(designednetwork != null);
+ assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch);
+ }
+
+ @Test
+ public void testDesignNoElementOnPhysicalNetwork() {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList());
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ final DeploymentPlan plan = mock(DeploymentPlan.class);
+ final Network network = mock(Network.class);
+ final Account account = mock(Account.class);
+
+ final Network designednetwork = guru.design(offering, plan, network, account);
+ assertTrue(designednetwork == null);
+ }
+
+ @Test
+ public void testDesignNoIsolationMethodSTT() {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList());
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ final DeploymentPlan plan = mock(DeploymentPlan.class);
+ final Network network = mock(Network.class);
+ final Account account = mock(Account.class);
+
+ final Network designednetwork = guru.design(offering, plan, network, account);
+ assertTrue(designednetwork == null);
+ }
+
+ @Test
+ public void testDesignNoConnectivityInOffering() {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
+ when(device.getId()).thenReturn(1L);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
+
+ final DeploymentPlan plan = mock(DeploymentPlan.class);
+ final Network network = mock(Network.class);
+ final Account account = mock(Account.class);
+
+ final Network designednetwork = guru.design(offering, plan, network, account);
+ assertTrue(designednetwork == null);
+ }
+
+ @Test
+ public void testImplement() throws InsufficientVirtualNetworkCapacityException {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
+ when(device.getId()).thenReturn(1L);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
+
+ mock(DeploymentPlan.class);
+
+ final NetworkVO network = mock(NetworkVO.class);
+ when(network.getName()).thenReturn("testnetwork");
+ when(network.getState()).thenReturn(State.Implementing);
+ when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
+
+ final DeployDestination dest = mock(DeployDestination.class);
+
+ final DataCenter dc = mock(DataCenter.class);
+ when(dest.getDataCenter()).thenReturn(dc);
+
+ final HostVO niciraHost = mock(HostVO.class);
+ when(hostdao.findById(anyLong())).thenReturn(niciraHost);
+ when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
+ when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
+ when(niciraHost.getId()).thenReturn(NETWORK_ID);
+
+ when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
+ final Domain dom = mock(Domain.class);
+ when(dom.getName()).thenReturn("domain");
+ final Account acc = mock(Account.class);
+ when(acc.getAccountName()).thenReturn("accountname");
+ final ReservationContext res = mock(ReservationContext.class);
+ when(res.getDomain()).thenReturn(dom);
+ when(res.getAccount()).thenReturn(acc);
+
+ final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
+ when(answer.getResult()).thenReturn(true);
+ when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
+ when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
+
+ final Network implementednetwork = guru.implement(network, offering, dest, res);
+ assertTrue(implementednetwork != null);
+ verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
+ }
+
+ @Test
+ public void testImplementWithCidr() throws InsufficientVirtualNetworkCapacityException {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
+ when(device.getId()).thenReturn(1L);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
+
+ mock(DeploymentPlan.class);
+
+ final NetworkVO network = mock(NetworkVO.class);
+ when(network.getName()).thenReturn("testnetwork");
+ when(network.getState()).thenReturn(State.Implementing);
+ when(network.getGateway()).thenReturn("10.1.1.1");
+ when(network.getCidr()).thenReturn("10.1.1.0/24");
+ when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
+
+ final DeployDestination dest = mock(DeployDestination.class);
+
+ final DataCenter dc = mock(DataCenter.class);
+ when(dest.getDataCenter()).thenReturn(dc);
+
+ final HostVO niciraHost = mock(HostVO.class);
+ when(hostdao.findById(anyLong())).thenReturn(niciraHost);
+ when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
+ when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
+ when(niciraHost.getId()).thenReturn(NETWORK_ID);
+
+ when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
+ final Domain dom = mock(Domain.class);
+ when(dom.getName()).thenReturn("domain");
+ final Account acc = mock(Account.class);
+ when(acc.getAccountName()).thenReturn("accountname");
+ final ReservationContext res = mock(ReservationContext.class);
+ when(res.getDomain()).thenReturn(dom);
+ when(res.getAccount()).thenReturn(acc);
+
+ final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
+ when(answer.getResult()).thenReturn(true);
+ when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
+ when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
+
+ final Network implementednetwork = guru.implement(network, offering, dest, res);
+ assertTrue(implementednetwork != null);
+ assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24"));
+ assertTrue(implementednetwork.getGateway().equals("10.1.1.1"));
+ verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
+ }
+
+ @Test
+ public void testImplementURIException() throws InsufficientVirtualNetworkCapacityException {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
+ when(device.getId()).thenReturn(1L);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
+
+ mock(DeploymentPlan.class);
+
+ final NetworkVO network = mock(NetworkVO.class);
+ when(network.getName()).thenReturn("testnetwork");
+ when(network.getState()).thenReturn(State.Implementing);
+ when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
+
+ final DeployDestination dest = mock(DeployDestination.class);
+
+ final DataCenter dc = mock(DataCenter.class);
+ when(dest.getDataCenter()).thenReturn(dc);
+
+ final HostVO niciraHost = mock(HostVO.class);
+ when(hostdao.findById(anyLong())).thenReturn(niciraHost);
+ when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
+ when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
+ when(niciraHost.getId()).thenReturn(NETWORK_ID);
+
+ when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
+ final Domain dom = mock(Domain.class);
+ when(dom.getName()).thenReturn("domain");
+ final Account acc = mock(Account.class);
+ when(acc.getAccountName()).thenReturn("accountname");
+ final ReservationContext res = mock(ReservationContext.class);
+ when(res.getDomain()).thenReturn(dom);
+ when(res.getAccount()).thenReturn(acc);
+
+ final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
+ when(answer.getResult()).thenReturn(true);
+ //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
+ when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
+
+ final Network implementednetwork = guru.implement(network, offering, dest, res);
+ assertTrue(implementednetwork == null);
+ verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
+ }
+
+ @Test
+ public void testShutdown() throws InsufficientVirtualNetworkCapacityException, URISyntaxException {
+ final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
+ when(physnetdao.findById((Long)any())).thenReturn(physnet);
+ when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
+ when(physnet.getId()).thenReturn(NETWORK_ID);
+
+ final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
+ when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
+ when(device.getId()).thenReturn(1L);
+
+ final NetworkOffering offering = mock(NetworkOffering.class);
+ when(offering.getId()).thenReturn(NETWORK_ID);
+ when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+ when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
+
+ mock(DeploymentPlan.class);
+
+ final NetworkVO network = mock(NetworkVO.class);
+ when(network.getName()).thenReturn("testnetwork");
+ when(network.getState()).thenReturn(State.Implementing);
+ when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
+ when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa"));
+ when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
+ when(netdao.findById(NETWORK_ID)).thenReturn(network);
+
+ final DeployDestination dest = mock(DeployDestination.class);
+
+ final DataCenter dc = mock(DataCenter.class);
+ when(dest.getDataCenter()).thenReturn(dc);
+
+ final HostVO niciraHost = mock(HostVO.class);
+ when(hostdao.findById(anyLong())).thenReturn(niciraHost);
+ when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
+ when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
+ when(niciraHost.getId()).thenReturn(NETWORK_ID);
+
+ when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
+ final Domain dom = mock(Domain.class);
+ when(dom.getName()).thenReturn("domain");
+ final Account acc = mock(Account.class);
+ when(acc.getAccountName()).thenReturn("accountname");
+ final ReservationContext res = mock(ReservationContext.class);
+ when(res.getDomain()).thenReturn(dom);
+ when(res.getAccount()).thenReturn(acc);
+
+ final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class);
+ when(answer.getResult()).thenReturn(true);
+ when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
+
+ final NetworkProfile implementednetwork = mock(NetworkProfile.class);
+ when(implementednetwork.getId()).thenReturn(NETWORK_ID);
+ when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa"));
+ when(offering.getSpecifyVlan()).thenReturn(false);
+
+ guru.shutdown(implementednetwork, offering);
+ verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
+ verify(implementednetwork, times(1)).setBroadcastUri(null);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
new file mode 100644
index 0000000..d4c6596
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
@@ -0,0 +1,55 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class NatRuleTest {
+
+ @Test
+ public void testNatRuleEncoding() {
+ final Gson gson =
+ new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter())
+ .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
+ .create();
+
+ final DestinationNatRule rn1 = new DestinationNatRule();
+ rn1.setToDestinationIpAddress("10.10.10.10");
+ rn1.setToDestinationPort(80);
+ final Match mr1 = new Match();
+ mr1.setSourceIpAddresses("11.11.11.11/24");
+ mr1.setEthertype("IPv4");
+ mr1.setProtocol(6);
+ rn1.setMatch(mr1);
+
+ final String jsonString = gson.toJson(rn1);
+ final NatRule dnr = gson.fromJson(jsonString, NatRule.class);
+
+ assertTrue(dnr instanceof DestinationNatRule);
+ assertTrue(rn1.equals(dnr));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
new file mode 100644
index 0000000..3bb4b9d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
@@ -0,0 +1,347 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.UUID;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.cloud.utils.PropertiesUtil;
+
+public class NiciraNvpApiIT {
+
+ protected NiciraNvpApi api;
+
+ protected long timestamp = System.currentTimeMillis();
+
+ @Before
+ public void setup() throws IOException {
+ final Properties properties = PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties"));
+ api = new NiciraNvpApi();
+ api.setControllerAddress(properties.getProperty("nvp.host"));
+ api.setAdminCredentials(properties.getProperty("nvp.admin.user"),
+ properties.getProperty("nvp.admin.pwd"));
+ }
+
+ @Test
+ public void testCRUDSecurityProfile() throws NiciraNvpApiException {
+ SecurityProfile sProfile = new SecurityProfile();
+ sProfile.setDisplayName("SecProfile"+timestamp);
+
+ final List<SecurityRule> egressRules = new ArrayList<SecurityRule>();
+ sProfile.setLogicalPortEgressRules(egressRules);
+ egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 80, 88, 6));
+ egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "2a80:34ac::1", null, 90, 98, 6));
+
+ final List<SecurityRule> ingressRules = new ArrayList<SecurityRule>();
+ sProfile.setLogicalPortIngressRules(ingressRules);
+ ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 50, 58, 6));
+ ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "280a:3ac4::1", null, 60, 68, 6));
+
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ sProfile.setTags(tags);
+ tags.add(new NiciraNvpTag("nvp", "MyTag1"));
+ tags.add(new NiciraNvpTag("nicira", "MyTag2"));
+ // In the creation we don't get to specify UUID, href or schema: they don't exist yet
+
+ try {
+ sProfile = api.createSecurityProfile(sProfile);
+
+ // We can now update the new entity
+ sProfile.setDisplayName("UpdatedSecProfile"+timestamp);
+ api.updateSecurityProfile(sProfile, sProfile.getUuid());
+
+ // Read them all
+ NiciraNvpList<SecurityProfile> profiles = api.findSecurityProfile();
+ SecurityProfile scInList = null;
+ for(final SecurityProfile iProfile : profiles.getResults()) {
+ if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) {
+ scInList = iProfile;
+ }
+ }
+ assertEquals("Read a Security Profile different from the one just created and updated",
+ sProfile, scInList);
+
+ // Read them filtered by uuid (get one)
+ profiles = api.findSecurityProfile(sProfile.getUuid());
+ assertEquals("Read a Security Profile different from the one just created and updated",
+ sProfile,
+ profiles.getResults().get(0));
+ assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item",
+ 1, profiles.getResults().size());
+
+ // We can now delete the new entity
+ api.deleteSecurityProfile(sProfile.getUuid());
+ } catch (final NiciraNvpApiException e) {
+ e.printStackTrace();
+ assertTrue("Errors in Security Profile CRUD", false);
+ }
+ }
+
+ @Test
+ public void testCRUDAcl() throws NiciraNvpApiException {
+ Acl acl = new Acl();
+ acl.setDisplayName("Acl"+timestamp);
+
+ // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type
+ // Note that if the protocol is 1 (ICMP) then you cannot put ports
+ final List<AclRule> egressRules = new ArrayList<AclRule>();
+ acl.setLogicalPortEgressRules(egressRules);
+ egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null,
+ "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
+ egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null,
+ "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
+
+ final List<AclRule> ingressRules = new ArrayList<AclRule>();
+ acl.setLogicalPortIngressRules(ingressRules);
+ ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null,
+ "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
+ ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null,
+ "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
+
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ acl.setTags(tags);
+ tags.add(new NiciraNvpTag("nvp", "MyTag1"));
+ tags.add(new NiciraNvpTag("nicira", "MyTag2"));
+ // In the creation we don't get to specify UUID, href or schema: they don't exist yet
+
+ try {
+ acl = api.createAcl(acl);
+
+ // We can now update the new entity
+ acl.setDisplayName("UpdatedAcl"+timestamp);
+ api.updateAcl(acl, acl.getUuid());
+
+ // Read them all
+ NiciraNvpList<Acl> acls = api.findAcl();
+ Acl scInList = null;
+ for(final Acl iAcl : acls.getResults()) {
+ if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) {
+ scInList = iAcl;
+ }
+ }
+ assertEquals("Read a ACL different from the one just created and updated",
+ acl, scInList);
+
+ // Read them filtered by uuid (get one)
+ acls = api.findAcl(acl.getUuid());
+ assertEquals("Read a ACL different from the one just created and updated",
+ acl,
+ acls.getResults().get(0));
+ assertEquals("Read a ACL filtered by unique id (UUID) with more than one item",
+ 1, acls.getResults().size());
+
+ // We can now delete the new entity
+ api.deleteAcl(acl.getUuid());
+ } catch (final NiciraNvpApiException e) {
+ e.printStackTrace();
+ assertTrue("Errors in ACL CRUD", false);
+ }
+ }
+
+ @Test
+ public void testCRUDLogicalSwitch() throws NiciraNvpApiException {
+ LogicalSwitch logicalSwitch = new LogicalSwitch();
+ logicalSwitch.setDisplayName("LogicalSwitch"+timestamp);
+ logicalSwitch.setPortIsolationEnabled(true);
+ logicalSwitch.setReplicationMode("service");
+ logicalSwitch.setTags(new ArrayList<NiciraNvpTag>());
+ logicalSwitch.getTags().add(new NiciraNvpTag("anto", "hugo"));
+
+ // In the creation we don't get to specify UUID, href or schema: they don't exist yet
+
+ try {
+ logicalSwitch = api.createLogicalSwitch(logicalSwitch);
+
+ // We can now update the new entity
+ logicalSwitch.setDisplayName("UpdatedLogicalSwitch"+timestamp);
+ api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid());
+
+ // Read them all
+ NiciraNvpList<LogicalSwitch> logicalSwitches = api.findLogicalSwitch();
+ for(final LogicalSwitch iLogicalSwitch : logicalSwitches.getResults()) {
+ if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) {
+ assertEquals("Read a LogicalSwitch different from the one just created and updated",
+ logicalSwitch, iLogicalSwitch);
+ }
+ }
+
+ // Read them filtered by uuid (get one)
+ logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid());
+ assertEquals("Read a LogicalSwitch different from the one just created and updated",
+ logicalSwitch,
+ logicalSwitches.getResults().get(0));
+ assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item",
+ 1, logicalSwitches.getResults().size());
+
+ // Before deleting the test LogicalSwitch, test its ports
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
+
+ LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort"+timestamp, tags, true);
+ logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
+
+ logicalSwitchPort.setDisplayName("UpdatedLSwitchPort"+timestamp);
+ api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
+
+ final NiciraNvpList<LogicalSwitchPort> logicalSwitchePorts =
+ api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
+ for(final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts.getResults()) {
+ if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) {
+ assertEquals("Read a LogicalSwitchPort different from the one just created and updated",
+ logicalSwitchPort, iLSwitchPort);
+ }
+ }
+
+ // And finally test attachments
+ final String attachmentUuid = UUID.randomUUID().toString();
+ final VifAttachment vifAttachment = new VifAttachment(attachmentUuid);
+ api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(),
+ vifAttachment);
+
+ assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
+ api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()),
+ logicalSwitchPort.getUuid());
+
+ api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
+
+ // We can now delete the new entity
+ api.deleteLogicalSwitch(logicalSwitch.getUuid());
+ } catch (final NiciraNvpApiException e) {
+ e.printStackTrace();
+ assertTrue("Errors in LogicalSwitch CRUD", false);
+ }
+ }
+
+ @Test
+ public void testCRUDLogicalRouter() throws NiciraNvpApiException {
+ LogicalRouter logicalRouter = new LogicalRouter();
+ logicalRouter.setDisplayName("LogicalRouter"+timestamp);
+ logicalRouter.setDistributed(true);
+ logicalRouter.setNatSynchronizationEnabled(true);
+ logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE);
+ final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig(
+ new RouterNextHop("192.168.10.20"));
+ logicalRouter.setRoutingConfig(routingConfig);
+
+ // In the creation we don't get to specify UUID, href or schema: they don't exist yet
+
+ try {
+ logicalRouter = api.createLogicalRouter(logicalRouter);
+
+ // We can now update the new entity
+ logicalRouter.setDisplayName("UpdatedLogicalSwitch"+timestamp);
+ api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid());
+
+ // Read them all
+ NiciraNvpList<LogicalRouter> logicalRouters = api.findLogicalRouter();
+ LogicalRouter lsInList = null;
+ for(final LogicalRouter iLogicalRouter : logicalRouters.getResults()) {
+ if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) {
+ lsInList = iLogicalRouter;
+ }
+ }
+ assertEquals("Read a LogicalRouter different from the one just created and updated",
+ logicalRouter, lsInList);
+
+ // Read them filtered by uuid (get one)
+ logicalRouters = api.findLogicalRouter(logicalRouter.getUuid());
+ assertEquals("Read a LogicalRouter different from the one just created and updated",
+ logicalRouter,
+ logicalRouters.getResults().get(0));
+ assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item",
+ 1, logicalRouters.getResults().size());
+
+ assertEquals("", logicalRouters.getResults().get(0),
+ api.findOneLogicalRouterByUuid(logicalRouter.getUuid()));
+
+ // Before deleting the test LogicalRouter, test its ports
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
+
+ LogicalRouterPort logicalRouterPort = new LogicalRouterPort();
+ logicalRouterPort.setDisplayName("LRouterPort"+timestamp);
+ logicalRouterPort.setTags(tags);
+ logicalRouterPort.setAdminStatusEnabled(true);
+ logicalRouterPort.setPortno(1024);
+ logicalRouterPort.setMacAddress("00:00:00:00:00:00");
+
+ final List<String> ipAddresses = new ArrayList<String>();
+ // Add some ips to this list
+ logicalRouterPort.setIpAddresses(ipAddresses);
+ logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
+
+ logicalRouterPort.setDisplayName("UpdatedLRouterPort"+timestamp);
+ api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
+
+ final NiciraNvpList<LogicalRouterPort> logicalRouterePorts =
+ api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid());
+ for(final LogicalRouterPort iLRouterPort : logicalRouterePorts.getResults()) {
+ if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) {
+ assertEquals("Read a LogicalRouterPort different from the one just created and updated",
+ logicalRouterPort, iLRouterPort);
+ }
+ }
+
+ UUID.randomUUID().toString();
+
+ // Test CRUD for Nat Rules
+ SourceNatRule snr = new SourceNatRule();
+ snr.setToSourceIpAddressMin("192.168.10.10");
+ snr.setToSourceIpAddressMax("192.168.10.20");
+ snr.setOrder(200);
+ final Match match = new Match();
+ match.setSourceIpAddresses("192.168.150.150");
+ snr.setMatch(match);
+ snr = (SourceNatRule) api.createLogicalRouterNatRule(logicalRouter.getUuid(), snr);
+ snr.setToSourceIpAddressMax("192.168.10.30");
+ api.updateLogicalRouterNatRule(logicalRouter.getUuid(), snr);
+
+ api.findNatRulesByLogicalRouterUuid(logicalRouter.getUuid());
+ api.deleteLogicalRouterNatRule(logicalRouter.getUuid(), snr.getUuid());
+
+ api.deleteLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort.getUuid());
+
+ // We can now delete the new entity
+ api.deleteLogicalRouter(logicalRouter.getUuid());
+ } catch (final NiciraNvpApiException e) {
+ e.printStackTrace();
+ assertTrue("Errors in LogicalRouter CRUD", false);
+ }
+ }
+
+ @Test
+ public void testGetControlClusterStatus() throws NiciraNvpApiException {
+ final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus();
+ final String clusterStatus = controlClusterStatus.getClusterStatus();
+ final boolean correctStatus = (clusterStatus.equalsIgnoreCase("stable") ||
+ clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"));
+ assertTrue("Not recognizable cluster status", correctStatus);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
new file mode 100644
index 0000000..1435cc5
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java
@@ -0,0 +1,339 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Matchers.any;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.params.HttpClientParams;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonParseException;
+import com.cloud.utils.rest.RESTServiceConnector;
+import com.cloud.utils.rest.RESTValidationStrategy;
+
+public class NiciraNvpApiTest {
+ protected static final String UUID = "aaaa";
+ protected static final String UUID2 = "bbbb";
+ protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa";
+ protected static final String SCHEMA = "myTestSchema";
+ protected static final String SCHEMA2 = "myTestSchema2";
+ protected static final String HREF = "myTestHref";
+ protected static final String HREF2 = "myTestHref2";
+ protected static final String SEC_PROFILE_JSON_RESPONSE =
+ "{\"uuid\" : \"aaaa\","
+ + "\"display_name\" : \"myTestName\","
+ + "\"href\" : \"myTestHref\","
+ + "\"schema\" : \"myTestSchema\"}";
+
+ protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\","
+ + "\"display_name\" : \"myTestName\","
+ + "\"href\" : \"myTestHref\","
+ + "\"schema\" : \"myTestSchema\"},"
+ + "{ \"uuid\" : \"bbbb\","
+ + "\"display_name\" : \"myTestName2\","
+ + "\"href\" : \"myTestHref2\","
+ + "\"schema\" : \"myTestSchema2\"}],"
+ + "\"result_count\": 2}";
+
+ NiciraNvpApi api;
+ HttpClient client = mock(HttpClient.class);
+ HttpMethod method;
+ String type;
+ String uri;
+
+ @Before
+ public void setUp() {
+ final HttpClientParams hmp = mock(HttpClientParams.class);
+ when(client.getParams()).thenReturn(hmp);
+ api = new NiciraNvpApi();
+
+ api.restConnector = new RESTServiceConnector(new RESTValidationStrategy()) {
+ @Override
+ public HttpClient createHttpClient() {
+ return client;
+ }
+
+ @Override
+ public HttpMethod createMethod(final String newType, final String newUri) {
+ type = newType;
+ uri = newUri;
+ return method;
+ }
+ };
+
+ api.setAdminCredentials("admin", "adminpass");
+ api.setControllerAddress("localhost");
+ }
+
+ @Test
+ public void testFindSecurityProfile() throws NiciraNvpApiException, IOException {
+ // Prepare
+ method = mock(GetMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
+ final NameValuePair[] queryString = new NameValuePair[]{
+ new NameValuePair("fields","*")};
+
+ // Execute
+ final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile();
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ verify(method, times(1)).setQueryString(queryString);
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ UUID, actualProfiles.getResults().get(0).getUuid());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ HREF, actualProfiles.getResults().get(0).getHref());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ SCHEMA, actualProfiles.getResults().get(0).getSchema());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ UUID2, actualProfiles.getResults().get(1).getUuid());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ HREF2, actualProfiles.getResults().get(1).getHref());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ SCHEMA2, actualProfiles.getResults().get(1).getSchema());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ 2, actualProfiles.getResultCount());
+ assertEquals("Wrong URI for SecurityProfile creation REST service",
+ NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
+ assertEquals("Wrong URI for SecurityProfile creation REST service",
+ NiciraNvpApi.GET_METHOD_TYPE, type);
+ }
+
+ @Test
+ public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException {
+ // Prepare
+ method = mock(GetMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
+ final NameValuePair[] queryString = new NameValuePair[]{
+ new NameValuePair("uuid", UUID),
+ new NameValuePair("fields","*")
+ };
+ final List<NameValuePair> queryStringNvps = new ArrayList<>();
+ doAnswer(new Answer<Void>() {
+
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ final NameValuePair[] arguments = (NameValuePair[]) invocation.getArguments()[0];
+ queryStringNvps.addAll(Arrays.asList(arguments));
+ return null;
+ }}).when(method).setQueryString(any(NameValuePair[].class));
+
+ // Execute
+ final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID);
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertTrue(queryStringNvps.containsAll(Arrays.asList(queryString)));
+ assertEquals(queryString.length, queryStringNvps.size());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ UUID, actualProfiles.getResults().get(0).getUuid());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ HREF, actualProfiles.getResults().get(0).getHref());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ SCHEMA, actualProfiles.getResults().get(0).getSchema());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ UUID2, actualProfiles.getResults().get(1).getUuid());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ HREF2, actualProfiles.getResults().get(1).getHref());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ SCHEMA2, actualProfiles.getResults().get(1).getSchema());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ 2, actualProfiles.getResultCount());
+ assertEquals("Wrong URI for SecurityProfile creation REST service",
+ NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
+ assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
+ NiciraNvpApi.GET_METHOD_TYPE, type);
+ }
+
+ @Test
+ public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final SecurityProfile inputSecProfile = new SecurityProfile();
+ method = mock(PostMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
+ when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE);
+
+ // Execute
+ final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile);
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ UUID, actualSecProfile.getUuid());
+ assertEquals("Wrong Uuid in the newly created SecurityProfile",
+ HREF, actualSecProfile.getHref());
+ assertEquals("Wrong Schema in the newly created SecurityProfile",
+ SCHEMA, actualSecProfile.getSchema());
+ assertEquals("Wrong URI for SecurityProfile creation REST service",
+ NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
+ assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
+ NiciraNvpApi.POST_METHOD_TYPE, type);
+ }
+
+ @Test
+ public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final SecurityProfile inputSecProfile = new SecurityProfile();
+ method = mock(PutMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+
+ // Execute
+ api.updateSecurityProfile(inputSecProfile, UUID);
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertEquals("Wrong URI for SecurityProfile creation REST service",
+ UUID_SEC_PROFILE_URI, uri);
+ assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
+ NiciraNvpApi.PUT_METHOD_TYPE, type);
+ }
+
+ @Test
+ public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException {
+ // Prepare
+ method = mock(DeleteMethod.class);
+ when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+
+ // Execute
+ api.deleteSecurityProfile(UUID);
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertEquals("Wrong URI for SecurityProfile deletion REST service", UUID_SEC_PROFILE_URI, uri);
+ assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", NiciraNvpApi.DELETE_METHOD_TYPE, type);
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testRoutingConfigAdapterNoType() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ gson.fromJson("{}", RoutingConfig.class);
+
+ // Assert: JsonParseException should be thrown
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testRoutingConfigAdapterWrongType() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class);
+
+ // Assert: JsonParseException should be thrown
+ }
+
+ @Test()
+ public void testRoutingConfigAdapter() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig =
+ (SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class);
+
+ // Assert: JsonParseException should be thrown
+ assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass());
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ gson.fromJson("{}", NatRule.class);
+
+ // Assert: JsonParseException should be thrown
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ gson.fromJson("{type : \"WrongType\"}", NatRule.class);
+
+ // Assert: JsonParseException should be thrown
+ }
+
+ @Test()
+ public void testRoutingConfigAdapterWithSourceNatRule() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ final SourceNatRule sourceNatRule =
+ (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class);
+
+ // Assert: JsonParseException should be thrown
+ assertEquals("", SourceNatRule.class, sourceNatRule.getClass());
+ }
+
+ @Test()
+ public void testRoutingConfigAdapterWithDestinationNatRule() throws NiciraNvpApiException, IOException {
+ // Prepare
+ final NiciraNvpApi api = new NiciraNvpApi();
+ final Gson gson = api.restConnector.getGson();
+
+ // Execute
+ final DestinationNatRule destinationNatRule =
+ (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class);
+
+ // Assert: JsonParseException should be thrown
+ assertEquals("", DestinationNatRule.class, destinationNatRule.getClass());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java
new file mode 100644
index 0000000..7a31264
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.nicira;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class NiciraTagTest {
+ @Test
+ public void testCreateTag() {
+ final NiciraNvpTag tag = new NiciraNvpTag("scope", "tag");
+ assertEquals("scope part set", "scope", tag.getScope());
+ assertEquals("tag part set", "tag", tag.getTag());
+ }
+
+ @Test
+ public void testCreateLongTag() {
+ final NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght");
+ assertEquals("scope part set", "scope", tag.getScope());
+ assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag());
+ }
+
+ @Test
+ public void testSetTag() {
+ final NiciraNvpTag tag = new NiciraNvpTag();
+ tag.setScope("scope");
+ tag.setTag("tag");
+ assertEquals("scope part set", "scope", tag.getScope());
+ assertEquals("tag part set", "tag", tag.getTag());
+ }
+
+ @Test
+ public void testSetLongTag() {
+ final NiciraNvpTag tag = new NiciraNvpTag();
+ tag.setScope("scope");
+ tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght");
+ assertEquals("scope part set", "scope", tag.getScope());
+ assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag());
+ }
+}
\ No newline at end of file
[45/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Delegate HTTP protocol activity in RESTServiceConnector to RestClient
- All HTTP protocol activities are now handled by RestClient
- This service is now only responsible for creating requests, and
dispatching them to the client
- Provides a Simple API for creating, updating, retrieving and deleting
objects
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/de63b94f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/de63b94f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/de63b94f
Branch: refs/heads/deploy-from-snapshot
Commit: de63b94f2dc571e74ce5eaa68c74ed6a9edf420c
Parents: 8a93bb8
Author: Miguel Ferreira <mi...@me.com>
Authored: Sun Aug 23 15:11:29 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:14 2015 +0200
----------------------------------------------------------------------
.../BasicEncodedRESTValidationStrategy.java | 66 ---
.../cloud/utils/rest/RESTServiceConnector.java | 391 +++----------
.../utils/rest/RESTValidationStrategy.java | 159 ------
.../utils/rest/HttpUriRequestMethodMatcher.java | 44 ++
.../rest/HttpUriRequestPayloadMatcher.java | 62 +++
.../utils/rest/RESTServiceConnectorTest.java | 553 ++++++++-----------
6 files changed, 430 insertions(+), 845 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/de63b94f/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java b/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
deleted file mode 100644
index bf001cd..0000000
--- a/utils/src/main/java/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
+++ /dev/null
@@ -1,66 +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 com.cloud.utils.rest;
-
-import java.io.IOException;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethodBase;
-
-/**
- * Base 64 encoded authorization strategy. This implementation as opposed to
- * {@link RESTValidationStrategy} doesn't do a login after auth error, but instead
- * includes the encoded credentials in each request, instead of a cookie.
- */
-public class BasicEncodedRESTValidationStrategy extends RESTValidationStrategy {
-
- public BasicEncodedRESTValidationStrategy(final String host, final String adminuser, final String adminpass) {
- super();
- this.host = host;
- user = adminuser;
- password = adminpass;
- }
-
- public BasicEncodedRESTValidationStrategy() {
- }
-
- @Override
- public void executeMethod(final HttpMethodBase method, final HttpClient client,
- final String protocol)
- throws CloudstackRESTException, HttpException, IOException {
- if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
- throw new CloudstackRESTException("Hostname/credentials are null or empty");
- }
-
- final String encodedCredentials = encodeCredentials();
- method.setRequestHeader("Authorization", "Basic " + encodedCredentials);
- client.executeMethod(method);
- }
-
- private String encodeCredentials() {
- final String authString = user + ":" + password;
- final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
- final String authStringEnc = new String(authEncBytes);
- return authStringEnc;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/de63b94f/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
index 01aca89..fc5bae3 100644
--- a/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
+++ b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java
@@ -20,371 +20,146 @@
package com.cloud.utils.rest;
import java.io.IOException;
-import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MalformedURLException;
-import java.net.Socket;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashMap;
import java.util.Map;
-import java.util.Map.Entry;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.apache.cloudstack.utils.security.SSLUtils;
-import org.apache.cloudstack.utils.security.SecureSSLSocketFactory;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
-import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.httpclient.cookie.CookiePolicy;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.methods.StringRequestEntity;
-import org.apache.commons.httpclient.params.HttpConnectionParams;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
-import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
+import com.google.common.base.Optional;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
-import com.google.gson.reflect.TypeToken;
/**
- * This abstraction encapsulates client side code for REST service communication. It encapsulates access in a delegate validation strategy. There may different implementations
- * extending {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
+ * This abstraction encapsulates client side code for REST service communication. It encapsulates access in a REST client. There can be different implementations of that client
+ * implementing {@link RestClient}, and any of them should mention the needed data to work.
*
- * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide in the constructor a list of classes and a list of deserializers for these
- * classes. These should be a correlated so that Nth deserializer is correctly mapped to Nth class.
+ * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide in the constructor a map of classes to deserializers for these classes.
*/
public class RESTServiceConnector {
- private static final String HTTPS = "https";
- protected static final String GET_METHOD_TYPE = "get";
- protected static final String DELETE_METHOD_TYPE = "delete";
- protected static final String PUT_METHOD_TYPE = "put";
- protected static final String POST_METHOD_TYPE = "post";
- private static final String TEXT_HTML_CONTENT_TYPE = "text/html";
- private static final String JSON_CONTENT_TYPE = "application/json";
- private static final String CONTENT_TYPE = "Content-Type";
- private static final int BODY_RESP_MAX_LEN = 1024;
- private static final int HTTPS_PORT = 443;
private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class);
- protected final static String protocol = HTTPS;
-
- private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
-
- protected RESTValidationStrategy validation;
-
- private final HttpClient client;
+ private static final Optional<String> ABSENT = Optional.absent();
+ private final RestClient client;
private final Gson gson;
- /**
- * Getter that may be needed only for test purpose
- *
- * @return
- */
- public Gson getGson() {
- return gson;
+ private RESTServiceConnector(final Builder builder) {
+ client = builder.client;
+ gson = setGsonDeserializer(builder.classToDeserializerMap);
}
- public RESTServiceConnector(final RESTValidationStrategy validationStrategy) {
- this(validationStrategy, null, null);
- }
-
- public RESTServiceConnector(final RESTValidationStrategy validationStrategy, final List<Class<?>> classList, final List<JsonDeserializer<?>> deserializerList) {
- validation = validationStrategy;
- client = createHttpClient();
- client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
-
- try {
- // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
- Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
- } catch (final IOException e) {
- s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
- }
-
+ private static Gson setGsonDeserializer(final Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap) {
final GsonBuilder gsonBuilder = new GsonBuilder();
- if (classList != null && deserializerList != null) {
- for (int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
- gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
- }
+ for (final Map.Entry<Class<?>, JsonDeserializer<?>> entry : classToDeserializerMap.entrySet()) {
+ gsonBuilder.registerTypeAdapter(entry.getKey(), entry.getValue());
}
- gson = gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
+ return gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
}
- public HttpClient createHttpClient() {
- return new HttpClient(s_httpClientManager);
+ public static Builder create() {
+ return new Builder();
}
- public HttpMethod createMethod(final String type, final String uri) throws CloudstackRESTException {
- String url;
- try {
- url = new URL(protocol, validation.getHost(), uri).toString();
- } catch (final MalformedURLException e) {
- s_logger.error("Unable to build REST Service URL", e);
- throw new CloudstackRESTException("Unable to build Nicira API URL", e);
- }
-
- if (POST_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new PostMethod(url);
- } else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new GetMethod(url);
- } else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new DeleteMethod(url);
- } else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new PutMethod(url);
- } else {
- throw new CloudstackRESTException("Requesting unknown method type");
- }
+ public <T> void executeUpdateObject(final T newObject, final String path, final Map<String, String> parameters) throws CloudstackRESTException {
+ s_logger.debug("Executing update object on " + path);
+ client.closeResponse(createAndExecuteRequest(HttpMethods.PUT, path, parameters, Optional.fromNullable(gson.toJson(newObject))));
}
- public void setControllerAddress(final String address) {
- validation.setHost(address);
+ public <T> void executeUpdateObject(final T newObject, final String path) throws CloudstackRESTException {
+ executeUpdateObject(newObject, path, new HashMap<String, String>());
}
- public void setAdminCredentials(final String username, final String password) {
- validation.setUser(username);
- validation.setPassword(password);
+ @SuppressWarnings("unchecked")
+ public <T> T executeCreateObject(final T newObject, final String path, final Map<String, String> parameters) throws CloudstackRESTException {
+ s_logger.debug("Executing create object on " + path);
+ final CloseableHttpResponse response = createAndExecuteRequest(HttpMethods.POST, path, parameters, Optional.fromNullable(gson.toJson(newObject)));
+ return (T) readResponseBody(response, newObject.getClass());
}
- public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
-
- final PutMethod pm = (PutMethod) createMethod(PUT_METHOD_TYPE, uri);
- pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
- try {
- pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
- } catch (final UnsupportedEncodingException e) {
- throw new CloudstackRESTException("Failed to encode json request body", e);
- }
-
- executeMethod(pm);
-
- if (pm.getStatusCode() != HttpStatus.SC_OK) {
- final String errorMessage = responseToErrorMessage(pm);
- pm.releaseConnection();
- s_logger.error("Failed to update object : " + errorMessage);
- throw new CloudstackRESTException("Failed to update object : " + errorMessage);
- }
- pm.releaseConnection();
+ public <T> T executeCreateObject(final T newObject, final String uri) throws CloudstackRESTException {
+ return executeCreateObject(newObject, uri, new HashMap<String, String>());
}
- @SuppressWarnings("unchecked")
- public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
-
- final PostMethod pm = (PostMethod) createMethod(POST_METHOD_TYPE, uri);
- pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
- try {
- pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
- } catch (final UnsupportedEncodingException e) {
- throw new CloudstackRESTException("Failed to encode json request body", e);
- }
-
- executeMethod(pm);
-
- if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
- final String errorMessage = responseToErrorMessage(pm);
- pm.releaseConnection();
- s_logger.error("Failed to create object : " + errorMessage);
- throw new CloudstackRESTException("Failed to create object : " + errorMessage);
- }
-
- T result;
- try {
- result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
- } catch (final IOException e) {
- throw new CloudstackRESTException("Failed to decode json response body", e);
- } finally {
- pm.releaseConnection();
- }
-
- return result;
+ public void executeDeleteObject(final String path) throws CloudstackRESTException {
+ s_logger.debug("Executing delete object on " + path);
+ client.closeResponse(createAndExecuteRequest(HttpMethods.DELETE, path, new HashMap<String, String>(), ABSENT));
}
- public void executeDeleteObject(final String uri) throws CloudstackRESTException {
- final DeleteMethod dm = (DeleteMethod) createMethod(DELETE_METHOD_TYPE, uri);
- dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
-
- executeMethod(dm);
-
- if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
- final String errorMessage = responseToErrorMessage(dm);
- dm.releaseConnection();
- s_logger.error("Failed to delete object : " + errorMessage);
- throw new CloudstackRESTException("Failed to delete object : " + errorMessage);
- }
- dm.releaseConnection();
+ public <T> T executeRetrieveObject(final Type returnObjectType, final String path, final Map<String, String> parameters) throws CloudstackRESTException {
+ s_logger.debug("Executing retrieve object on " + path);
+ final CloseableHttpResponse response = createAndExecuteRequest(HttpMethods.GET, path, parameters, ABSENT);
+ return readResponseBody(response, returnObjectType);
}
- @SuppressWarnings("unchecked")
- public <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
- final GetMethod gm = (GetMethod) createMethod(GET_METHOD_TYPE, uri);
- gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
- if (parameters != null && !parameters.isEmpty()) {
- final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
- for (final Entry<String, String> e : parameters.entrySet()) {
- nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
- }
- gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
- }
-
- executeMethod(gm);
+ public <T> T executeRetrieveObject(final Type returnObjectType, final String path) throws CloudstackRESTException {
+ return executeRetrieveObject(returnObjectType, path, new HashMap<String, String>());
+ }
- if (gm.getStatusCode() != HttpStatus.SC_OK) {
- final String errorMessage = responseToErrorMessage(gm);
- gm.releaseConnection();
- s_logger.error("Failed to retrieve object : " + errorMessage);
- throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
- }
+ private CloseableHttpResponse createAndExecuteRequest(final HttpMethods method, final String path, final Map<String, String> parameters, final Optional<String> jsonPayLoad)
+ throws CloudstackRESTException {
+ final HttpUriRequest httpRequest = HttpUriRequestBuilder.create()
+ .path(path)
+ .parameters(parameters)
+ .jsonPayload(jsonPayLoad)
+ .method(method)
+ .build();
+ if (jsonPayLoad.isPresent()) {
+ s_logger.debug("Built request '" + httpRequest + "' with payload: " + jsonPayLoad);
+ }
+ return executeRequest(httpRequest);
+ }
- T returnValue;
- try {
- returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
- } catch (final IOException e) {
- s_logger.error("IOException while retrieving response body", e);
- throw new CloudstackRESTException(e);
- } finally {
- gm.releaseConnection();
- }
- return returnValue;
+ private CloseableHttpResponse executeRequest(final HttpUriRequest httpRequest) throws CloudstackRESTException {
+ final CloseableHttpResponse response = client.execute(httpRequest);
+ s_logger.debug("Executed request: " + httpRequest + " status was " + response.getStatusLine().toString());
+ return response;
}
- public void executeMethod(final HttpMethodBase method) throws CloudstackRESTException {
+ private <T> T readResponseBody(final CloseableHttpResponse response, final Type type) throws CloudstackRESTException {
+ final HttpEntity entity = response.getEntity();
try {
- validation.executeMethod(method, client, protocol);
- } catch (final HttpException e) {
- s_logger.error("HttpException caught while trying to connect to the REST Service", e);
- method.releaseConnection();
- throw new CloudstackRESTException("API call to REST Service Failed", e);
+ final String stringEntity = EntityUtils.toString(entity);
+ s_logger.debug("Response entity: " + stringEntity);
+ EntityUtils.consumeQuietly(entity);
+ return gson.fromJson(stringEntity, type);
} catch (final IOException e) {
- s_logger.error("IOException caught while trying to connect to the REST Service", e);
- method.releaseConnection();
- throw new CloudstackRESTException("API call to Nicira REST Service Failed", e);
- }
- }
-
- private static String responseToErrorMessage(final HttpMethodBase method) {
- assert method.isRequestSent() : "no use getting an error message unless the request is sent";
-
- if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
- // The error message is the response content
- // Safety margin of 1024 characters, anything longer is probably useless
- // and will clutter the logs
- try {
- return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
- } catch (final IOException e) {
- s_logger.debug("Error while loading response body", e);
- }
+ throw new CloudstackRESTException("Could not deserialize response to JSON. Entity: " + entity, e);
+ } finally {
+ client.closeResponse(response);
}
- // The default
- return method.getStatusText();
}
- /*
- * Some controllers use a self-signed certificate. The TrustingProtocolSocketFactory will accept any provided certificate when making an SSL connection to the SDN Manager
- */
- private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
-
- private SSLSocketFactory ssf;
-
- public TrustingProtocolSocketFactory() throws IOException {
- // Create a trust manager that does not validate certificate chains
- final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- @Override
- public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
- // Trust always
- }
-
- @Override
- public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
- // Trust always
- }
- } };
-
- try {
- // Install the all-trusting trust manager
- final SSLContext sc = SSLUtils.getSSLContext();
- sc.init(null, trustAllCerts, new java.security.SecureRandom());
- ssf = new SecureSSLSocketFactory(sc);
- } catch (final KeyManagementException e) {
- throw new IOException(e);
- } catch (final NoSuchAlgorithmException e) {
- throw new IOException(e);
- }
- }
+ public static class Builder {
+ private RestClient client;
+ final private Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap = new HashMap<Class<?>, JsonDeserializer<?>>();
- @Override
- public Socket createSocket(final String host, final int port) throws IOException {
- final SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
- socket.setEnabledProtocols(SSLUtils.getSupportedProtocols(socket.getEnabledProtocols()));
- return socket;
+ public Builder client(final RestClient client) {
+ this.client = client;
+ return this;
}
- @Override
- public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
- final Socket socket = ssf.createSocket(address, port, localAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket) socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
- }
- return socket;
+ public Builder classToDeserializerMap(final Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap) {
+ this.classToDeserializerMap.clear();
+ this.classToDeserializerMap.putAll(classToDeserializerMap);
+ return this;
}
- @Override
- public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
- final Socket s = ssf.createSocket(socket, host, port, autoClose);
- if (s instanceof SSLSocket) {
- ((SSLSocket) s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) s).getEnabledProtocols()));
- }
- return s;
+ public Builder classToDeserializerEntry(final Class<?> clazz, final JsonDeserializer<?> deserializer) {
+ classToDeserializerMap.put(clazz, deserializer);
+ return this;
}
- @Override
- public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException,
- UnknownHostException, ConnectTimeoutException {
- final int timeout = params.getConnectionTimeout();
- if (timeout == 0) {
- final Socket socket = createSocket(host, port, localAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket) socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
- }
- return socket;
- } else {
- final Socket s = ssf.createSocket();
- if (s instanceof SSLSocket) {
- ((SSLSocket) s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket) s).getEnabledProtocols()));
- }
- s.bind(new InetSocketAddress(localAddress, localPort));
- s.connect(new InetSocketAddress(host, port), timeout);
- return s;
- }
+ public RESTServiceConnector build() {
+ return new RESTServiceConnector(this);
}
}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/de63b94f/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
deleted file mode 100644
index 8ec920a..0000000
--- a/utils/src/main/java/com/cloud/utils/rest/RESTValidationStrategy.java
+++ /dev/null
@@ -1,159 +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 com.cloud.utils.rest;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.log4j.Logger;
-
-/**
- * Basic authentication strategy. This strategy needs user and password for authentication.
- *
- * A login URL is needed which will be used for login and getting the cookie to be used in next requests. If an executeMethod request fails due to authorization it will try to
- * login, get the cookie and repeat the attempt to execute the method.
- */
-public class RESTValidationStrategy {
-
- private static final Logger s_logger = Logger.getLogger(RESTValidationStrategy.class);
-
- protected String host;
- protected String user;
- protected String password;
- protected String serverVersion;
- protected String loginUrl;
-
- public RESTValidationStrategy(final String host, final String user, final String password, final String serverVersion, final String loginUrl) {
- super();
- this.host = host;
- this.user = user;
- this.password = password;
- this.serverVersion = serverVersion;
- this.loginUrl = loginUrl;
- }
-
- public RESTValidationStrategy(final String loginUrl) {
- this.loginUrl = loginUrl;
- }
-
- public RESTValidationStrategy() {
- }
-
- public String getUser() {
- return user;
- }
-
- public void setUser(final String user) {
- this.user = user;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(final String password) {
- this.password = password;
- }
-
- public String getLoginUrl() {
- return loginUrl;
- }
-
- public void setLoginUrl(final String loginUrl) {
- this.loginUrl = loginUrl;
- }
-
- public String getHost() {
- return host;
- }
-
- public void setHost(final String host) {
- this.host = host;
- }
-
- public void executeMethod(final HttpMethodBase method, final HttpClient client, final String protocol) throws CloudstackRESTException, HttpException, IOException {
- if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
- throw new CloudstackRESTException("Hostname/credentials are null or empty");
- }
-
- client.executeMethod(method);
- if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
- method.releaseConnection();
- // login and try again
- login(protocol, client);
- client.executeMethod(method);
- }
- }
-
- /**
- * Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable.
- * <p>
- * The method returns false if the login failed or the connection could not be made.
- *
- */
- protected void login(final String protocol, final HttpClient client) throws CloudstackRESTException {
- String url;
-
- if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
- throw new CloudstackRESTException("Hostname/credentials are null or empty");
- }
-
- try {
- url = new URL(protocol, host, loginUrl).toString();
- } catch (final MalformedURLException e) {
- s_logger.error("Unable to build Nicira API URL", e);
- throw new CloudstackRESTException("Unable to build Nicira API URL", e);
- }
-
- final PostMethod pm = new PostMethod(url);
- pm.addParameter("username", user);
- pm.addParameter("password", password);
-
- try {
- client.executeMethod(pm);
- } catch (final HttpException e) {
- throw new CloudstackRESTException("REST Service API login failed ", e);
- } catch (final IOException e) {
- throw new CloudstackRESTException("REST Service API login failed ", e);
- } finally {
- pm.releaseConnection();
- }
-
- if (pm.getStatusCode() != HttpStatus.SC_OK) {
- s_logger.error("REST Service API login failed : " + pm.getStatusText());
- throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText());
- }
-
- // Extract the version for later use
- if (pm.getResponseHeader("Server") != null) {
- serverVersion = pm.getResponseHeader("Server").getValue();
- s_logger.debug("Server reports version " + serverVersion);
- }
-
- // Success; the cookie required for login is kept in _client
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/de63b94f/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java
new file mode 100644
index 0000000..f2d091f
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.rest;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.mockito.Matchers.argThat;
+
+import org.apache.http.client.methods.HttpUriRequest;
+import org.hamcrest.FeatureMatcher;
+import org.hamcrest.Matcher;
+
+public class HttpUriRequestMethodMatcher extends FeatureMatcher<HttpUriRequest, String> {
+
+ public static HttpUriRequest aMethod(final String method) {
+ return argThat(new HttpUriRequestMethodMatcher(equalTo(method), "method", "method"));
+ }
+
+ public HttpUriRequestMethodMatcher(final Matcher<? super String> subMatcher, final String featureDescription, final String featureName) {
+ super(subMatcher, featureDescription, featureName);
+ }
+
+ @Override
+ protected String featureValueOf(final HttpUriRequest actual) {
+ return actual.getMethod();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/de63b94f/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java
new file mode 100644
index 0000000..724f495
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java
@@ -0,0 +1,62 @@
+//
+// 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 com.cloud.utils.rest;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.mockito.Matchers.argThat;
+
+import java.io.IOException;
+
+import org.apache.http.HttpEntityEnclosingRequest;
+import org.apache.http.ParseException;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.util.EntityUtils;
+import org.hamcrest.FeatureMatcher;
+import org.hamcrest.Matcher;
+
+public class HttpUriRequestPayloadMatcher extends FeatureMatcher<HttpUriRequest, String> {
+
+ public static HttpUriRequest aPayload(final String payload) {
+ return argThat(hasPayload(payload));
+ }
+
+ public static HttpUriRequestPayloadMatcher hasPayload(final String payload) {
+ return new HttpUriRequestPayloadMatcher(equalTo(payload), "payload", "payload");
+ }
+
+ public HttpUriRequestPayloadMatcher(final Matcher<? super String> subMatcher, final String featureDescription, final String featureName) {
+ super(subMatcher, featureDescription, featureName);
+ }
+
+ @Override
+ protected String featureValueOf(final HttpUriRequest actual) {
+ String payload = "";
+ if (actual instanceof HttpEntityEnclosingRequest) {
+ try {
+ payload = EntityUtils.toString(((HttpEntityEnclosingRequest) actual).getEntity());
+ } catch (final ParseException e) {
+ throw new IllegalArgumentException("Couldn't read request's entity payload.", e);
+ } catch (final IOException e) {
+ throw new IllegalArgumentException("Couldn't read request's entity payload.", e);
+ }
+ }
+ return payload;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/de63b94f/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
index b177fe1..e26ee6a 100644
--- a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
+++ b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java
@@ -19,376 +19,305 @@
package com.cloud.utils.rest;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import java.io.IOException;
-import java.util.Collections;
-
-import org.apache.commons.httpclient.Header;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.params.HttpClientParams;
-import org.apache.http.HttpStatus;
-import org.junit.Before;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.ProtocolVersion;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.message.BasicStatusLine;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.map.type.CollectionType;
import org.junit.Test;
-public class RESTServiceConnectorTest {
- protected static final String UUID = "aaaa";
- protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}";
-
- RESTServiceConnector connector;
- HttpClient client = mock(HttpClient.class);
- HttpMethod method;
- String type;
- String uri;
-
- @Before
- public void setUp() {
- final HttpClientParams hmp = mock(HttpClientParams.class);
- when(client.getParams()).thenReturn(hmp);
- connector = new RESTServiceConnector(null) {
- @Override
- public HttpClient createHttpClient() {
- return client;
- }
-
- @Override
- public HttpMethod createMethod(final String newType, final String newUri) {
- type = newType;
- uri = newUri;
- return method;
- }
- };
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
- connector.validation = new RESTValidationStrategy();
- connector.setAdminCredentials("admin", "adminpass");
- connector.setControllerAddress("localhost");
- }
-
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteLoginWithoutHostname() throws CloudstackRESTException {
- connector.setControllerAddress(null);
- connector.validation.login(RESTServiceConnector.protocol, client);
+public class RESTServiceConnectorTest {
+ private static final BasicStatusLine HTTP_200_STATUS_LINE = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
+ private static final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
+ private static final Map<String, String> DEFAULT_TEST_PARAMETERS = new HashMap<String, String>();
+ static {
+ DEFAULT_TEST_PARAMETERS.put("arg1", "val1");
+ DEFAULT_TEST_PARAMETERS.put("arg2", "val2");
}
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteLoginWithoutCredentials() throws CloudstackRESTException {
- method = mock(PutMethod.class);
- connector.setAdminCredentials(null, null);
- connector.validation.login(RESTServiceConnector.protocol, client);
- }
+ @Test
+ public void testExecuteUpdateObject() throws Exception {
+ final TestPojo newObject = new TestPojo();
+ newObject.setField("newValue");
+ final String newObjectJson = gson.toJson(newObject);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(PutMethod.class);
- connector.setControllerAddress(null);
- connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
- }
+ connector.executeUpdateObject(newObject, "/somepath");
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(PutMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
}
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(PostMethod.class);
- connector.setControllerAddress(null);
- connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
- }
+ @Test
+ public void testExecuteUpdateObjectWithParameters() throws Exception {
+ final TestPojo newObject = new TestPojo();
+ newObject.setField("newValue");
+ final String newObjectJson = gson.toJson(newObject);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(PostMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
- }
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(DeleteMethod.class);
- connector.setControllerAddress(null);
- connector.executeDeleteObject("/");
- }
+ connector.executeUpdateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(DeleteMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeDeleteObject("/");
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
}
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectWithoutHostname() throws CloudstackRESTException {
- method = mock(GetMethod.class);
- connector.setControllerAddress(null);
- connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
+ @Test
+ public void testExecuteCreateObject() throws Exception {
+ final TestPojo newObject = new TestPojo();
+ newObject.setField("newValue");
+ final String newObjectJson = gson.toJson(newObject);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
+
+ final TestPojo object = connector.executeCreateObject(newObject, "/somepath");
+
+ assertThat(object, notNullValue());
+ assertThat(object, equalTo(newObject));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
+ verify(response).close();
}
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectWithoutCredentials() throws CloudstackRESTException {
- method = mock(GetMethod.class);
- connector.setAdminCredentials(null, null);
- connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
+ @Test
+ public void testExecuteCreateObjectWithParameters() throws Exception {
+ final TestPojo newObject = new TestPojo();
+ newObject.setField("newValue");
+ final String newObjectJson = gson.toJson(newObject);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
+
+ final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);
+
+ assertThat(object, notNullValue());
+ assertThat(object, equalTo(newObject));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
+ verify(response).close();
}
@Test
- public void testExecuteMethod() throws CloudstackRESTException {
- final GetMethod gm = mock(GetMethod.class);
+ public void testExecuteDeleteObject() throws Exception {
+ final HttpEntity entity = mock(HttpEntity.class);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getEntity()).thenReturn(entity);
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
- when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- connector.executeMethod(gm);
- verify(gm, times(1)).getStatusCode();
- }
+ connector.executeDeleteObject("/somepath");
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException {
- final GetMethod gm = mock(GetMethod.class);
- when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
- when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
- connector.executeMethod(gm);
- verify(gm, times(1)).getStatusCode();
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("DELETE"), any(HttpClientContext.class));
+ verify(response).close();
}
- /*
- * Bit of a roundabout way to ensure that login is called after an un authorized result It not possible to properly mock login()
- */
- public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException {
- // Prepare
- final GetMethod gm = mock(GetMethod.class);
- when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
-
- final RESTValidationStrategy previousValidationStrategy = connector.validation;
- connector.validation = new RESTValidationStrategy() {
- @Override
- protected void login(final String protocol, final HttpClient client) throws CloudstackRESTException {
- // Do nothing
- }
- };
- connector.setAdminCredentials("admin", "adminpass");
- connector.setControllerAddress("localhost");
-
- // Execute
- connector.executeMethod(gm);
- // Leave mock object as is was
- connector.validation = previousValidationStrategy;
-
- // Assert/verify
- verify(gm, times(2)).getStatusCode();
+ @Test
+ public void testExecuteRetrieveObject() throws Exception {
+ final TestPojo existingObject = new TestPojo();
+ existingObject.setField("existingValue");
+ final String newObjectJson = gson.toJson(existingObject);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
+
+ final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath");
+
+ assertThat(object, notNullValue());
+ assertThat(object, equalTo(existingObject));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
+ verify(response).close();
}
@Test
- public void testExecuteCreateObject() throws CloudstackRESTException, IOException {
- JsonEntity ls = new JsonEntity();
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
- assertTrue(UUID.equals(ls.getUuid()));
- verify(method, times(1)).releaseConnection();
-
+ public void testExecuteRetrieveObjectWithParameters() throws Exception {
+ final TestPojo existingObject = new TestPojo();
+ existingObject.setField("existingValue");
+ final String newObjectJson = gson.toJson(existingObject);
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();
+
+ final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath", DEFAULT_TEST_PARAMETERS);
+
+ assertThat(object, notNullValue());
+ assertThat(object, equalTo(existingObject));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
+ verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
+ verify(response).close();
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testCustomDeserializerTypeMismatch() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ when(response.getEntity()).thenReturn(new StringEntity("[{somethig_not_type : \"WrongType\"}]"));
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder()
+ .client(restClient)
+ .classToDeserializerEntry(TestPojo.class, new TestPojoDeserializer())
+ .build();
+
+ connector.executeRetrieveObject(TestPojo.class, "/somepath");
}
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectFailure() throws CloudstackRESTException, IOException {
- JsonEntity ls = new JsonEntity();
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
+ @Test
+ public void testCustomDeserializerForCustomLists() throws Exception {
+ final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
+ when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
+ when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}"));
+ final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
+ when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
+ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
+ final Class<? extends CollectionType> clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass();
+ final RESTServiceConnector connector = new RESTServiceConnector.Builder()
+ .client(restClient)
+ .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer<TestPojoDeserializer>())
+ .build();
+
+ connector.executeRetrieveObject(TestPojo.class, "/somepath");
+ }
+
+ class NiciraList<T> {
+ private List<T> results;
+ private int resultCount;
+
+ public List<T> getResults() {
+ return results;
}
- }
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteCreateObjectException() throws CloudstackRESTException, IOException {
- JsonEntity ls = new JsonEntity();
- when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- try {
- ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
+ public void setResults(final List<T> results) {
+ this.results = results;
}
- }
-
- @Test
- public void testExecuteUpdateObject() throws CloudstackRESTException, IOException {
- final JsonEntity ls = new JsonEntity();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
- verify(method, times(1)).releaseConnection();
- verify(client, times(1)).executeMethod(method);
- }
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectFailure() throws CloudstackRESTException, IOException {
- final JsonEntity ls = new JsonEntity();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
+ public int getResultCount() {
+ return resultCount;
}
- }
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteUpdateObjectException() throws CloudstackRESTException, IOException {
- final JsonEntity ls = new JsonEntity();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(client.executeMethod((HttpMethod) any())).thenThrow(new IOException());
- try {
- connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
+ public void setResultCount(final int resultCount) {
+ this.resultCount = resultCount;
}
- }
- @Test
- public void testExecuteDeleteObject() throws CloudstackRESTException, IOException {
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
- connector.executeDeleteObject("/");
- verify(method, times(1)).releaseConnection();
- verify(client, times(1)).executeMethod(method);
}
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectFailure() throws CloudstackRESTException, IOException {
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- connector.executeDeleteObject("/");
- } finally {
- verify(method, times(1)).releaseConnection();
- }
- }
+ class TestPojo {
+ private String field;
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteDeleteObjectException() throws CloudstackRESTException, IOException {
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
- when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
- try {
- connector.executeDeleteObject("/");
- } finally {
- verify(method, times(1)).releaseConnection();
+ public String getField() {
+ return field;
}
- }
-
- @Test
- public void testExecuteRetrieveObject() throws CloudstackRESTException, IOException {
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
- verify(method, times(1)).releaseConnection();
- verify(client, times(1)).executeMethod(method);
- }
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectFailure() throws CloudstackRESTException, IOException {
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- final Header header = mock(Header.class);
- when(header.getValue()).thenReturn("text/html");
- when(method.getResponseHeader("Content-Type")).thenReturn(header);
- when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
- when(method.isRequestSent()).thenReturn(true);
- try {
- connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
+ public void setField(final String field) {
+ this.field = field;
}
- }
- @Test(expected = CloudstackRESTException.class)
- public void testExecuteRetrieveObjectException() throws CloudstackRESTException, IOException {
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
- when(client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
- try {
- connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
- } finally {
- verify(method, times(1)).releaseConnection();
+ @Override
+ public int hashCode() {
+ return HashCodeBuilder.reflectionHashCode(this);
}
- }
-}
-
-class JsonEntity {
- private String displayName;
- private String uuid;
- private String href;
- private String schema;
+ @Override
+ public boolean equals(final Object obj) {
+ return EqualsBuilder.reflectionEquals(this, obj);
+ }
- public String getDisplayName() {
- return displayName;
}
- public void setDisplayName(final String displayName) {
- this.displayName = displayName;
- }
+ private final class TestPojoDeserializer implements JsonDeserializer<TestPojo> {
+ @Override
+ public TestPojo deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
+ final JsonObject jsonObject = json.getAsJsonObject();
- public String getUuid() {
- return uuid;
- }
+ if (!jsonObject.has("type")) {
+ throw new JsonParseException("Deserializing as a TestPojo, but no type present in the json object");
+ }
- public void setUuid(final String uuid) {
- this.uuid = uuid;
+ return context.deserialize(jsonObject, TestPojo.class);
+ }
}
- public String getHref() {
- return href;
- }
+ private final class CustomListDeserializer<T> implements JsonDeserializer<T> {
+ private final Gson standardGson = new GsonBuilder().create();
- public void setHref(final String href) {
- this.href = href;
- }
+ @Override
+ public T deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
+ final JsonObject jsonObject = json.getAsJsonObject();
- public String getSchema() {
- return schema;
- }
+ System.err.println(json.toString());
- public void setSchema(final String schema) {
- this.schema = schema;
+ if (jsonObject.has("results")) {
+ final JsonArray results = jsonObject.getAsJsonArray("results");
+ return context.deserialize(results, typeOfT);
+ } else {
+ return standardGson.fromJson(jsonObject, typeOfT);
+ }
+ }
}
-}
\ No newline at end of file
+}
[31/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java
deleted file mode 100644
index 36e4643..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java
+++ /dev/null
@@ -1,476 +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 com.cloud.network.guru;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyLong;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.Collections;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
-
-import com.cloud.agent.AgentManager;
-import com.cloud.agent.api.Command;
-import com.cloud.agent.api.CreateLogicalSwitchAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
-import com.cloud.dc.DataCenter;
-import com.cloud.dc.DataCenter.NetworkType;
-import com.cloud.dc.DataCenterVO;
-import com.cloud.dc.dao.DataCenterDao;
-import com.cloud.deploy.DeployDestination;
-import com.cloud.deploy.DeploymentPlan;
-import com.cloud.domain.Domain;
-import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
-import com.cloud.host.HostVO;
-import com.cloud.host.dao.HostDao;
-import com.cloud.network.Network;
-import com.cloud.network.Network.GuestType;
-import com.cloud.network.Network.Service;
-import com.cloud.network.Network.State;
-import com.cloud.network.NetworkModel;
-import com.cloud.network.NetworkProfile;
-import com.cloud.network.Networks.BroadcastDomainType;
-import com.cloud.network.Networks.TrafficType;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.network.dao.NetworkDao;
-import com.cloud.network.dao.NetworkVO;
-import com.cloud.network.dao.NiciraNvpDao;
-import com.cloud.network.dao.PhysicalNetworkDao;
-import com.cloud.network.dao.PhysicalNetworkVO;
-import com.cloud.offering.NetworkOffering;
-import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
-import com.cloud.user.Account;
-import com.cloud.vm.ReservationContext;
-
-public class NiciraNvpGuestNetworkGuruTest {
- private static final long NETWORK_ID = 42L;
- PhysicalNetworkDao physnetdao = mock(PhysicalNetworkDao.class);
- NiciraNvpDao nvpdao = mock(NiciraNvpDao.class);
- DataCenterDao dcdao = mock(DataCenterDao.class);
- NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class);
- AgentManager agentmgr = mock(AgentManager.class);
- NetworkOrchestrationService netmgr = mock(NetworkOrchestrationService.class);
- NetworkModel netmodel = mock(NetworkModel.class);
-
- HostDao hostdao = mock(HostDao.class);
- NetworkDao netdao = mock(NetworkDao.class);
- NiciraNvpGuestNetworkGuru guru;
-
- @Before
- public void setUp() {
- guru = new NiciraNvpGuestNetworkGuru();
- ((GuestNetworkGuru)guru)._physicalNetworkDao = physnetdao;
- guru.physicalNetworkDao = physnetdao;
- guru.niciraNvpDao = nvpdao;
- guru._dcDao = dcdao;
- guru.ntwkOfferingSrvcDao = nosd;
- guru.networkModel = netmodel;
- guru.hostDao = hostdao;
- guru.agentMgr = agentmgr;
- guru.networkDao = netdao;
-
- final DataCenterVO dc = mock(DataCenterVO.class);
- when(dc.getNetworkType()).thenReturn(NetworkType.Advanced);
- when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24");
-
- when(dcdao.findById((Long)any())).thenReturn(dc);
- }
-
- @Test
- public void testCanHandle() {
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true);
-
- assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
-
- // Supported: IsolationMethod == VXLAN
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VXLAN"}));
- assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
-
- // Not supported TrafficType != Guest
- when(offering.getTrafficType()).thenReturn(TrafficType.Management);
- assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
-
- // Not supported: GuestType Shared
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Shared);
- assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
-
- // Not supported: Basic networking
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
- assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true);
-
- // Not supported: IsolationMethod != STT, VXLAN
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"}));
- assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true);
-
- }
-
- @Test
- public void testDesign() {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
- when(device.getId()).thenReturn(1L);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true);
-
- final DeploymentPlan plan = mock(DeploymentPlan.class);
- final Network network = mock(Network.class);
- final Account account = mock(Account.class);
-
- final Network designednetwork = guru.design(offering, plan, network, account);
- assertTrue(designednetwork != null);
- assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch);
- }
-
- @Test
- public void testDesignNoElementOnPhysicalNetwork() {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList());
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- final DeploymentPlan plan = mock(DeploymentPlan.class);
- final Network network = mock(Network.class);
- final Account account = mock(Account.class);
-
- final Network designednetwork = guru.design(offering, plan, network, account);
- assertTrue(designednetwork == null);
- }
-
- @Test
- public void testDesignNoIsolationMethodSTT() {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList());
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- final DeploymentPlan plan = mock(DeploymentPlan.class);
- final Network network = mock(Network.class);
- final Account account = mock(Account.class);
-
- final Network designednetwork = guru.design(offering, plan, network, account);
- assertTrue(designednetwork == null);
- }
-
- @Test
- public void testDesignNoConnectivityInOffering() {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
- when(device.getId()).thenReturn(1L);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
-
- final DeploymentPlan plan = mock(DeploymentPlan.class);
- final Network network = mock(Network.class);
- final Account account = mock(Account.class);
-
- final Network designednetwork = guru.design(offering, plan, network, account);
- assertTrue(designednetwork == null);
- }
-
- @Test
- public void testImplement() throws InsufficientVirtualNetworkCapacityException {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
- when(device.getId()).thenReturn(1L);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
-
- mock(DeploymentPlan.class);
-
- final NetworkVO network = mock(NetworkVO.class);
- when(network.getName()).thenReturn("testnetwork");
- when(network.getState()).thenReturn(State.Implementing);
- when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
-
- final DeployDestination dest = mock(DeployDestination.class);
-
- final DataCenter dc = mock(DataCenter.class);
- when(dest.getDataCenter()).thenReturn(dc);
-
- final HostVO niciraHost = mock(HostVO.class);
- when(hostdao.findById(anyLong())).thenReturn(niciraHost);
- when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
- when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
- when(niciraHost.getId()).thenReturn(NETWORK_ID);
-
- when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
- final Domain dom = mock(Domain.class);
- when(dom.getName()).thenReturn("domain");
- final Account acc = mock(Account.class);
- when(acc.getAccountName()).thenReturn("accountname");
- final ReservationContext res = mock(ReservationContext.class);
- when(res.getDomain()).thenReturn(dom);
- when(res.getAccount()).thenReturn(acc);
-
- final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
- when(answer.getResult()).thenReturn(true);
- when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
- when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
-
- final Network implementednetwork = guru.implement(network, offering, dest, res);
- assertTrue(implementednetwork != null);
- verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
- }
-
- @Test
- public void testImplementWithCidr() throws InsufficientVirtualNetworkCapacityException {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
- when(device.getId()).thenReturn(1L);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
-
- mock(DeploymentPlan.class);
-
- final NetworkVO network = mock(NetworkVO.class);
- when(network.getName()).thenReturn("testnetwork");
- when(network.getState()).thenReturn(State.Implementing);
- when(network.getGateway()).thenReturn("10.1.1.1");
- when(network.getCidr()).thenReturn("10.1.1.0/24");
- when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
-
- final DeployDestination dest = mock(DeployDestination.class);
-
- final DataCenter dc = mock(DataCenter.class);
- when(dest.getDataCenter()).thenReturn(dc);
-
- final HostVO niciraHost = mock(HostVO.class);
- when(hostdao.findById(anyLong())).thenReturn(niciraHost);
- when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
- when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
- when(niciraHost.getId()).thenReturn(NETWORK_ID);
-
- when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
- final Domain dom = mock(Domain.class);
- when(dom.getName()).thenReturn("domain");
- final Account acc = mock(Account.class);
- when(acc.getAccountName()).thenReturn("accountname");
- final ReservationContext res = mock(ReservationContext.class);
- when(res.getDomain()).thenReturn(dom);
- when(res.getAccount()).thenReturn(acc);
-
- final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
- when(answer.getResult()).thenReturn(true);
- when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
- when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
-
- final Network implementednetwork = guru.implement(network, offering, dest, res);
- assertTrue(implementednetwork != null);
- assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24"));
- assertTrue(implementednetwork.getGateway().equals("10.1.1.1"));
- verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
- }
-
- @Test
- public void testImplementURIException() throws InsufficientVirtualNetworkCapacityException {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
- when(device.getId()).thenReturn(1L);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
-
- mock(DeploymentPlan.class);
-
- final NetworkVO network = mock(NetworkVO.class);
- when(network.getName()).thenReturn("testnetwork");
- when(network.getState()).thenReturn(State.Implementing);
- when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
-
- final DeployDestination dest = mock(DeployDestination.class);
-
- final DataCenter dc = mock(DataCenter.class);
- when(dest.getDataCenter()).thenReturn(dc);
-
- final HostVO niciraHost = mock(HostVO.class);
- when(hostdao.findById(anyLong())).thenReturn(niciraHost);
- when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
- when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
- when(niciraHost.getId()).thenReturn(NETWORK_ID);
-
- when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
- final Domain dom = mock(Domain.class);
- when(dom.getName()).thenReturn("domain");
- final Account acc = mock(Account.class);
- when(acc.getAccountName()).thenReturn("accountname");
- final ReservationContext res = mock(ReservationContext.class);
- when(res.getDomain()).thenReturn(dom);
- when(res.getAccount()).thenReturn(acc);
-
- final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
- when(answer.getResult()).thenReturn(true);
- //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
- when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
-
- final Network implementednetwork = guru.implement(network, offering, dest, res);
- assertTrue(implementednetwork == null);
- verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
- }
-
- @Test
- public void testShutdown() throws InsufficientVirtualNetworkCapacityException, URISyntaxException {
- final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
- when(physnetdao.findById((Long)any())).thenReturn(physnet);
- when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"}));
- when(physnet.getId()).thenReturn(NETWORK_ID);
-
- final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
- when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
- when(device.getId()).thenReturn(1L);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
-
- mock(DeploymentPlan.class);
-
- final NetworkVO network = mock(NetworkVO.class);
- when(network.getName()).thenReturn("testnetwork");
- when(network.getState()).thenReturn(State.Implementing);
- when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
- when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa"));
- when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
- when(netdao.findById(NETWORK_ID)).thenReturn(network);
-
- final DeployDestination dest = mock(DeployDestination.class);
-
- final DataCenter dc = mock(DataCenter.class);
- when(dest.getDataCenter()).thenReturn(dc);
-
- final HostVO niciraHost = mock(HostVO.class);
- when(hostdao.findById(anyLong())).thenReturn(niciraHost);
- when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
- when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
- when(niciraHost.getId()).thenReturn(NETWORK_ID);
-
- when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
- final Domain dom = mock(Domain.class);
- when(dom.getName()).thenReturn("domain");
- final Account acc = mock(Account.class);
- when(acc.getAccountName()).thenReturn("accountname");
- final ReservationContext res = mock(ReservationContext.class);
- when(res.getDomain()).thenReturn(dom);
- when(res.getAccount()).thenReturn(acc);
-
- final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class);
- when(answer.getResult()).thenReturn(true);
- when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
-
- final NetworkProfile implementednetwork = mock(NetworkProfile.class);
- when(implementednetwork.getId()).thenReturn(NETWORK_ID);
- when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa"));
- when(offering.getSpecifyVlan()).thenReturn(false);
-
- guru.shutdown(implementednetwork, offering);
- verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
- verify(implementednetwork, times(1)).setBroadcastUri(null);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java
deleted file mode 100644
index d4c6596..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java
+++ /dev/null
@@ -1,55 +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 com.cloud.network.nicira;
-
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-import com.google.gson.FieldNamingPolicy;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public class NatRuleTest {
-
- @Test
- public void testNatRuleEncoding() {
- final Gson gson =
- new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter())
- .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
- .create();
-
- final DestinationNatRule rn1 = new DestinationNatRule();
- rn1.setToDestinationIpAddress("10.10.10.10");
- rn1.setToDestinationPort(80);
- final Match mr1 = new Match();
- mr1.setSourceIpAddresses("11.11.11.11/24");
- mr1.setEthertype("IPv4");
- mr1.setProtocol(6);
- rn1.setMatch(mr1);
-
- final String jsonString = gson.toJson(rn1);
- final NatRule dnr = gson.fromJson(jsonString, NatRule.class);
-
- assertTrue(dnr instanceof DestinationNatRule);
- assertTrue(rn1.equals(dnr));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java
deleted file mode 100644
index 3bb4b9d..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java
+++ /dev/null
@@ -1,347 +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 com.cloud.network.nicira;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.UUID;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import com.cloud.utils.PropertiesUtil;
-
-public class NiciraNvpApiIT {
-
- protected NiciraNvpApi api;
-
- protected long timestamp = System.currentTimeMillis();
-
- @Before
- public void setup() throws IOException {
- final Properties properties = PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties"));
- api = new NiciraNvpApi();
- api.setControllerAddress(properties.getProperty("nvp.host"));
- api.setAdminCredentials(properties.getProperty("nvp.admin.user"),
- properties.getProperty("nvp.admin.pwd"));
- }
-
- @Test
- public void testCRUDSecurityProfile() throws NiciraNvpApiException {
- SecurityProfile sProfile = new SecurityProfile();
- sProfile.setDisplayName("SecProfile"+timestamp);
-
- final List<SecurityRule> egressRules = new ArrayList<SecurityRule>();
- sProfile.setLogicalPortEgressRules(egressRules);
- egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 80, 88, 6));
- egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "2a80:34ac::1", null, 90, 98, 6));
-
- final List<SecurityRule> ingressRules = new ArrayList<SecurityRule>();
- sProfile.setLogicalPortIngressRules(ingressRules);
- ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 50, 58, 6));
- ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "280a:3ac4::1", null, 60, 68, 6));
-
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- sProfile.setTags(tags);
- tags.add(new NiciraNvpTag("nvp", "MyTag1"));
- tags.add(new NiciraNvpTag("nicira", "MyTag2"));
- // In the creation we don't get to specify UUID, href or schema: they don't exist yet
-
- try {
- sProfile = api.createSecurityProfile(sProfile);
-
- // We can now update the new entity
- sProfile.setDisplayName("UpdatedSecProfile"+timestamp);
- api.updateSecurityProfile(sProfile, sProfile.getUuid());
-
- // Read them all
- NiciraNvpList<SecurityProfile> profiles = api.findSecurityProfile();
- SecurityProfile scInList = null;
- for(final SecurityProfile iProfile : profiles.getResults()) {
- if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) {
- scInList = iProfile;
- }
- }
- assertEquals("Read a Security Profile different from the one just created and updated",
- sProfile, scInList);
-
- // Read them filtered by uuid (get one)
- profiles = api.findSecurityProfile(sProfile.getUuid());
- assertEquals("Read a Security Profile different from the one just created and updated",
- sProfile,
- profiles.getResults().get(0));
- assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item",
- 1, profiles.getResults().size());
-
- // We can now delete the new entity
- api.deleteSecurityProfile(sProfile.getUuid());
- } catch (final NiciraNvpApiException e) {
- e.printStackTrace();
- assertTrue("Errors in Security Profile CRUD", false);
- }
- }
-
- @Test
- public void testCRUDAcl() throws NiciraNvpApiException {
- Acl acl = new Acl();
- acl.setDisplayName("Acl"+timestamp);
-
- // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type
- // Note that if the protocol is 1 (ICMP) then you cannot put ports
- final List<AclRule> egressRules = new ArrayList<AclRule>();
- acl.setLogicalPortEgressRules(egressRules);
- egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null,
- "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
- egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null,
- "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
-
- final List<AclRule> ingressRules = new ArrayList<AclRule>();
- acl.setLogicalPortIngressRules(ingressRules);
- ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null,
- "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
- ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null,
- "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
-
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- acl.setTags(tags);
- tags.add(new NiciraNvpTag("nvp", "MyTag1"));
- tags.add(new NiciraNvpTag("nicira", "MyTag2"));
- // In the creation we don't get to specify UUID, href or schema: they don't exist yet
-
- try {
- acl = api.createAcl(acl);
-
- // We can now update the new entity
- acl.setDisplayName("UpdatedAcl"+timestamp);
- api.updateAcl(acl, acl.getUuid());
-
- // Read them all
- NiciraNvpList<Acl> acls = api.findAcl();
- Acl scInList = null;
- for(final Acl iAcl : acls.getResults()) {
- if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) {
- scInList = iAcl;
- }
- }
- assertEquals("Read a ACL different from the one just created and updated",
- acl, scInList);
-
- // Read them filtered by uuid (get one)
- acls = api.findAcl(acl.getUuid());
- assertEquals("Read a ACL different from the one just created and updated",
- acl,
- acls.getResults().get(0));
- assertEquals("Read a ACL filtered by unique id (UUID) with more than one item",
- 1, acls.getResults().size());
-
- // We can now delete the new entity
- api.deleteAcl(acl.getUuid());
- } catch (final NiciraNvpApiException e) {
- e.printStackTrace();
- assertTrue("Errors in ACL CRUD", false);
- }
- }
-
- @Test
- public void testCRUDLogicalSwitch() throws NiciraNvpApiException {
- LogicalSwitch logicalSwitch = new LogicalSwitch();
- logicalSwitch.setDisplayName("LogicalSwitch"+timestamp);
- logicalSwitch.setPortIsolationEnabled(true);
- logicalSwitch.setReplicationMode("service");
- logicalSwitch.setTags(new ArrayList<NiciraNvpTag>());
- logicalSwitch.getTags().add(new NiciraNvpTag("anto", "hugo"));
-
- // In the creation we don't get to specify UUID, href or schema: they don't exist yet
-
- try {
- logicalSwitch = api.createLogicalSwitch(logicalSwitch);
-
- // We can now update the new entity
- logicalSwitch.setDisplayName("UpdatedLogicalSwitch"+timestamp);
- api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid());
-
- // Read them all
- NiciraNvpList<LogicalSwitch> logicalSwitches = api.findLogicalSwitch();
- for(final LogicalSwitch iLogicalSwitch : logicalSwitches.getResults()) {
- if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) {
- assertEquals("Read a LogicalSwitch different from the one just created and updated",
- logicalSwitch, iLogicalSwitch);
- }
- }
-
- // Read them filtered by uuid (get one)
- logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid());
- assertEquals("Read a LogicalSwitch different from the one just created and updated",
- logicalSwitch,
- logicalSwitches.getResults().get(0));
- assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item",
- 1, logicalSwitches.getResults().size());
-
- // Before deleting the test LogicalSwitch, test its ports
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
-
- LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort"+timestamp, tags, true);
- logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
-
- logicalSwitchPort.setDisplayName("UpdatedLSwitchPort"+timestamp);
- api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
-
- final NiciraNvpList<LogicalSwitchPort> logicalSwitchePorts =
- api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
- for(final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts.getResults()) {
- if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) {
- assertEquals("Read a LogicalSwitchPort different from the one just created and updated",
- logicalSwitchPort, iLSwitchPort);
- }
- }
-
- // And finally test attachments
- final String attachmentUuid = UUID.randomUUID().toString();
- final VifAttachment vifAttachment = new VifAttachment(attachmentUuid);
- api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(),
- vifAttachment);
-
- assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
- api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()),
- logicalSwitchPort.getUuid());
-
- api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
-
- // We can now delete the new entity
- api.deleteLogicalSwitch(logicalSwitch.getUuid());
- } catch (final NiciraNvpApiException e) {
- e.printStackTrace();
- assertTrue("Errors in LogicalSwitch CRUD", false);
- }
- }
-
- @Test
- public void testCRUDLogicalRouter() throws NiciraNvpApiException {
- LogicalRouter logicalRouter = new LogicalRouter();
- logicalRouter.setDisplayName("LogicalRouter"+timestamp);
- logicalRouter.setDistributed(true);
- logicalRouter.setNatSynchronizationEnabled(true);
- logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE);
- final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig(
- new RouterNextHop("192.168.10.20"));
- logicalRouter.setRoutingConfig(routingConfig);
-
- // In the creation we don't get to specify UUID, href or schema: they don't exist yet
-
- try {
- logicalRouter = api.createLogicalRouter(logicalRouter);
-
- // We can now update the new entity
- logicalRouter.setDisplayName("UpdatedLogicalSwitch"+timestamp);
- api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid());
-
- // Read them all
- NiciraNvpList<LogicalRouter> logicalRouters = api.findLogicalRouter();
- LogicalRouter lsInList = null;
- for(final LogicalRouter iLogicalRouter : logicalRouters.getResults()) {
- if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) {
- lsInList = iLogicalRouter;
- }
- }
- assertEquals("Read a LogicalRouter different from the one just created and updated",
- logicalRouter, lsInList);
-
- // Read them filtered by uuid (get one)
- logicalRouters = api.findLogicalRouter(logicalRouter.getUuid());
- assertEquals("Read a LogicalRouter different from the one just created and updated",
- logicalRouter,
- logicalRouters.getResults().get(0));
- assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item",
- 1, logicalRouters.getResults().size());
-
- assertEquals("", logicalRouters.getResults().get(0),
- api.findOneLogicalRouterByUuid(logicalRouter.getUuid()));
-
- // Before deleting the test LogicalRouter, test its ports
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
-
- LogicalRouterPort logicalRouterPort = new LogicalRouterPort();
- logicalRouterPort.setDisplayName("LRouterPort"+timestamp);
- logicalRouterPort.setTags(tags);
- logicalRouterPort.setAdminStatusEnabled(true);
- logicalRouterPort.setPortno(1024);
- logicalRouterPort.setMacAddress("00:00:00:00:00:00");
-
- final List<String> ipAddresses = new ArrayList<String>();
- // Add some ips to this list
- logicalRouterPort.setIpAddresses(ipAddresses);
- logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
-
- logicalRouterPort.setDisplayName("UpdatedLRouterPort"+timestamp);
- api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
-
- final NiciraNvpList<LogicalRouterPort> logicalRouterePorts =
- api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid());
- for(final LogicalRouterPort iLRouterPort : logicalRouterePorts.getResults()) {
- if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) {
- assertEquals("Read a LogicalRouterPort different from the one just created and updated",
- logicalRouterPort, iLRouterPort);
- }
- }
-
- UUID.randomUUID().toString();
-
- // Test CRUD for Nat Rules
- SourceNatRule snr = new SourceNatRule();
- snr.setToSourceIpAddressMin("192.168.10.10");
- snr.setToSourceIpAddressMax("192.168.10.20");
- snr.setOrder(200);
- final Match match = new Match();
- match.setSourceIpAddresses("192.168.150.150");
- snr.setMatch(match);
- snr = (SourceNatRule) api.createLogicalRouterNatRule(logicalRouter.getUuid(), snr);
- snr.setToSourceIpAddressMax("192.168.10.30");
- api.updateLogicalRouterNatRule(logicalRouter.getUuid(), snr);
-
- api.findNatRulesByLogicalRouterUuid(logicalRouter.getUuid());
- api.deleteLogicalRouterNatRule(logicalRouter.getUuid(), snr.getUuid());
-
- api.deleteLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort.getUuid());
-
- // We can now delete the new entity
- api.deleteLogicalRouter(logicalRouter.getUuid());
- } catch (final NiciraNvpApiException e) {
- e.printStackTrace();
- assertTrue("Errors in LogicalRouter CRUD", false);
- }
- }
-
- @Test
- public void testGetControlClusterStatus() throws NiciraNvpApiException {
- final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus();
- final String clusterStatus = controlClusterStatus.getClusterStatus();
- final boolean correctStatus = (clusterStatus.equalsIgnoreCase("stable") ||
- clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"));
- assertTrue("Not recognizable cluster status", correctStatus);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java
deleted file mode 100644
index 1435cc5..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java
+++ /dev/null
@@ -1,339 +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 com.cloud.network.nicira;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Matchers.any;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.params.HttpClientParams;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonParseException;
-import com.cloud.utils.rest.RESTServiceConnector;
-import com.cloud.utils.rest.RESTValidationStrategy;
-
-public class NiciraNvpApiTest {
- protected static final String UUID = "aaaa";
- protected static final String UUID2 = "bbbb";
- protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa";
- protected static final String SCHEMA = "myTestSchema";
- protected static final String SCHEMA2 = "myTestSchema2";
- protected static final String HREF = "myTestHref";
- protected static final String HREF2 = "myTestHref2";
- protected static final String SEC_PROFILE_JSON_RESPONSE =
- "{\"uuid\" : \"aaaa\","
- + "\"display_name\" : \"myTestName\","
- + "\"href\" : \"myTestHref\","
- + "\"schema\" : \"myTestSchema\"}";
-
- protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\","
- + "\"display_name\" : \"myTestName\","
- + "\"href\" : \"myTestHref\","
- + "\"schema\" : \"myTestSchema\"},"
- + "{ \"uuid\" : \"bbbb\","
- + "\"display_name\" : \"myTestName2\","
- + "\"href\" : \"myTestHref2\","
- + "\"schema\" : \"myTestSchema2\"}],"
- + "\"result_count\": 2}";
-
- NiciraNvpApi api;
- HttpClient client = mock(HttpClient.class);
- HttpMethod method;
- String type;
- String uri;
-
- @Before
- public void setUp() {
- final HttpClientParams hmp = mock(HttpClientParams.class);
- when(client.getParams()).thenReturn(hmp);
- api = new NiciraNvpApi();
-
- api.restConnector = new RESTServiceConnector(new RESTValidationStrategy()) {
- @Override
- public HttpClient createHttpClient() {
- return client;
- }
-
- @Override
- public HttpMethod createMethod(final String newType, final String newUri) {
- type = newType;
- uri = newUri;
- return method;
- }
- };
-
- api.setAdminCredentials("admin", "adminpass");
- api.setControllerAddress("localhost");
- }
-
- @Test
- public void testFindSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
- final NameValuePair[] queryString = new NameValuePair[]{
- new NameValuePair("fields","*")};
-
- // Execute
- final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile();
-
- // Assert
- verify(method, times(1)).releaseConnection();
- verify(method, times(1)).setQueryString(queryString);
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID, actualProfiles.getResults().get(0).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF, actualProfiles.getResults().get(0).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA, actualProfiles.getResults().get(0).getSchema());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID2, actualProfiles.getResults().get(1).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF2, actualProfiles.getResults().get(1).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA2, actualProfiles.getResults().get(1).getSchema());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- 2, actualProfiles.getResultCount());
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.GET_METHOD_TYPE, type);
- }
-
- @Test
- public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException {
- // Prepare
- method = mock(GetMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
- when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
- final NameValuePair[] queryString = new NameValuePair[]{
- new NameValuePair("uuid", UUID),
- new NameValuePair("fields","*")
- };
- final List<NameValuePair> queryStringNvps = new ArrayList<>();
- doAnswer(new Answer<Void>() {
-
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- final NameValuePair[] arguments = (NameValuePair[]) invocation.getArguments()[0];
- queryStringNvps.addAll(Arrays.asList(arguments));
- return null;
- }}).when(method).setQueryString(any(NameValuePair[].class));
-
- // Execute
- final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertTrue(queryStringNvps.containsAll(Arrays.asList(queryString)));
- assertEquals(queryString.length, queryStringNvps.size());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID, actualProfiles.getResults().get(0).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF, actualProfiles.getResults().get(0).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA, actualProfiles.getResults().get(0).getSchema());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID2, actualProfiles.getResults().get(1).getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF2, actualProfiles.getResults().get(1).getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA2, actualProfiles.getResults().get(1).getSchema());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- 2, actualProfiles.getResultCount());
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
- assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
- NiciraNvpApi.GET_METHOD_TYPE, type);
- }
-
- @Test
- public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- final SecurityProfile inputSecProfile = new SecurityProfile();
- method = mock(PostMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
- when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE);
-
- // Execute
- final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- UUID, actualSecProfile.getUuid());
- assertEquals("Wrong Uuid in the newly created SecurityProfile",
- HREF, actualSecProfile.getHref());
- assertEquals("Wrong Schema in the newly created SecurityProfile",
- SCHEMA, actualSecProfile.getSchema());
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
- assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
- NiciraNvpApi.POST_METHOD_TYPE, type);
- }
-
- @Test
- public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- final SecurityProfile inputSecProfile = new SecurityProfile();
- method = mock(PutMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
-
- // Execute
- api.updateSecurityProfile(inputSecProfile, UUID);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertEquals("Wrong URI for SecurityProfile creation REST service",
- UUID_SEC_PROFILE_URI, uri);
- assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
- NiciraNvpApi.PUT_METHOD_TYPE, type);
- }
-
- @Test
- public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException {
- // Prepare
- method = mock(DeleteMethod.class);
- when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
-
- // Execute
- api.deleteSecurityProfile(UUID);
-
- // Assert
- verify(method, times(1)).releaseConnection();
- assertEquals("Wrong URI for SecurityProfile deletion REST service", UUID_SEC_PROFILE_URI, uri);
- assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", NiciraNvpApi.DELETE_METHOD_TYPE, type);
- }
-
- @Test(expected = JsonParseException.class)
- public void testRoutingConfigAdapterNoType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{}", RoutingConfig.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test(expected = JsonParseException.class)
- public void testRoutingConfigAdapterWrongType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test()
- public void testRoutingConfigAdapter() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig =
- (SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class);
-
- // Assert: JsonParseException should be thrown
- assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass());
- }
-
- @Test(expected = JsonParseException.class)
- public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test(expected = JsonParseException.class)
- public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- gson.fromJson("{type : \"WrongType\"}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- }
-
- @Test()
- public void testRoutingConfigAdapterWithSourceNatRule() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- final SourceNatRule sourceNatRule =
- (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- assertEquals("", SourceNatRule.class, sourceNatRule.getClass());
- }
-
- @Test()
- public void testRoutingConfigAdapterWithDestinationNatRule() throws NiciraNvpApiException, IOException {
- // Prepare
- final NiciraNvpApi api = new NiciraNvpApi();
- final Gson gson = api.restConnector.getGson();
-
- // Execute
- final DestinationNatRule destinationNatRule =
- (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class);
-
- // Assert: JsonParseException should be thrown
- assertEquals("", DestinationNatRule.class, destinationNatRule.getClass());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java
deleted file mode 100644
index 7a31264..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java
+++ /dev/null
@@ -1,58 +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 com.cloud.network.nicira;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class NiciraTagTest {
- @Test
- public void testCreateTag() {
- final NiciraNvpTag tag = new NiciraNvpTag("scope", "tag");
- assertEquals("scope part set", "scope", tag.getScope());
- assertEquals("tag part set", "tag", tag.getTag());
- }
-
- @Test
- public void testCreateLongTag() {
- final NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght");
- assertEquals("scope part set", "scope", tag.getScope());
- assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag());
- }
-
- @Test
- public void testSetTag() {
- final NiciraNvpTag tag = new NiciraNvpTag();
- tag.setScope("scope");
- tag.setTag("tag");
- assertEquals("scope part set", "scope", tag.getScope());
- assertEquals("tag part set", "tag", tag.getTag());
- }
-
- @Test
- public void testSetLongTag() {
- final NiciraNvpTag tag = new NiciraNvpTag();
- tag.setScope("scope");
- tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght");
- assertEquals("scope part set", "scope", tag.getScope());
- assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag());
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
deleted file mode 100644
index 7fe6287..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ /dev/null
@@ -1,255 +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 com.cloud.network.resource;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalSwitchCommand;
-import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
-import com.cloud.agent.api.MaintainCommand;
-import com.cloud.agent.api.ReadyCommand;
-import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
-import com.cloud.network.nicira.LogicalRouterPort;
-import com.cloud.network.nicira.LogicalSwitch;
-import com.cloud.network.nicira.NiciraNvpApi;
-import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.nicira.VifAttachment;
-
-public class NiciraNvpRequestWrapperTest {
-
- @Mock
- private final NiciraNvpResource niciraNvpResource = Mockito.mock(NiciraNvpResource.class);
-
- @Test
- public void testReadyCommandWrapper() {
- final ReadyCommand command = new ReadyCommand();
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testMaintainCommandWrapper() {
- final MaintainCommand command = new MaintainCommand();
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testCreateLogicalSwitchCommandWrapper() {
- final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
- final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class);
- final LogicalSwitch logicalSwitch = Mockito.mock(LogicalSwitch.class);
-
- final String transportUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String transportType = "stt";
- final String name = "logicalswitch";
- final String ownerName = "owner";
-
- final CreateLogicalSwitchCommand command = new CreateLogicalSwitchCommand(transportUuid, transportType, name, ownerName);
-
- final String truncated = "lswitch-" + command.getName();
-
- when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities);
- when(niciraNvpUtilities.createLogicalSwitch()).thenReturn(logicalSwitch);
- when(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN)).thenReturn(truncated);
- when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
-
- try {
- when(niciraNvpApi.createLogicalSwitch(logicalSwitch)).thenReturn(logicalSwitch);
- when(logicalSwitch.getUuid()).thenReturn(transportUuid);
- } catch (final NiciraNvpApiException e) {
- fail(e.getMessage());
- }
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testDeleteLogicalSwitchCommandWrapper() {
- final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
-
- final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
-
- final DeleteLogicalSwitchCommand command = new DeleteLogicalSwitchCommand(logicalSwitchUuid);
-
- when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
-
- try {
- doNothing().when(niciraNvpApi).deleteLogicalSwitch(command.getLogicalSwitchUuid());
- } catch (final NiciraNvpApiException e) {
- fail(e.getMessage());
- }
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testConfigurePublicIpsOnLogicalRouterCommand() {
- final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
- final LogicalRouterPort port1 = Mockito.mock(LogicalRouterPort.class);
-
- final List<LogicalRouterPort> listPorts = new ArrayList<LogicalRouterPort>();
- listPorts.add(port1);
-
- final NiciraNvpList<LogicalRouterPort> ports = new NiciraNvpList<LogicalRouterPort>();
- ports.setResults(listPorts);
- ports.setResultCount(1);
-
- final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final List<String> publicCidrs = new ArrayList<String>();
- publicCidrs.add("10.1.1.0/24");
-
- final ConfigurePublicIpsOnLogicalRouterCommand command = new ConfigurePublicIpsOnLogicalRouterCommand(logicalRouterUuid, l3GatewayServiceUuid, publicCidrs);
-
- when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
-
- try {
- when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(ports);
- doNothing().when(niciraNvpApi).updateLogicalRouterPort(command.getLogicalRouterUuid(), port1);
- } catch (final NiciraNvpApiException e) {
- fail(e.getMessage());
- }
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testDeleteLogicalSwitchPortCommand() {
- final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
-
- final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
-
- final DeleteLogicalSwitchPortCommand command = new DeleteLogicalSwitchPortCommand(logicalSwitchUuid, logicalSwitchPortUuid);
-
- when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
-
- try {
- doNothing().when(niciraNvpApi).deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid());
- } catch (final NiciraNvpApiException e) {
- fail(e.getMessage());
- }
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testDeleteLogicalRouterCommand() {
- final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
-
- final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
-
- final DeleteLogicalRouterCommand command = new DeleteLogicalRouterCommand(logicalRouterUuid);
-
- when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
-
- try {
- doNothing().when(niciraNvpApi).deleteLogicalRouter(command.getLogicalRouterUuid());
- } catch (final NiciraNvpApiException e) {
- fail(e.getMessage());
- }
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-
- @Test
- public void testUpdateLogicalSwitchPortCommand() {
- final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
- final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class);
- final VifAttachment vifAttachment = Mockito.mock(VifAttachment.class);
-
- final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String attachmentUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
- final String ownerName = "admin";
- final String nicName = "eth0";
-
- final UpdateLogicalSwitchPortCommand command = new UpdateLogicalSwitchPortCommand(logicalSwitchPortUuid, logicalSwitchUuid, attachmentUuid, ownerName, nicName);
-
- when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities);
- when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
-
- try {
- when(niciraNvpUtilities.createVifAttachment(attachmentUuid)).thenReturn(vifAttachment);
- doNothing().when(niciraNvpApi).updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment);
- } catch (final NiciraNvpApiException e) {
- fail(e.getMessage());
- }
-
- final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
- assertNotNull(wrapper);
-
- final Answer answer = wrapper.execute(command, niciraNvpResource);
-
- assertTrue(answer.getResult());
- }
-}
\ No newline at end of file
[07/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Add Marvin test for Nicira NVP plugin
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/98dd7717
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/98dd7717
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/98dd7717
Branch: refs/heads/deploy-from-snapshot
Commit: 98dd7717026d3da6c034140fbadb06eb88eaf41d
Parents: abb824e
Author: Miguel Ferreira <mi...@me.com>
Authored: Fri Aug 21 17:39:02 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 14:50:30 2015 +0200
----------------------------------------------------------------------
.../integration/smoke/test_nicira_controller.py | 310 +++++++++++++++++++
tools/marvin/marvin/cloudstackTestCase.py | 4 +
tools/marvin/marvin/lib/base.py | 46 +++
3 files changed, 360 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/98dd7717/test/integration/smoke/test_nicira_controller.py
----------------------------------------------------------------------
diff --git a/test/integration/smoke/test_nicira_controller.py b/test/integration/smoke/test_nicira_controller.py
new file mode 100644
index 0000000..229612d
--- /dev/null
+++ b/test/integration/smoke/test_nicira_controller.py
@@ -0,0 +1,310 @@
+#!/usr/bin/env python
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import requests
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.lib.utils import cleanup_resources
+from marvin.lib.base import (
+ PhysicalNetwork,
+ NetworkOffering,
+ NiciraNvp,
+ ServiceOffering,
+ Network,
+ VirtualMachine
+)
+from marvin.lib.common import (get_domain, get_zone, get_template)
+from nose.plugins.attrib import attr
+from marvin.codes import (FAILED, PASS)
+import time
+
+class TestNiciraContoller(cloudstackTestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ test_case = super(TestNiciraContoller, cls)
+
+ test_client = test_case.getClsTestClient()
+ cls.config = test_case.getClsConfig()
+ cls.api_client = test_client.getApiClient()
+
+ cls.physical_networks = cls.config.zones[0].physical_networks
+ cls.nicira_hosts = cls.config.niciraNvp.hosts
+
+ cls.physical_network_id = cls.get_nicira_enabled_physical_network_id(cls.physical_networks)
+
+ cls.network_offerring_services = {
+ 'name': 'NiciraEnabledNetwork',
+ 'displaytext': 'NiciraEnabledNetwork',
+ 'guestiptype': 'Isolated',
+ 'supportedservices': 'SourceNat,Firewall,PortForwarding,Connectivity',
+ 'traffictype': 'GUEST',
+ 'availability': 'Optional',
+ 'serviceProviderList': {
+ 'SourceNat': 'VirtualRouter',
+ 'Firewall': 'VirtualRouter',
+ 'PortForwarding': 'VirtualRouter',
+ 'Connectivity': 'NiciraNvp'
+ }
+ }
+
+ cls.network_offering = NetworkOffering.create(cls.api_client, cls.network_offerring_services)
+ cls.network_offering.update(cls.api_client, state='Enabled')
+
+ cls.nicira_credentials = {
+ 'username': 'admin',
+ 'password': 'admin'
+ }
+
+ cls.nicira_master_controller = cls.determine_master_controller(
+ cls.nicira_hosts,
+ cls.nicira_credentials
+ )
+
+ cls.transport_zone_uuid = cls.get_transport_zone_from_controller(
+ cls.nicira_master_controller,
+ cls.nicira_credentials
+ )
+
+ cls.domain = get_domain(cls.api_client)
+ cls.zone = get_zone(cls.api_client, test_client.getZoneForTests())
+
+ template = get_template(
+ cls.api_client,
+ cls.zone.id
+ )
+ if template == FAILED:
+ raise Exception("get_template() failed to return template with description %s" % cls.services['ostype'])
+
+ cls.vm_services = {
+ 'mode': cls.zone.networktype,
+ 'small': {
+ 'zoneid': cls.zone.id,
+ 'template': template.id,
+ 'displayname': 'testserver',
+ 'username': cls.config.zones[0].pods[0].clusters[0].hosts[0].username,
+ 'password': cls.config.zones[0].pods[0].clusters[0].hosts[0].password,
+ 'ssh_port': 22,
+ 'hypervisor': cls.config.zones[0].pods[0].clusters[0].hypervisor,
+ 'privateport': 22,
+ 'publicport': 22,
+ 'protocol': 'TCP',
+ },
+ 'service_offerings': {
+ 'tiny': {
+ 'name': 'Tiny Instance',
+ 'displaytext': 'Tiny Instance',
+ 'cpunumber': 1,
+ 'cpuspeed': 100,
+ 'memory': 64,
+ }
+ }
+ }
+
+ if cls.zone.localstorageenabled == True:
+ cls.vm_services['service_offerings']['tiny']['storagetype'] = 'local'
+
+ cls.service_offering = ServiceOffering.create(
+ cls.api_client,
+ cls.vm_services['service_offerings']['tiny']
+ )
+
+ cls.cleanup = [
+ cls.network_offering,
+ cls.service_offering
+ ]
+
+
+ @classmethod
+ def tearDownClass(cls):
+ try:
+ cleanup_resources(cls.api_client, reversed(cls.cleanup))
+ except Exception as e:
+ raise Exception("Warning: Exception during class cleanup : %s" % e)
+
+ def setUp(self):
+ self.test_cleanup = []
+
+ def tearDown(self):
+ try:
+ cleanup_resources(self.api_client, reversed(self.test_cleanup))
+ except Exception as e:
+ raise Exception("Warning: Exception during test cleanup : %s" % e)
+
+
+ @classmethod
+ def determine_master_controller(cls, hosts, credentials):
+ for host in hosts:
+ r1 = requests.post("https://%s/ws.v1/login" % host, credentials, verify=False)
+ r2 = requests.get("https://%s/ws.v1/control-cluster/status" % host, verify=False, cookies=r1.cookies)
+ status_code = r2.status_code
+ if status_code == 401:
+ continue
+ elif status_code == 200:
+ return host
+ raise Exception("None of the supplied hosts (%s) is a Nicira controller" % hosts)
+
+
+ @classmethod
+ def get_transport_zone_from_controller(cls, controller_host, credentials):
+ r1 = requests.post("https://%s/ws.v1/login" % controller_host, credentials, verify=False)
+ r2 = requests.get("https://%s/ws.v1/transport-zone" % controller_host, verify=False, cookies=r1.cookies)
+ status_code = r2.status_code
+ if status_code == 200:
+ list_transport_zone_response = r2.json()
+ result_count = list_transport_zone_response['result_count']
+ if result_count == 0:
+ raise Exception('Nicira controller did not return any Transport Zones')
+ elif result_count > 1:
+ self.debug("Nicira controller returned %s Transport Zones, picking first one" % resultCount)
+ transport_zone_api_url = list_transport_zone_response['results'][0]['_href']
+ r3 = requests.get(
+ "https://%s%s" % (controller_host, transport_zone_api_url),
+ verify=False,
+ cookies=r1.cookies
+ )
+ return r3.json()['uuid']
+ else:
+ raise Exception("Unexpected response from Nicira controller. Status code = %s, content = %s" % status_code)
+
+
+ @classmethod
+ def get_nicira_enabled_physical_network_id(cls, physical_networks):
+ nicira_physical_network_name = None
+ for physical_network in physical_networks:
+ for provider in physical_network.providers:
+ if provider.name == 'NiciraNvp':
+ nicira_physical_network_name = physical_network.name
+ if nicira_physical_network_name is None:
+ raise Exception('Did not find a Nicira enabled physical network in configuration')
+ return PhysicalNetwork.list(cls.api_client, name=nicira_physical_network_name)[0].id
+
+
+ def determine_slave_conroller(self, hosts, master_controller):
+ slaves = [ s for s in hosts if s != master_controller ]
+ if len(slaves) > 0:
+ return slaves[0]
+ else:
+ raise Exception("None of the supplied hosts (%s) is a Nicira slave" % hosts)
+
+ @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true")
+ def test_01_nicira_controller(self):
+ nicira_device = NiciraNvp.add(
+ self.api_client,
+ None,
+ self.physical_network_id,
+ hostname=self.nicira_master_controller,
+ username=self.nicira_credentials['username'],
+ password=self.nicira_credentials['password'],
+ transportzoneuuid=self.transport_zone_uuid)
+ self.test_cleanup.append(nicira_device)
+
+ network_services = {
+ 'name' : 'nicira_enabled_network',
+ 'displaytext' : 'nicira_enabled_network',
+ 'zoneid' : self.zone.id,
+ 'networkoffering' : self.network_offering.id
+ }
+ network = Network.create(
+ self.api_client,
+ network_services,
+ accountid='admin',
+ domainid=self.domain.id,
+ )
+ self.test_cleanup.append(network)
+
+ virtual_machine = VirtualMachine.create(
+ self.api_client,
+ self.vm_services['small'],
+ accountid='admin',
+ domainid=self.domain.id,
+ serviceofferingid=self.service_offering.id,
+ networkids=[network.id],
+ mode=self.vm_services['mode']
+ )
+ self.test_cleanup.append(virtual_machine)
+
+ list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id)
+ self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id)
+
+ self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list')
+ self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty')
+
+ vm_response = list_vm_response[0]
+ self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request')
+ self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state')
+
+ @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true")
+ def test_02_nicira_controller_redirect(self):
+ """
+ Nicira clusters will redirect clients (in this case ACS) to the master node.
+ This test assumes that a Nicira cluster is present and configured properly, and
+ that it has at least two controller nodes. The test will check that ASC follows
+ redirects by:
+ - adding a Nicira Nvp device that points to one of the cluster's slave controllers,
+ - create a VM in a Nicira backed network
+ If all is well, no matter what controller is specified (slaves or master), the vm (and respective router VM)
+ should be created without issues.
+ """
+ nicira_slave = self.determine_slave_conroller(self.nicira_hosts, self.nicira_master_controller)
+ self.debug("Nicira slave controller is: %s " % nicira_slave)
+
+ nicira_device = NiciraNvp.add(
+ self.api_client,
+ None,
+ self.physical_network_id,
+ hostname=nicira_slave,
+ username=self.nicira_credentials['username'],
+ password=self.nicira_credentials['password'],
+ transportzoneuuid=self.transport_zone_uuid)
+ self.test_cleanup.append(nicira_device)
+
+ network_services = {
+ 'name' : 'nicira_enabled_network',
+ 'displaytext' : 'nicira_enabled_network',
+ 'zoneid' : self.zone.id,
+ 'networkoffering' : self.network_offering.id
+ }
+ network = Network.create(
+ self.api_client,
+ network_services,
+ accountid='admin',
+ domainid=self.domain.id,
+ )
+ self.test_cleanup.append(network)
+
+ virtual_machine = VirtualMachine.create(
+ self.api_client,
+ self.vm_services['small'],
+ accountid='admin',
+ domainid=self.domain.id,
+ serviceofferingid=self.service_offering.id,
+ networkids=[network.id],
+ mode=self.vm_services['mode']
+ )
+ self.test_cleanup.append(virtual_machine)
+
+ list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id)
+ self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id)
+
+ self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list')
+ self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty')
+
+ vm_response = list_vm_response[0]
+ self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request')
+ self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state')
+
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/98dd7717/tools/marvin/marvin/cloudstackTestCase.py
----------------------------------------------------------------------
diff --git a/tools/marvin/marvin/cloudstackTestCase.py b/tools/marvin/marvin/cloudstackTestCase.py
index 5cb4a10..692e817 100644
--- a/tools/marvin/marvin/cloudstackTestCase.py
+++ b/tools/marvin/marvin/cloudstackTestCase.py
@@ -52,3 +52,7 @@ class cloudstackTestCase(unittest.case.TestCase):
@classmethod
def getClsTestClient(cls):
return cls.clstestclient
+
+ @classmethod
+ def getClsConfig(cls):
+ return cls.config
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/98dd7717/tools/marvin/marvin/lib/base.py
----------------------------------------------------------------------
diff --git a/tools/marvin/marvin/lib/base.py b/tools/marvin/marvin/lib/base.py
index aca7fd1..54922c8 100755
--- a/tools/marvin/marvin/lib/base.py
+++ b/tools/marvin/marvin/lib/base.py
@@ -3834,6 +3834,52 @@ class NetScaler:
cmd.listall = True
return(apiclient.listNetscalerLoadBalancers(cmd))
+class NiciraNvp:
+
+ def __init__(self, items):
+ self.__dict__.update(items)
+
+ @classmethod
+ def add(cls, apiclient, services, physicalnetworkid,
+ hostname=None, username=None, password=None, transportzoneuuid=None):
+ cmd = addNiciraNvpDevice.addNiciraNvpDeviceCmd()
+ cmd.physicalnetworkid = physicalnetworkid
+ if hostname:
+ cmd.hostname = hostname
+ else:
+ cmd.hostname = services['hostname']
+
+ if username:
+ cmd.username = username
+ else:
+ cmd.username = services['username']
+
+ if password:
+ cmd.password = password
+ else:
+ cmd.password = services['password']
+
+ if transportzoneuuid:
+ cmd.transportzoneuuid = transportzoneuuid
+ else:
+ cmd.transportzoneuuid = services['transportZoneUuid']
+
+ return NiciraNvp(apiclient.addNiciraNvpDevice(cmd).__dict__)
+
+ def delete(self, apiclient):
+ cmd = deleteNiciraNvpDevice.deleteNiciraNvpDeviceCmd()
+ cmd.nvpdeviceid = self.nvpdeviceid
+ apiclient.deleteNiciraNvpDevice(cmd)
+ return
+
+ @classmethod
+ def list(cls, apiclient, **kwargs):
+ cmd = listNiciraNvpDevices.listNiciraNvpDevicesCmd()
+ [setattr(cmd, k, v) for k, v in kwargs.items()]
+ if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
+ cmd.listall = True
+ return(apiclient.listNiciraNvpDevices(cmd))
+
class NetworkServiceProvider:
"""Manage network serivce providers for CloudStack"""
[21/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/security/CertificateHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/security/CertificateHelper.java b/utils/src/com/cloud/utils/security/CertificateHelper.java
deleted file mode 100644
index d43542f..0000000
--- a/utils/src/com/cloud/utils/security/CertificateHelper.java
+++ /dev/null
@@ -1,166 +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 com.cloud.utils.security;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.StringReader;
-import java.security.Key;
-import java.security.KeyFactory;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-import org.apache.commons.codec.binary.Base64;
-
-import com.cloud.utils.Ternary;
-import org.bouncycastle.openssl.PEMReader;
-
-public class CertificateHelper {
- public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
- NoSuchAlgorithmException, InvalidKeySpecException, IOException {
- KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword);
-
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
- os.close();
- return os.toByteArray();
- }
-
- public static byte[] buildAndSaveKeystore(List<Ternary<String, String, String>> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException,
- CertificateException, IOException, InvalidKeySpecException {
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
-
- //name,cert,key
- for (Ternary<String, String, String> cert : certs) {
- if (cert.third() == null) {
- Certificate c = buildCertificate(cert.second());
- ks.setCertificateEntry(cert.first(), c);
- } else {
- Certificate[] c = new Certificate[certs.size()];
- int i = certs.size();
- for (Ternary<String, String, String> ct : certs) {
- c[i - 1] = buildCertificate(ct.second());
- i--;
- }
- ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c);
- }
- }
-
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
- os.close();
- return os.toByteArray();
- }
-
- public static KeyStore loadKeystore(byte[] ksData, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
- assert (ksData != null);
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(new ByteArrayInputStream(ksData), storePassword != null ? storePassword.toCharArray() : null);
-
- return ks;
- }
-
- public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
- NoSuchAlgorithmException, InvalidKeySpecException, IOException {
-
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
- Certificate[] certs = new Certificate[1];
- certs[0] = buildCertificate(cert);
- ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs);
- return ks;
- }
-
- public static Certificate buildCertificate(String content) throws CertificateException {
- assert (content != null);
-
- BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes()));
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- return cf.generateCertificate(bis);
- }
-
- public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedKeyContent));
- return kf.generatePrivate(keysp);
- }
-
- public static 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");
-
- return certs;
- }
-
- public static 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 CloudRuntimeException("Bad certificate encoding");
- } catch (NoSuchAlgorithmException e) {
- throw new CloudRuntimeException("Bad certificate algorithm");
- }
-
- return buffer.toString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java b/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java
deleted file mode 100644
index e35a3ea..0000000
--- a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java
+++ /dev/null
@@ -1,179 +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 com.cloud.utils.ssh;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.log4j.Logger;
-
-import com.trilead.ssh2.ChannelCondition;
-import com.trilead.ssh2.Session;
-
-public class SSHCmdHelper {
- private static final Logger s_logger = Logger.getLogger(SSHCmdHelper.class);
-
- public static com.trilead.ssh2.Connection acquireAuthorizedConnection(String ip, String username, String password) {
- return acquireAuthorizedConnection(ip, 22, username, password);
- }
-
- public static com.trilead.ssh2.Connection acquireAuthorizedConnection(String ip, int port, String username, String password) {
- com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(ip, port);
- try {
- sshConnection.connect(null, 60000, 60000);
- if (!sshConnection.authenticateWithPassword(username, password)) {
- String[] methods = sshConnection.getRemainingAuthMethods(username);
- StringBuffer mStr = new StringBuffer();
- for (int i = 0; i < methods.length; i++) {
- mStr.append(methods[i]);
- }
- s_logger.warn("SSH authorizes failed, support authorized methods are " + mStr);
- return null;
- }
- return sshConnection;
- } catch (IOException e) {
- s_logger.warn("Get SSH connection failed", e);
- return null;
- }
- }
-
- public static void releaseSshConnection(com.trilead.ssh2.Connection sshConnection) {
- if (sshConnection != null) {
- sshConnection.close();
- }
- }
-
- public static boolean sshExecuteCmd(com.trilead.ssh2.Connection sshConnection, String cmd, int nTimes) {
- for (int i = 0; i < nTimes; i++) {
- try {
- if (sshExecuteCmdOneShot(sshConnection, cmd))
- return true;
- } catch (SshException e) {
- continue;
- }
- }
- return false;
- }
-
- public static int sshExecuteCmdWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) {
- return sshExecuteCmdWithExitCode(sshConnection, cmd, 3);
- }
-
- public static int sshExecuteCmdWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd, int nTimes) {
- for (int i = 0; i < nTimes; i++) {
- try {
- return sshExecuteCmdOneShotWithExitCode(sshConnection, cmd);
- } catch (SshException e) {
- continue;
- }
- }
- return -1;
- }
-
- public static boolean sshExecuteCmd(com.trilead.ssh2.Connection sshConnection, String cmd) {
- return sshExecuteCmd(sshConnection, cmd, 3);
- }
-
- public static int sshExecuteCmdOneShotWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException {
- s_logger.debug("Executing cmd: " + cmd);
- Session sshSession = null;
- try {
- sshSession = sshConnection.openSession();
- // There is a bug in Trilead library, wait a second before
- // starting a shell and executing commands, from http://spci.st.ewi.tudelft.nl/chiron/xref/nl/tudelft/swerl/util/SSHConnection.html
- Thread.sleep(1000);
-
- if (sshSession == null) {
- throw new SshException("Cannot open ssh session");
- }
-
- sshSession.execCommand(cmd);
-
- InputStream stdout = sshSession.getStdout();
- InputStream stderr = sshSession.getStderr();
-
- byte[] buffer = new byte[8192];
- StringBuffer sbResult = new StringBuffer();
-
- int currentReadBytes = 0;
- while (true) {
- if (stdout == null || stderr == null) {
- throw new SshException("stdout or stderr of ssh session is null");
- }
- if ((stdout.available() == 0) && (stderr.available() == 0)) {
- int conditions = sshSession.waitForCondition(ChannelCondition.STDOUT_DATA
- | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
- 120000);
-
- if ((conditions & ChannelCondition.TIMEOUT) != 0) {
- String msg = "Timed out in waiting SSH execution result";
- s_logger.error(msg);
- throw new Exception(msg);
- }
-
- if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
- if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
- break;
- }
- }
-
- if ((conditions & ChannelCondition.EOF) != 0) {
- if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
- break;
- }
- }
- }
-
- while (stdout.available() > 0) {
- currentReadBytes = stdout.read(buffer);
- sbResult.append(new String(buffer, 0, currentReadBytes));
- }
-
- while (stderr.available() > 0) {
- currentReadBytes = stderr.read(buffer);
- sbResult.append(new String(buffer, 0, currentReadBytes));
- }
- }
-
- String result = sbResult.toString();
- if (result != null && !result.isEmpty())
- s_logger.debug(cmd + " output:" + result);
- // exit status delivery might get delayed
- for(int i = 0 ; i<10 ; i++ ) {
- Integer status = sshSession.getExitStatus();
- if( status != null ) {
- return status;
- }
- Thread.sleep(100);
- }
- return -1;
- } catch (Exception e) {
- s_logger.debug("Ssh executed failed", e);
- throw new SshException("Ssh executed failed " + e.getMessage());
- } finally {
- if (sshSession != null)
- sshSession.close();
- }
- }
-
- public static boolean sshExecuteCmdOneShot(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException {
- return sshExecuteCmdOneShotWithExitCode(sshConnection, cmd) == 0;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ssh/SSHKeysHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ssh/SSHKeysHelper.java b/utils/src/com/cloud/utils/ssh/SSHKeysHelper.java
deleted file mode 100644
index 39db5c4..0000000
--- a/utils/src/com/cloud/utils/ssh/SSHKeysHelper.java
+++ /dev/null
@@ -1,115 +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 com.cloud.utils.ssh;
-
-import java.io.ByteArrayOutputStream;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-import org.apache.commons.codec.binary.Base64;
-
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.KeyPair;
-
-public class SSHKeysHelper {
-
- private KeyPair keyPair;
- private static final char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
-
- private static String toHexString(byte[] b) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < b.length; i++) {
- sb.append(hexChars[(b[i] >> 4) & 0x0f]);
- sb.append(hexChars[(b[i]) & 0x0f]);
- }
- return sb.toString();
- }
-
- public SSHKeysHelper() {
- try {
- keyPair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA);
- } catch (JSchException e) {
- e.printStackTrace();
- }
- }
-
- public String getPublicKeyFingerPrint() {
- return getPublicKeyFingerprint(getPublicKey());
- }
-
- public static String getPublicKeyFingerprint(String publicKey) {
- String key[] = publicKey.split(" ");
- if (key.length < 2) {
- throw new RuntimeException("Incorrect public key is passed in");
- }
- byte[] keyBytes = Base64.decodeBase64(key[1]);
-
- MessageDigest md5 = null;
- try {
- md5 = MessageDigest.getInstance("MD5");
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
-
- String rString = "";
- String sumString = "";
- if (md5 != null) {
- sumString = toHexString(md5.digest(keyBytes));
- }
-
- for (int i = 2; i <= sumString.length(); i += 2) {
- rString += sumString.substring(i - 2, i);
- if (i != sumString.length())
- rString += ":";
- }
-
- return rString;
- }
-
- public static String getPublicKeyFromKeyMaterial(String keyMaterial) {
- if (!keyMaterial.contains(" "))
- keyMaterial = new String(Base64.decodeBase64(keyMaterial.getBytes()));
-
- if ((!keyMaterial.startsWith("ssh-rsa") && !keyMaterial.startsWith("ssh-dss")) || !keyMaterial.contains(" "))
- return null;
-
- String[] key = keyMaterial.split(" ");
- if (key.length < 2)
- return null;
-
- return key[0].concat(" ").concat(key[1]);
- }
-
- public String getPublicKey() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- keyPair.writePublicKey(baos, "");
-
- return baos.toString();
- }
-
- public String getPrivateKey() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- keyPair.writePrivateKey(baos);
-
- return baos.toString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ssh/SshException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ssh/SshException.java b/utils/src/com/cloud/utils/ssh/SshException.java
deleted file mode 100644
index a9d9ed8..0000000
--- a/utils/src/com/cloud/utils/ssh/SshException.java
+++ /dev/null
@@ -1,30 +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 com.cloud.utils.ssh;
-
-import com.cloud.utils.SerialVersionUID;
-
-public class SshException extends Exception {
- private static final long serialVersionUID = SerialVersionUID.sshException;
-
- public SshException(String msg) {
- super(msg);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/ssh/SshHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ssh/SshHelper.java b/utils/src/com/cloud/utils/ssh/SshHelper.java
deleted file mode 100644
index 3aac427..0000000
--- a/utils/src/com/cloud/utils/ssh/SshHelper.java
+++ /dev/null
@@ -1,209 +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 com.cloud.utils.ssh;
-
-import java.io.File;
-import java.io.InputStream;
-
-import org.apache.log4j.Logger;
-
-import com.trilead.ssh2.ChannelCondition;
-
-import com.cloud.utils.Pair;
-
-public class SshHelper {
- private static final int DEFAULT_CONNECT_TIMEOUT = 60000;
- private static final int DEFAULT_KEX_TIMEOUT = 60000;
-
- private static final Logger s_logger = Logger.getLogger(SshHelper.class);
-
- public static Pair<Boolean, String> sshExecute(String host, int port, String user, File pemKeyFile, String password, String command) throws Exception {
-
- return sshExecute(host, port, user, pemKeyFile, password, command, 60000, 60000, 120000);
- }
-
- public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, String localFile, String fileMode)
- throws Exception {
-
- scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, localFile, fileMode, DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT);
- }
-
- public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, byte[] data, String remoteFileName,
- String fileMode) throws Exception {
-
- scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, data, remoteFileName, fileMode, DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT);
- }
-
- public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, String localFile, String fileMode,
- int connectTimeoutInMs, int kexTimeoutInMs) throws Exception {
-
- com.trilead.ssh2.Connection conn = null;
- com.trilead.ssh2.SCPClient scpClient = null;
-
- try {
- conn = new com.trilead.ssh2.Connection(host, port);
- conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
-
- if (pemKeyFile == null) {
- if (!conn.authenticateWithPassword(user, password)) {
- String msg = "Failed to authentication SSH user " + user + " on host " + host;
- s_logger.error(msg);
- throw new Exception(msg);
- }
- } else {
- if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
- String msg = "Failed to authentication SSH user " + user + " on host " + host;
- s_logger.error(msg);
- throw new Exception(msg);
- }
- }
-
- scpClient = conn.createSCPClient();
-
- if (fileMode != null)
- scpClient.put(localFile, remoteTargetDirectory, fileMode);
- else
- scpClient.put(localFile, remoteTargetDirectory);
- } finally {
- if (conn != null)
- conn.close();
- }
- }
-
- public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, byte[] data, String remoteFileName,
- String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception {
-
- com.trilead.ssh2.Connection conn = null;
- com.trilead.ssh2.SCPClient scpClient = null;
-
- try {
- conn = new com.trilead.ssh2.Connection(host, port);
- conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
-
- if (pemKeyFile == null) {
- if (!conn.authenticateWithPassword(user, password)) {
- String msg = "Failed to authentication SSH user " + user + " on host " + host;
- s_logger.error(msg);
- throw new Exception(msg);
- }
- } else {
- if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
- String msg = "Failed to authentication SSH user " + user + " on host " + host;
- s_logger.error(msg);
- throw new Exception(msg);
- }
- }
-
- scpClient = conn.createSCPClient();
- if (fileMode != null)
- scpClient.put(data, remoteFileName, remoteTargetDirectory, fileMode);
- else
- scpClient.put(data, remoteFileName, remoteTargetDirectory);
- } finally {
- if (conn != null)
- conn.close();
- }
- }
-
- public static Pair<Boolean, String> sshExecute(String host, int port, String user, File pemKeyFile, String password, String command, int connectTimeoutInMs,
- int kexTimeoutInMs, int waitResultTimeoutInMs) throws Exception {
-
- com.trilead.ssh2.Connection conn = null;
- com.trilead.ssh2.Session sess = null;
- try {
- conn = new com.trilead.ssh2.Connection(host, port);
- conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
-
- if (pemKeyFile == null) {
- if (!conn.authenticateWithPassword(user, password)) {
- String msg = "Failed to authentication SSH user " + user + " on host " + host;
- s_logger.error(msg);
- throw new Exception(msg);
- }
- } else {
- if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
- String msg = "Failed to authentication SSH user " + user + " on host " + host;
- s_logger.error(msg);
- throw new Exception(msg);
- }
- }
- sess = conn.openSession();
-
- sess.execCommand(command);
-
- InputStream stdout = sess.getStdout();
- InputStream stderr = sess.getStderr();
-
- byte[] buffer = new byte[8192];
- StringBuffer sbResult = new StringBuffer();
-
- int currentReadBytes = 0;
- while (true) {
- if ((stdout.available() == 0) && (stderr.available() == 0)) {
- int conditions =
- sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
- waitResultTimeoutInMs);
-
- if ((conditions & ChannelCondition.TIMEOUT) != 0) {
- String msg = "Timed out in waiting SSH execution result";
- s_logger.error(msg);
- throw new Exception(msg);
- }
-
- if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
- if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
- break;
- }
- }
- }
-
- while (stdout.available() > 0) {
- currentReadBytes = stdout.read(buffer);
- sbResult.append(new String(buffer, 0, currentReadBytes));
- }
-
- while (stderr.available() > 0) {
- currentReadBytes = stderr.read(buffer);
- sbResult.append(new String(buffer, 0, currentReadBytes));
- }
- }
-
- String result = sbResult.toString();
-
- if (sess.getExitStatus() == null) {
- //Exit status is NOT available. Returning failure result.
- return new Pair<Boolean, String>(false, result);
- }
-
- if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
- s_logger.error("SSH execution of command " + command + " has an error status code in return. result output: " + result);
- return new Pair<Boolean, String>(false, result);
- }
-
- return new Pair<Boolean, String>(true, result);
- } finally {
- if (sess != null)
- sess.close();
-
- if (conn != null)
- conn.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/storage/encoding/DecodedDataObject.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/storage/encoding/DecodedDataObject.java b/utils/src/com/cloud/utils/storage/encoding/DecodedDataObject.java
deleted file mode 100644
index 56be699..0000000
--- a/utils/src/com/cloud/utils/storage/encoding/DecodedDataObject.java
+++ /dev/null
@@ -1,56 +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 com.cloud.utils.storage.encoding;
-
-public class DecodedDataObject {
- private String objType;
- private Long size;
- private String name;
- private String path;
- private DecodedDataStore store;
-
- public DecodedDataObject(String objType, Long size, String name, String path, DecodedDataStore store) {
- this.objType = objType;
- this.size = size;
- this.name = name;
- this.path = path;
- this.store = store;
- }
-
- public String getObjType() {
- return objType;
- }
-
- public Long getSize() {
- return size;
- }
-
- public String getName() {
- return name;
- }
-
- public String getPath() {
- return path;
- }
-
- public DecodedDataStore getStore() {
- return store;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/storage/encoding/DecodedDataStore.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/storage/encoding/DecodedDataStore.java b/utils/src/com/cloud/utils/storage/encoding/DecodedDataStore.java
deleted file mode 100644
index ac8af8b..0000000
--- a/utils/src/com/cloud/utils/storage/encoding/DecodedDataStore.java
+++ /dev/null
@@ -1,68 +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 com.cloud.utils.storage.encoding;
-
-public class DecodedDataStore {
- private final String role;
- private final String uuid;
- private final String providerName;
- private final String scheme;
- private final String url;
- private final String server;
- private final String path;
-
- public DecodedDataStore(String role, String uuid, String providerName, String scheme, String url, String server, String path) {
- this.role = role;
- this.uuid = uuid;
- this.providerName = providerName;
- this.scheme = scheme;
- this.url = url;
- this.server = server;
- this.path = path;
- }
-
- public String getRole() {
- return role;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public String getProviderName() {
- return providerName;
- }
-
- public String getScheme() {
- return scheme;
- }
-
- public String getUrl() {
- return url;
- }
-
- public String getServer() {
- return server;
- }
-
- public String getPath() {
- return path;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/storage/encoding/Decoder.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/storage/encoding/Decoder.java b/utils/src/com/cloud/utils/storage/encoding/Decoder.java
deleted file mode 100644
index c7c61d3..0000000
--- a/utils/src/com/cloud/utils/storage/encoding/Decoder.java
+++ /dev/null
@@ -1,66 +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 com.cloud.utils.storage.encoding;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-
-public class Decoder {
- private static final Logger s_logger = Logger.getLogger(Decoder.class);
-
- private static Map<String, String> getParameters(URI uri) {
- String parameters = uri.getQuery();
- Map<String, String> params = new HashMap<String, String>();
- List<String> paraLists = Arrays.asList(parameters.split("&"));
- for (String para : paraLists) {
- String[] pair = para.split("=");
- if (!pair[1].equalsIgnoreCase("null")) {
- params.put(pair[0], pair[1]);
- }
-
- }
- return params;
- }
-
- public static DecodedDataObject decode(String url) throws URISyntaxException {
- URI uri = new URI(url);
- Map<String, String> params = getParameters(uri);
- DecodedDataStore store =
- new DecodedDataStore(params.get(EncodingType.ROLE.toString()), params.get(EncodingType.STOREUUID.toString()),
- params.get(EncodingType.PROVIDERNAME.toString()), uri.getScheme(), uri.getScheme() + uri.getHost() + uri.getPath(), uri.getHost(), uri.getPath());
-
- Long size = null;
- try {
- size = Long.parseLong(params.get(EncodingType.SIZE.toString()));
- } catch (NumberFormatException e) {
- s_logger.info("[ignored] number not recognised",e);
- }
- DecodedDataObject obj =
- new DecodedDataObject(params.get(EncodingType.OBJTYPE.toString()), size, params.get(EncodingType.NAME.toString()), params.get(EncodingType.PATH.toString()),
- store);
- return obj;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/storage/encoding/EncodingType.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/storage/encoding/EncodingType.java b/utils/src/com/cloud/utils/storage/encoding/EncodingType.java
deleted file mode 100644
index f40f4f9..0000000
--- a/utils/src/com/cloud/utils/storage/encoding/EncodingType.java
+++ /dev/null
@@ -1,32 +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 com.cloud.utils.storage.encoding;
-
-public enum EncodingType {
- //object
- OBJTYPE,
- SIZE,
- NAME,
- PATH,
- //dataStore
- ROLE,
- STOREUUID,
- PROVIDERNAME
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/time/InaccurateClock.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/time/InaccurateClock.java b/utils/src/com/cloud/utils/time/InaccurateClock.java
deleted file mode 100644
index 2a22853..0000000
--- a/utils/src/com/cloud/utils/time/InaccurateClock.java
+++ /dev/null
@@ -1,102 +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 com.cloud.utils.time;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.StandardMBean;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.concurrency.NamedThreadFactory;
-import com.cloud.utils.mgmt.JmxUtil;
-
-/**
- */
-
-public class InaccurateClock extends StandardMBean implements InaccurateClockMBean {
- private static final Logger s_logger = Logger.getLogger(InaccurateClock.class);
- static ScheduledExecutorService s_executor = null;
- static final InaccurateClock s_timer = new InaccurateClock();
- private static long time;
-
- public InaccurateClock() {
- super(InaccurateClockMBean.class, false);
- time = System.currentTimeMillis();
- restart();
- try {
- JmxUtil.registerMBean("InaccurateClock", "InaccurateClock", this);
- } catch (Exception e) {
- s_logger.warn("Unable to initialize inaccurate clock", e);
- }
- }
-
- @Override
- public long[] getCurrentTimes() {
- long[] results = new long[2];
- results[0] = time;
- results[1] = System.currentTimeMillis();
-
- return results;
- }
-
- @Override
- public synchronized String restart() {
- turnOff();
- s_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("InaccurateClock"));
- s_executor.scheduleAtFixedRate(new SetTimeTask(), 0, 60, TimeUnit.SECONDS);
- return "Restarted";
- }
-
- @Override
- public String turnOff() {
- if (s_executor != null) {
- try {
- s_executor.shutdown();
- } catch (Throwable th) {
- s_logger.error("Unable to shutdown the Executor", th);
- return "Unable to turn off check logs";
- }
- }
- s_executor = null;
- return "Off";
- }
-
- public static long getTime() {
- return s_executor != null ? time : System.currentTimeMillis();
- }
-
- public static long getTimeInSeconds() {
- return time / 1000;
- }
-
- protected class SetTimeTask implements Runnable {
- @Override
- public void run() {
- try {
- time = System.currentTimeMillis();
- } catch (Throwable th) {
- s_logger.error("Unable to time", th);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/time/InaccurateClockMBean.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/time/InaccurateClockMBean.java b/utils/src/com/cloud/utils/time/InaccurateClockMBean.java
deleted file mode 100644
index acc4615..0000000
--- a/utils/src/com/cloud/utils/time/InaccurateClockMBean.java
+++ /dev/null
@@ -1,28 +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 com.cloud.utils.time;
-
-public interface InaccurateClockMBean {
- String restart();
-
- String turnOff();
-
- long[] getCurrentTimes();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/xmlobject/XmlObject.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/xmlobject/XmlObject.java b/utils/src/com/cloud/utils/xmlobject/XmlObject.java
deleted file mode 100644
index 42af945..0000000
--- a/utils/src/com/cloud/utils/xmlobject/XmlObject.java
+++ /dev/null
@@ -1,214 +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 com.cloud.utils.xmlobject;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Logger;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class XmlObject {
- private final Logger logger = Logger.getLogger(XmlObject.class.getName());
- private final Map<String, Object> elements = new HashMap<String, Object>();
- private String text;
- private String tag;
-
- XmlObject() {
- }
-
- public void removeAllChildren() {
- elements.clear();
- }
-
- public XmlObject(String tag) {
- this.tag = tag;
- }
-
- public XmlObject putElement(String key, Object e) {
- if (e == null) {
- throw new IllegalArgumentException(String.format("element[%s] can not be null", key));
- }
- Object old = elements.get(key);
- if (old == null) {
- //System.out.println(String.format("no %s, add new", key));
- elements.put(key, e);
- } else {
- if (old instanceof List) {
- //System.out.println(String.format("already list %s, add", key));
- ((List)old).add(e);
- } else {
- //System.out.println(String.format("not list list %s, add list", key));
- List lst = new ArrayList();
- lst.add(old);
- lst.add(e);
- elements.put(key, lst);
- }
- }
-
- return this;
- }
-
- public void removeElement(String key) {
- elements.remove(key);
- }
-
- private Object recurGet(XmlObject obj, Iterator<String> it) {
- String key = it.next();
- Object e = obj.elements.get(key);
- if (e == null) {
- return null;
- }
-
- if (!it.hasNext()) {
- return e;
- } else {
- if (!(e instanceof XmlObject)) {
- throw new CloudRuntimeException(String.format("%s doesn't reference to a XmlObject", it.next()));
- }
- return recurGet((XmlObject)e, it);
- }
- }
-
- public <T> T get(String elementStr) {
- String[] strs = elementStr.split("\\.");
- List<String> lst = new ArrayList<String>(strs.length);
- Collections.addAll(lst, strs);
- return (T)recurGet(this, lst.iterator());
- }
-
- public <T> List<T> getAsList(String elementStr) {
- Object e = get(elementStr);
- if (e instanceof List) {
- return (List<T>)e;
- }
-
- List lst = new ArrayList(1);
- if (e != null) {
- lst.add(e);
- }
-
- return lst;
- }
-
- public String getText() {
- return text;
- }
-
- public XmlObject setText(String text) {
- this.text = text;
- return this;
- }
-
- public String getTag() {
- return tag;
- }
-
- public XmlObject setTag(String tag) {
- this.tag = tag;
- return this;
- }
-
- public String dump() {
- StringBuilder sb = new StringBuilder();
- sb.append("<").append(tag);
- List<XmlObject> children = new ArrayList<XmlObject>();
- for (Map.Entry<String, Object> e : elements.entrySet()) {
- String key = e.getKey();
- Object val = e.getValue();
- if (val instanceof String) {
- sb.append(String.format(" %s=\"%s\"", key, val.toString()));
- } else if (val instanceof XmlObject) {
- children.add((XmlObject)val);
- } else if (val instanceof List) {
- children.addAll((Collection<? extends XmlObject>)val);
- } else {
- throw new CloudRuntimeException(String.format("unsupported element type[tag:%s, class: %s], only allowed type of [String, List<XmlObject>, Object]", key,
- val.getClass().getName()));
- }
- }
-
- if (!children.isEmpty() && text != null) {
- logger.info(String.format("element %s cannot have both text[%s] and child elements, set text to null", tag, text));
- text = null;
- }
-
- if (!children.isEmpty()) {
- sb.append(">");
- for (XmlObject x : children) {
- sb.append(x.dump());
- }
- sb.append(String.format("</%s>", tag));
- } else {
- if (text != null) {
- sb.append(">");
- sb.append(text);
- sb.append(String.format("</%s>", tag));
- } else {
- sb.append(" />");
- }
- }
- return sb.toString();
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("<" + tag);
- for (Map.Entry<String, Object> e : elements.entrySet()) {
- String key = e.getKey();
- Object value = e.getValue();
- if (!(value instanceof String)) {
- continue;
- }
- sb.append(String.format(" %s=\"%s\"", key, value.toString()));
- }
-
- if (text == null || "".equals(text.trim())) {
- sb.append(" />");
- } else {
- sb.append(">").append(text).append(String.format("</ %s>", tag));
- }
- return sb.toString();
- }
-
- public <T> T evaluateObject(T obj) {
- Class<?> clazz = obj.getClass();
- try {
- do {
- Field[] fs = clazz.getDeclaredFields();
- for (Field f : fs) {
- f.setAccessible(true);
- Object value = get(f.getName());
- f.set(obj, value);
- }
- clazz = clazz.getSuperclass();
- } while (clazz != null && clazz != Object.class);
- return obj;
- } catch (Exception e) {
- throw new CloudRuntimeException(e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java b/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java
deleted file mode 100644
index f0e8ce3..0000000
--- a/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java
+++ /dev/null
@@ -1,128 +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 com.cloud.utils.xmlobject;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.Stack;
-
-public class XmlObjectParser {
- final private InputStream is;
-
- private class XmlHandler extends DefaultHandler {
- private Stack<XmlObject> stack;
- private String currentValue;
- private XmlObject root;
-
- XmlHandler() {
- stack = new Stack<XmlObject>();
- }
-
- @Override
- public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
- //System.out.println(String.format("startElement: namespaceURI:%s, localName:%s, qName:%s", namespaceURI, localName, qName));
- currentValue = null;
- XmlObject obj = new XmlObject();
- for (int i = 0; i < atts.getLength(); i++) {
- obj.putElement(atts.getQName(i), atts.getValue(i));
- }
- obj.setTag(qName);
- if (!stack.isEmpty()) {
- XmlObject parent = stack.peek();
- parent.putElement(qName, obj);
- }
- stack.push(obj);
- }
-
- @Override
- public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
- XmlObject currObj = stack.pop();
- if (currentValue != null) {
- currObj.setText(currentValue);
- }
-
- if (stack.isEmpty()) {
- root = currObj;
- }
-
- //System.out.println(String.format("endElement: namespaceURI:%s, localName:%s, qName:%s", namespaceURI, localName, qName));
- }
-
- @Override
- public void characters(char[] ch, int start, int length) throws SAXException {
- StringBuilder str = new StringBuilder();
- str.append(ch, start, length);
- currentValue = str.toString();
- //System.out.println(String.format("characters: %s", str.toString()));
- }
-
- XmlObject getRoot() {
- return root;
- }
- }
-
- private XmlObjectParser(InputStream is) {
- super();
- this.is = is;
- }
-
- public static XmlObject parseFromFile(String filePath) {
- FileInputStream fs;
- try {
- fs = new FileInputStream(new File(filePath));
- XmlObjectParser p = new XmlObjectParser(fs);
- return p.parse();
- } catch (FileNotFoundException e) {
- throw new CloudRuntimeException(e);
- }
- }
-
- public static XmlObject parseFromString(String xmlString) {
- InputStream stream = new ByteArrayInputStream(xmlString.getBytes());
- XmlObjectParser p = new XmlObjectParser(stream);
- XmlObject obj = p.parse();
- if (obj.getText() != null && obj.getText().replaceAll("\\n", "").replaceAll("\\r", "").replaceAll(" ", "").isEmpty()) {
- obj.setText(null);
- }
- return obj;
- }
-
- private XmlObject parse() {
- SAXParserFactory spfactory = SAXParserFactory.newInstance();
- try {
- SAXParser saxParser = spfactory.newSAXParser();
- XmlHandler handler = new XmlHandler();
- saxParser.parse(is, handler);
- return handler.getRoot();
- } catch (Exception e) {
- throw new CloudRuntimeException(e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/maint/Version.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/maint/Version.java b/utils/src/main/java/com/cloud/maint/Version.java
new file mode 100644
index 0000000..925806e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/maint/Version.java
@@ -0,0 +1,77 @@
+//
+// 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 com.cloud.maint;
+
+public class Version {
+ /**
+ * Compares two version strings and see which one is higher version.
+ * @param ver1
+ * @param ver2
+ * @return positive if ver1 is higher. negative if ver1 is lower; zero if the same.
+ */
+ public static int compare(String ver1, String ver2) {
+ String[] tokens1 = ver1.split("[.]");
+ String[] tokens2 = ver2.split("[.]");
+// assert(tokens1.length <= tokens2.length);
+
+ int compareLength = Math.min(tokens1.length, tokens2.length);
+ for (int i = 0; i < compareLength; i++) {
+ long version1 = Long.parseLong(tokens1[i]);
+ long version2 = Long.parseLong(tokens2[i]);
+ if (version1 != version2) {
+ return version1 < version2 ? -1 : 1;
+ }
+ }
+
+ if (tokens1.length > tokens2.length) {
+ return 1;
+ } else if (tokens1.length < tokens2.length) {
+ return -1;
+ }
+
+ return 0;
+ }
+
+ public static String trimToPatch(String version) {
+ int index = version.indexOf("-");
+
+ if (index > 0)
+ version = version.substring(0, index);
+
+ String[] tokens = version.split("[.]");
+
+ if (tokens.length < 3)
+ return "0";
+ return tokens[0] + "." + tokens[1] + "." + tokens[2];
+ }
+
+ public static String trimRouterVersion(String version) {
+ String[] tokens = version.split(" ");
+ if (tokens.length >= 3 && tokens[2].matches("[0-9]+(\\.[0-9]+)*")) {
+ return tokens[2];
+ }
+ return "0";
+ }
+
+ public static void main(String[] args) {
+ System.out.println("Result is " + compare(args[0], args[1]));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ActionDelegate.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ActionDelegate.java b/utils/src/main/java/com/cloud/utils/ActionDelegate.java
new file mode 100644
index 0000000..02f76d9
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ActionDelegate.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.utils;
+
+public interface ActionDelegate<T> {
+ void action(T param);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/AutoCloseableUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/AutoCloseableUtil.java b/utils/src/main/java/com/cloud/utils/AutoCloseableUtil.java
new file mode 100644
index 0000000..f93265b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/AutoCloseableUtil.java
@@ -0,0 +1,36 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.utils;
+
+import org.apache.log4j.Logger;
+
+public class AutoCloseableUtil {
+ private final static Logger s_logger = Logger.getLogger(AutoCloseableUtil.class);
+
+ public static void closeAutoCloseable(AutoCloseable ac, String message) {
+ try {
+
+ if (ac != null) {
+ ac.close();
+ }
+
+ } catch (Exception e) {
+ s_logger.warn("[ignored] " + message, e);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/CloudResourceBundle.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/CloudResourceBundle.java b/utils/src/main/java/com/cloud/utils/CloudResourceBundle.java
new file mode 100644
index 0000000..cf27d79
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/CloudResourceBundle.java
@@ -0,0 +1,48 @@
+//
+// 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 com.cloud.utils;
+
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+public class CloudResourceBundle {
+
+ private ResourceBundle _bundle;
+
+ public CloudResourceBundle(ResourceBundle bundle) {
+ _bundle = bundle;
+ }
+
+ public static CloudResourceBundle getBundle(String baseName, Locale locale) {
+ return new CloudResourceBundle(ResourceBundle.getBundle(baseName, locale));
+ }
+
+ private String getString(String key) {
+ try {
+ return _bundle.getString(key);
+ } catch (Exception e) {
+ return key; //if translation is not found, just return original word (i.e. English).
+ }
+ }
+
+ public String t(String key) {
+ return getString(key);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ConstantTimeComparator.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ConstantTimeComparator.java b/utils/src/main/java/com/cloud/utils/ConstantTimeComparator.java
new file mode 100644
index 0000000..baf2bc2
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ConstantTimeComparator.java
@@ -0,0 +1,42 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import java.nio.charset.Charset;
+
+public class ConstantTimeComparator {
+
+ public static boolean compareBytes(byte[] b1, byte[] b2) {
+ if (b1.length != b2.length) {
+ return false;
+ }
+
+ int result = 0;
+ for (int i = 0; i < b1.length; i++) {
+ result |= b1[i] ^ b2[i];
+ }
+ return result == 0;
+ }
+
+ public static boolean compareStrings(String s1, String s2) {
+ final Charset encoding = Charset.forName("UTF-8");
+ return compareBytes(s1.getBytes(encoding), s2.getBytes(encoding));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/DateUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/DateUtil.java b/utils/src/main/java/com/cloud/utils/DateUtil.java
new file mode 100644
index 0000000..7787e1b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/DateUtil.java
@@ -0,0 +1,274 @@
+//
+// 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 com.cloud.utils;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class DateUtil {
+ public static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
+ public static final String YYYYMMDD_FORMAT = "yyyyMMddHHmmss";
+ private static final DateFormat s_outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
+
+ public static Date currentGMTTime() {
+ // Date object always stores miliseconds offset based on GMT internally
+ return new Date();
+ }
+
+ // yyyy-MM-ddTHH:mm:ssZxxxx
+ public static Date parseTZDateString(String str) throws ParseException {
+ DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z");
+ return dfParse.parse(str);
+ }
+
+ public static Date parseDateString(TimeZone tz, String dateString) {
+ return parseDateString(tz, dateString, "yyyy-MM-dd HH:mm:ss");
+ }
+
+ public static Date parseDateString(TimeZone tz, String dateString, String formatString) {
+ DateFormat df = new SimpleDateFormat(formatString);
+ df.setTimeZone(tz);
+
+ try {
+ return df.parse(dateString);
+ } catch (ParseException e) {
+ throw new CloudRuntimeException("why why ", e);
+ }
+ }
+
+ public static String displayDateInTimezone(TimeZone tz, Date time) {
+ return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss z");
+ }
+
+ public static String getDateDisplayString(TimeZone tz, Date time) {
+ return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss");
+ }
+
+ public static String getDateDisplayString(TimeZone tz, Date time, String formatString) {
+ DateFormat df = new SimpleDateFormat(formatString);
+ df.setTimeZone(tz);
+
+ return df.format(time);
+ }
+
+ public static String getOutputString(Date date) {
+ if (date == null) {
+ return "";
+ }
+ String formattedString = null;
+ synchronized (s_outputFormat) {
+ formattedString = s_outputFormat.format(date);
+ }
+ return formattedString;
+ }
+
+ public static Date now() {
+ return new Date(System.currentTimeMillis());
+ }
+
+ public enum IntervalType {
+ HOURLY, DAILY, WEEKLY, MONTHLY;
+
+ boolean equals(String intervalType) {
+ return super.toString().equalsIgnoreCase(intervalType);
+ }
+
+ public static IntervalType getIntervalType(String intervalTypeStr) {
+ for (IntervalType intervalType : IntervalType.values()) {
+ if (intervalType.equals(intervalTypeStr)) {
+ return intervalType;
+ }
+ }
+ return null;
+ }
+ }
+
+ public static IntervalType getIntervalType(short type) {
+ if (type < 0 || type >= IntervalType.values().length) {
+ return null;
+ }
+ return IntervalType.values()[type];
+ }
+
+ /**
+ * Return next run time
+ * @param intervalType hourly/daily/weekly/monthly
+ * @param schedule MM[:HH][:DD] format. DD is day of week for weekly and day of month for monthly
+ * @param timezone The timezone in which the schedule string is specified
+ * @param startDate if specified, returns next run time after the specified startDate
+ * @return
+ */
+ public static Date getNextRunTime(IntervalType type, String schedule, String timezone, Date startDate) {
+
+ String[] scheduleParts = schedule.split(":"); //MM:HH:DAY
+
+ final Calendar scheduleTime = Calendar.getInstance();
+ scheduleTime.setTimeZone(TimeZone.getTimeZone(timezone));
+
+ if (startDate == null) {
+ startDate = new Date();
+ }
+ scheduleTime.setTime(startDate);
+ // Throw an ArrayIndexOutOfBoundsException if schedule is badly formatted.
+ scheduleTime.setLenient(false);
+ int minutes = 0;
+ int hour = 0;
+ int day = 0;
+ Date execDate = null;
+
+ switch (type) {
+ case HOURLY:
+ if (scheduleParts.length < 1) {
+ throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
+ }
+ minutes = Integer.parseInt(scheduleParts[0]);
+ scheduleTime.set(Calendar.MINUTE, minutes);
+ scheduleTime.set(Calendar.SECOND, 0);
+ scheduleTime.set(Calendar.MILLISECOND, 0);
+ try {
+ execDate = scheduleTime.getTime();
+ } catch (IllegalArgumentException ex) {
+ scheduleTime.setLenient(true);
+ execDate = scheduleTime.getTime();
+ scheduleTime.setLenient(false);
+ }
+ // XXX: !execDate.after(startDate) is strictly for testing.
+ // During testing we use a test clock which runs much faster than the real clock
+ // So startDate and execDate will always be ahead in the future
+ // and we will never increase the time here
+ if (execDate.before(new Date()) || !execDate.after(startDate)) {
+ scheduleTime.add(Calendar.HOUR_OF_DAY, 1);
+ }
+ break;
+ case DAILY:
+ if (scheduleParts.length < 2) {
+ throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
+ }
+ minutes = Integer.parseInt(scheduleParts[0]);
+ hour = Integer.parseInt(scheduleParts[1]);
+
+ scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
+ scheduleTime.set(Calendar.MINUTE, minutes);
+ scheduleTime.set(Calendar.SECOND, 0);
+ scheduleTime.set(Calendar.MILLISECOND, 0);
+ try {
+ execDate = scheduleTime.getTime();
+ } catch (IllegalArgumentException ex) {
+ scheduleTime.setLenient(true);
+ execDate = scheduleTime.getTime();
+ scheduleTime.setLenient(false);
+ }
+ // XXX: !execDate.after(startDate) is strictly for testing.
+ // During testing we use a test clock which runs much faster than the real clock
+ // So startDate and execDate will always be ahead in the future
+ // and we will never increase the time here
+ if (execDate.before(new Date()) || !execDate.after(startDate)) {
+ scheduleTime.add(Calendar.DAY_OF_YEAR, 1);
+ }
+ break;
+ case WEEKLY:
+ if (scheduleParts.length < 3) {
+ throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
+ }
+ minutes = Integer.parseInt(scheduleParts[0]);
+ hour = Integer.parseInt(scheduleParts[1]);
+ day = Integer.parseInt(scheduleParts[2]);
+ scheduleTime.set(Calendar.DAY_OF_WEEK, day);
+ scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
+ scheduleTime.set(Calendar.MINUTE, minutes);
+ scheduleTime.set(Calendar.SECOND, 0);
+ scheduleTime.set(Calendar.MILLISECOND, 0);
+ try {
+ execDate = scheduleTime.getTime();
+ } catch (IllegalArgumentException ex) {
+ scheduleTime.setLenient(true);
+ execDate = scheduleTime.getTime();
+ scheduleTime.setLenient(false);
+ }
+ // XXX: !execDate.after(startDate) is strictly for testing.
+ // During testing we use a test clock which runs much faster than the real clock
+ // So startDate and execDate will always be ahead in the future
+ // and we will never increase the time here
+ if (execDate.before(new Date()) || !execDate.after(startDate)) {
+ scheduleTime.add(Calendar.DAY_OF_WEEK, 7);
+ }
+ ;
+ break;
+ case MONTHLY:
+ if (scheduleParts.length < 3) {
+ throw new CloudRuntimeException("Incorrect schedule format: " + schedule + " for interval type:" + type.toString());
+ }
+ minutes = Integer.parseInt(scheduleParts[0]);
+ hour = Integer.parseInt(scheduleParts[1]);
+ day = Integer.parseInt(scheduleParts[2]);
+ if (day > 28) {
+ throw new CloudRuntimeException("Day cannot be greater than 28 for monthly schedule");
+ }
+ scheduleTime.set(Calendar.DAY_OF_MONTH, day);
+ scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
+ scheduleTime.set(Calendar.MINUTE, minutes);
+ scheduleTime.set(Calendar.SECOND, 0);
+ scheduleTime.set(Calendar.MILLISECOND, 0);
+ try {
+ execDate = scheduleTime.getTime();
+ } catch (IllegalArgumentException ex) {
+ scheduleTime.setLenient(true);
+ execDate = scheduleTime.getTime();
+ scheduleTime.setLenient(false);
+ }
+ // XXX: !execDate.after(startDate) is strictly for testing.
+ // During testing we use a test clock which runs much faster than the real clock
+ // So startDate and execDate will always be ahead in the future
+ // and we will never increase the time here
+ if (execDate.before(new Date()) || !execDate.after(startDate)) {
+ scheduleTime.add(Calendar.MONTH, 1);
+ }
+ break;
+ default:
+ throw new CloudRuntimeException("Incorrect interval: " + type.toString());
+ }
+
+ try {
+ return scheduleTime.getTime();
+ } catch (IllegalArgumentException ex) {
+ scheduleTime.setLenient(true);
+ Date nextScheduledDate = scheduleTime.getTime();
+ scheduleTime.setLenient(false);
+ return nextScheduledDate;
+ }
+ }
+
+ public static long getTimeDifference(Date date1, Date date2){
+
+ Calendar dateCalendar1 = Calendar.getInstance();
+ dateCalendar1.setTime(date1);
+ Calendar dateCalendar2 = Calendar.getInstance();
+ dateCalendar2.setTime(date2);
+
+ return (dateCalendar1.getTimeInMillis() - dateCalendar2.getTimeInMillis() )/1000;
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/EncryptionUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/EncryptionUtil.java b/utils/src/main/java/com/cloud/utils/EncryptionUtil.java
new file mode 100644
index 0000000..b82842e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/EncryptionUtil.java
@@ -0,0 +1,73 @@
+/*
+ * 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 com.cloud.utils;
+
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+import org.jasypt.encryption.pbe.PBEStringEncryptor;
+import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class EncryptionUtil {
+ public static final Logger s_logger = Logger.getLogger(EncryptionUtil.class.getName());
+ private static PBEStringEncryptor encryptor;
+
+ private static void initialize(String key) {
+ StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
+ standardPBEStringEncryptor.setAlgorithm("PBEWITHSHA1ANDDESEDE");
+ standardPBEStringEncryptor.setPassword(key);
+ encryptor = standardPBEStringEncryptor;
+ }
+
+ public static String encodeData(String data, String key) {
+ if (encryptor == null) {
+ initialize(key);
+ }
+ return encryptor.encrypt(data);
+ }
+
+ public static String decodeData(String encodedData, String key) {
+ if (encryptor == null) {
+ initialize(key);
+ }
+ return encryptor.decrypt(encodedData);
+ }
+
+ public static String generateSignature(String data, String key) {
+ try {
+ final Mac mac = Mac.getInstance("HmacSHA1");
+ final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
+ mac.init(keySpec);
+ mac.update(data.getBytes("UTF-8"));
+ final byte[] encryptedBytes = mac.doFinal();
+ return Base64.encodeBase64String(encryptedBytes);
+ } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
+ s_logger.error("exception occurred which encoding the data." + e.getMessage());
+ throw new CloudRuntimeException("unable to generate signature", e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/EnumUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/EnumUtils.java b/utils/src/main/java/com/cloud/utils/EnumUtils.java
new file mode 100644
index 0000000..02b6a25
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/EnumUtils.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+public class EnumUtils {
+ public static String listValues(Enum<?>[] enums) {
+ StringBuilder b = new StringBuilder("[");
+
+ for (Enum<?> e : enums) {
+ b.append(e).append(", ");
+ }
+ b.append("]");
+ return b.toString();
+ }
+
+ public static <T extends Enum<T>> T fromString(Class<T> clz, String value, T defaultVal) {
+ assert (clz != null);
+
+ if (value != null) {
+ try {
+ return Enum.valueOf(clz, value.trim());
+ } catch (IllegalArgumentException ex) {
+ assert (false);
+ }
+ }
+ return defaultVal;
+ }
+
+ public static <T extends Enum<T>> T fromString(Class<T> clz, String value) {
+ assert (clz != null);
+
+ if (value != null) {
+ try {
+ return Enum.valueOf(clz, value.trim());
+ } catch (IllegalArgumentException ex) {
+ assert (false);
+ }
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ExecutionResult.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ExecutionResult.java b/utils/src/main/java/com/cloud/utils/ExecutionResult.java
new file mode 100644
index 0000000..c8b620a
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ExecutionResult.java
@@ -0,0 +1,46 @@
+//
+// 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 com.cloud.utils;
+
+public class ExecutionResult {
+ private Boolean success;
+ private String details;
+
+ public ExecutionResult(Boolean success, String details) {
+ this.success = success;
+ this.details = details;
+ }
+
+ public Boolean isSuccess() {
+ return success;
+ }
+
+ public void setSuccess(Boolean success) {
+ this.success = success;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/FileUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/FileUtil.java b/utils/src/main/java/com/cloud/utils/FileUtil.java
new file mode 100644
index 0000000..c55dd74
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/FileUtil.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.commons.io.FileUtils;
+
+public class FileUtil {
+
+ public static void copyfile(File source, File destination) throws IOException {
+ FileUtils.copyFile(source, destination);
+ }
+}
[05/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Merge pull request #738 from michaelandersen/vpc_defaultroute_fix
CLOUDSTACK-8685: Fix for missing defaultroute on VPC router https://issues.apache.org/jira/browse/CLOUDSTACK-8685
Refactored CsRoute and CsAddress to:
- add methods to add and verify the defaultroute
- renamed methods flush, add, and routeTable to flush_table, add_route, add_table respectively.
Added some suboptimal unit tests to TestCsRoutes
* pr/738:
Fixed defaultroute on VPC routers in CsRoute and CsAddress Refactored CsRoute
pep8 cleanup
Signed-off-by: Remi Bergsma <gi...@remi.nl>
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/2772e4da
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/2772e4da
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/2772e4da
Branch: refs/heads/deploy-from-snapshot
Commit: 2772e4da82fb36a10d401fa5b072bfefeb5c0913
Parents: c0fde9a a9eb4ba
Author: Remi Bergsma <gi...@remi.nl>
Authored: Tue Aug 25 10:37:26 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Tue Aug 25 10:37:27 2015 +0200
----------------------------------------------------------------------
.../debian/config/opt/cloud/bin/cs/CsAddress.py | 178 +++++++++++++------
.../config/opt/cloud/bin/cs/CsRedundant.py | 59 +++---
.../debian/config/opt/cloud/bin/cs/CsRoute.py | 64 +++++--
.../debian/config/opt/cloud/bin/master.py | 2 +-
systemvm/test/python/TestCsRoute.py | 17 +-
5 files changed, 229 insertions(+), 91 deletions(-)
----------------------------------------------------------------------
[32/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
new file mode 100644
index 0000000..7fe6287
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -0,0 +1,255 @@
+//
+// 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 com.cloud.network.resource;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
+import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalRouterCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
+import com.cloud.agent.api.MaintainCommand;
+import com.cloud.agent.api.ReadyCommand;
+import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalRouterPort;
+import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.nicira.VifAttachment;
+
+public class NiciraNvpRequestWrapperTest {
+
+ @Mock
+ private final NiciraNvpResource niciraNvpResource = Mockito.mock(NiciraNvpResource.class);
+
+ @Test
+ public void testReadyCommandWrapper() {
+ final ReadyCommand command = new ReadyCommand();
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testMaintainCommandWrapper() {
+ final MaintainCommand command = new MaintainCommand();
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testCreateLogicalSwitchCommandWrapper() {
+ final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+ final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class);
+ final LogicalSwitch logicalSwitch = Mockito.mock(LogicalSwitch.class);
+
+ final String transportUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String transportType = "stt";
+ final String name = "logicalswitch";
+ final String ownerName = "owner";
+
+ final CreateLogicalSwitchCommand command = new CreateLogicalSwitchCommand(transportUuid, transportType, name, ownerName);
+
+ final String truncated = "lswitch-" + command.getName();
+
+ when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities);
+ when(niciraNvpUtilities.createLogicalSwitch()).thenReturn(logicalSwitch);
+ when(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN)).thenReturn(truncated);
+ when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+ try {
+ when(niciraNvpApi.createLogicalSwitch(logicalSwitch)).thenReturn(logicalSwitch);
+ when(logicalSwitch.getUuid()).thenReturn(transportUuid);
+ } catch (final NiciraNvpApiException e) {
+ fail(e.getMessage());
+ }
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testDeleteLogicalSwitchCommandWrapper() {
+ final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+
+ final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+
+ final DeleteLogicalSwitchCommand command = new DeleteLogicalSwitchCommand(logicalSwitchUuid);
+
+ when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+ try {
+ doNothing().when(niciraNvpApi).deleteLogicalSwitch(command.getLogicalSwitchUuid());
+ } catch (final NiciraNvpApiException e) {
+ fail(e.getMessage());
+ }
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testConfigurePublicIpsOnLogicalRouterCommand() {
+ final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+ final LogicalRouterPort port1 = Mockito.mock(LogicalRouterPort.class);
+
+ final List<LogicalRouterPort> listPorts = new ArrayList<LogicalRouterPort>();
+ listPorts.add(port1);
+
+ final NiciraNvpList<LogicalRouterPort> ports = new NiciraNvpList<LogicalRouterPort>();
+ ports.setResults(listPorts);
+ ports.setResultCount(1);
+
+ final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final List<String> publicCidrs = new ArrayList<String>();
+ publicCidrs.add("10.1.1.0/24");
+
+ final ConfigurePublicIpsOnLogicalRouterCommand command = new ConfigurePublicIpsOnLogicalRouterCommand(logicalRouterUuid, l3GatewayServiceUuid, publicCidrs);
+
+ when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+ try {
+ when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(ports);
+ doNothing().when(niciraNvpApi).updateLogicalRouterPort(command.getLogicalRouterUuid(), port1);
+ } catch (final NiciraNvpApiException e) {
+ fail(e.getMessage());
+ }
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testDeleteLogicalSwitchPortCommand() {
+ final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+
+ final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+
+ final DeleteLogicalSwitchPortCommand command = new DeleteLogicalSwitchPortCommand(logicalSwitchUuid, logicalSwitchPortUuid);
+
+ when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+ try {
+ doNothing().when(niciraNvpApi).deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid());
+ } catch (final NiciraNvpApiException e) {
+ fail(e.getMessage());
+ }
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testDeleteLogicalRouterCommand() {
+ final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+
+ final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+
+ final DeleteLogicalRouterCommand command = new DeleteLogicalRouterCommand(logicalRouterUuid);
+
+ when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+ try {
+ doNothing().when(niciraNvpApi).deleteLogicalRouter(command.getLogicalRouterUuid());
+ } catch (final NiciraNvpApiException e) {
+ fail(e.getMessage());
+ }
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+
+ @Test
+ public void testUpdateLogicalSwitchPortCommand() {
+ final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+ final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class);
+ final VifAttachment vifAttachment = Mockito.mock(VifAttachment.class);
+
+ final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String attachmentUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+ final String ownerName = "admin";
+ final String nicName = "eth0";
+
+ final UpdateLogicalSwitchPortCommand command = new UpdateLogicalSwitchPortCommand(logicalSwitchPortUuid, logicalSwitchUuid, attachmentUuid, ownerName, nicName);
+
+ when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities);
+ when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+ try {
+ when(niciraNvpUtilities.createVifAttachment(attachmentUuid)).thenReturn(vifAttachment);
+ doNothing().when(niciraNvpApi).updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment);
+ } catch (final NiciraNvpApiException e) {
+ fail(e.getMessage());
+ }
+
+ final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+ assertNotNull(wrapper);
+
+ final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+ assertTrue(answer.getResult());
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
new file mode 100644
index 0000000..ddf2993
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -0,0 +1,882 @@
+//
+// 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 com.cloud.network.resource;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.naming.ConfigurationException;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.CreateLogicalRouterAnswer;
+import com.cloud.agent.api.CreateLogicalRouterCommand;
+import com.cloud.agent.api.CreateLogicalSwitchAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
+import com.cloud.agent.api.DeleteLogicalRouterAnswer;
+import com.cloud.agent.api.DeleteLogicalRouterCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
+import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
+import com.cloud.agent.api.FindLogicalSwitchPortCommand;
+import com.cloud.agent.api.PingCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
+import com.cloud.agent.api.to.PortForwardingRuleTO;
+import com.cloud.agent.api.to.StaticNatRuleTO;
+import com.cloud.host.Host;
+import com.cloud.network.nicira.Attachment;
+import com.cloud.network.nicira.ControlClusterStatus;
+import com.cloud.network.nicira.DestinationNatRule;
+import com.cloud.network.nicira.LogicalRouter;
+import com.cloud.network.nicira.LogicalRouterPort;
+import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NatRule;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.nicira.SourceNatRule;
+import com.cloud.network.utils.CommandRetryUtility;
+
+public class NiciraNvpResourceTest {
+ NiciraNvpApi nvpApi = mock(NiciraNvpApi.class);
+ NiciraNvpResource resource;
+ Map<String, Object> parameters;
+
+ private CommandRetryUtility retryUtility;
+
+ @Before
+ public void setUp() throws ConfigurationException {
+ resource = new NiciraNvpResource() {
+ @Override
+ protected NiciraNvpApi createNiciraNvpApi() {
+ return nvpApi;
+ }
+ };
+
+ parameters = new HashMap<String, Object>();
+ parameters.put("name", "nvptestdevice");
+ parameters.put("ip", "127.0.0.1");
+ parameters.put("adminuser", "adminuser");
+ parameters.put("guid", "aaaaa-bbbbb-ccccc");
+ parameters.put("zoneId", "blublub");
+ parameters.put("adminpass", "adminpass");
+
+ retryUtility = CommandRetryUtility.getInstance();
+ retryUtility.setServerResource(resource);
+ }
+
+ @Test(expected = ConfigurationException.class)
+ public void resourceConfigureFailure() throws ConfigurationException {
+ resource.configure("NiciraNvpResource", Collections.<String, Object> emptyMap());
+ }
+
+ @Test
+ public void resourceConfigure() throws ConfigurationException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ verify(nvpApi).setAdminCredentials("adminuser", "adminpass");
+ verify(nvpApi).setControllerAddress("127.0.0.1");
+ assertTrue("Incorrect resource name", "nvptestdevice".equals(resource.getName()));
+
+ /* Pretty lame test, but here to assure this plugin fails
+ * if the type name ever changes from L2Networking
+ */
+ assertTrue("Incorrect resource type", resource.getType() == Host.Type.L2Networking);
+ }
+
+ @Test
+ public void testInitialization() throws ConfigurationException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final StartupCommand[] sc = resource.initialize();
+ assertTrue(sc.length == 1);
+ assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid()));
+ assertTrue("Incorrect NVP device name", "nvptestdevice".equals(sc[0].getName()));
+ assertTrue("Incorrect Data Center", "blublub".equals(sc[0].getDataCenter()));
+ }
+
+ @Test
+ public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
+ when(ccs.getClusterStatus()).thenReturn("stable");
+ when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
+
+ final PingCommand ping = resource.getCurrentStatus(42);
+ assertTrue(ping != null);
+ assertTrue(ping.getHostId() == 42);
+ assertTrue(ping.getHostType() == Host.Type.L2Networking);
+ }
+
+ @Test
+ public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
+ when(ccs.getClusterStatus()).thenReturn("unstable");
+ when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
+
+ final PingCommand ping = resource.getCurrentStatus(42);
+ assertTrue(ping == null);
+ }
+
+ @Test
+ public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
+ when(ccs.getClusterStatus()).thenReturn("unstable");
+ when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException());
+
+ final PingCommand ping = resource.getCurrentStatus(42);
+ assertTrue(ping == null);
+ }
+
+ @Test
+ public void testRetries() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalSwitch ls = mock(LogicalSwitch.class);
+ when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
+ when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls);
+
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ assertTrue(clsa.getResult());
+ }
+
+ @Test
+ public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalSwitch ls = mock(LogicalSwitch.class);
+ when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
+ when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls);
+
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ assertTrue(clsa.getResult());
+ assertTrue("cccc".equals(clsa.getLogicalSwitchUuid()));
+ }
+
+ @Test
+ public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalSwitch ls = mock(LogicalSwitch.class);
+ when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
+ when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException());
+
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ assertFalse(clsa.getResult());
+ }
+
+ @Test
+ public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
+ final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
+ assertTrue(dlsa.getResult());
+ }
+
+ @Test
+ public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any());
+
+ final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
+ final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
+ assertFalse(dlsa.getResult());
+ }
+
+ @Test
+ public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ when(lsp.getUuid()).thenReturn("eeee");
+ when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
+
+ final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ assertTrue(clspa.getResult());
+ assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid()));
+
+ }
+
+ @Test
+ public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ when(lsp.getUuid()).thenReturn("eeee");
+ when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException());
+
+ final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ assertFalse(clspa.getResult());
+ }
+
+ @Test
+ public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ when(lsp.getUuid()).thenReturn("eeee");
+ when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
+
+ final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ assertFalse(clspa.getResult());
+ verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any());
+ }
+
+ @Test
+ public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any());
+ final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
+ assertFalse(dlspa.getResult());
+ }
+
+ @Test
+ public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
+ final UpdateLogicalSwitchPortAnswer dlspa =
+ (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
+ assertFalse(dlspa.getResult());
+ }
+
+ @Test
+ public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
+ when(lspl.getResultCount()).thenReturn(1);
+ when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
+
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ assertTrue(flspa.getResult());
+ }
+
+ @Test
+ public void testFindLogicalSwitchPortNotFound() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
+ when(lspl.getResultCount()).thenReturn(0);
+ when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
+
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ assertFalse(flspa.getResult());
+ }
+
+ @Test
+ public void testFindLogicalSwitchPortApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException());
+
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ assertFalse(flspa.getResult());
+ }
+
+ @Test
+ public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalRouter lrc = mock(LogicalRouter.class);
+ final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ when(lrc.getUuid()).thenReturn("ccccc");
+ when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
+ when(lsp.getUuid()).thenReturn("fffff");
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
+ when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+
+ assertTrue(clra.getResult());
+ assertTrue("ccccc".equals(clra.getLogicalRouterUuid()));
+ verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String)any(), (NatRule)any());
+ }
+
+ @Test
+ public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenThrow(new NiciraNvpApiException());
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+
+ assertFalse(clra.getResult());
+ }
+
+ @Test
+ public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalRouter lrc = mock(LogicalRouter.class);
+ when(lrc.getUuid()).thenReturn("ccccc");
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException());
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+
+ assertFalse(clra.getResult());
+ verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
+ }
+
+ @Test
+ public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final LogicalRouter lrc = mock(LogicalRouter.class);
+ final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ when(lrc.getUuid()).thenReturn("ccccc");
+ when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
+ when(lsp.getUuid()).thenReturn("fffff");
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
+ when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
+ when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException());
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+
+ assertFalse(clra.getResult());
+ verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
+ verify(nvpApi, atLeast(1)).deleteLogicalSwitchPort(eq("bbbbb"), eq("fffff"));
+ }
+
+ @Test
+ public void testDeleteLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa"));
+ final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
+ assertFalse(dlspa.getResult());
+ }
+
+ @Test
+ public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<LogicalRouterPort> list = mock(NiciraNvpList.class);
+
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+ when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
+ when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list);
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
+
+ final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ assertFalse(answer.getResult());
+
+ }
+
+ @Test
+ public void testConfigurePublicIpsOnLogicalRouterRetry() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+
+ final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
+
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+ when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
+ when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenThrow(new NiciraNvpApiException("retry 1")).thenThrow(new NiciraNvpApiException("retry 2"));
+
+ final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ assertFalse(answer.getResult());
+
+ }
+
+ @Test
+ public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertTrue(a.getResult());
+ verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ return true;
+ }
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ return true;
+ }
+ return false;
+ }
+ }));
+ }
+
+ @Test
+ public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(storedRules.getResultCount()).thenReturn(2);
+ when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertTrue(a.getResult());
+ verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ return true;
+ }
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ return true;
+ }
+ return false;
+ }
+ }));
+ }
+
+ @Test
+ public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ final UUID rule0Uuid = UUID.randomUUID();
+ final UUID rule1Uuid = UUID.randomUUID();
+ rulepair[0].setUuid(rule0Uuid);
+ rulepair[1].setUuid(rule1Uuid);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(storedRules.getResultCount()).thenReturn(2);
+ when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertTrue(a.getResult());
+ verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final UUID uuid = (UUID)argument;
+ if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
+ return true;
+ }
+ return false;
+ }
+ }));
+ }
+
+ @Test
+ public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(storedRules.getResultCount()).thenReturn(0);
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertFalse(a.getResult());
+ verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
+ }
+
+ @Test
+ public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertTrue(a.getResult());
+ verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ return true;
+ }
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ return true;
+ }
+ return false;
+ }
+ }));
+ }
+
+ @Test
+ public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(storedRules.getResultCount()).thenReturn(2);
+ when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertTrue(a.getResult());
+ verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
+ if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
+ return true;
+ }
+ if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) {
+ return true;
+ }
+ return false;
+ }
+ }));
+ }
+
+ @Test
+ public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final UUID rule0Uuid = UUID.randomUUID();
+ final UUID rule1Uuid = UUID.randomUUID();
+ rulepair[0].setUuid(rule0Uuid);
+ rulepair[1].setUuid(rule1Uuid);
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(storedRules.getResultCount()).thenReturn(2);
+ when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertTrue(a.getResult());
+ verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
+ @Override
+ public boolean matches(final Object argument) {
+ final UUID uuid = (UUID)argument;
+ if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
+ return true;
+ }
+ return false;
+ }
+ }));
+ }
+
+ @Test
+ public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(storedRules.getResultCount()).thenReturn(0);
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ assertFalse(a.getResult());
+ verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
+ }
+
+ @Test
+ public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException {
+ resource.configure("NiciraNvpResource", parameters);
+ /* StaticNat
+ * Outside IP: 11.11.11.11
+ * Inside IP: 10.10.10.10
+ */
+
+ // Mock the command
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ rules.add(rule);
+ when(cmd.getRules()).thenReturn(rules);
+ when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+
+ // Mock the api find call
+ @SuppressWarnings("unchecked")
+ final
+ NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
+ when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
+
+ // Mock the api create calls
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp");
+ rulepair[0].setUuid(UUID.randomUUID());
+ rulepair[1].setUuid(UUID.randomUUID());
+ when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
+
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+
+ // The expected result is false, Nicira does not support port ranges in DNAT
+ assertFalse(a.getResult());
+
+ }
+
+ @Test
+ public void testGenerateStaticNatRulePair() {
+ final NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ assertTrue("DestinationNatRule".equals(rules[0].getType()));
+ assertTrue("SourceNatRule".equals(rules[1].getType()));
+
+ final DestinationNatRule dnr = (DestinationNatRule)rules[0];
+ assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
+ assertTrue(dnr.getToDestinationPort() == null);
+ assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
+
+ final SourceNatRule snr = (SourceNatRule)rules[1];
+ assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
+ assertTrue(snr.getToSourcePort() == null);
+ assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
+ }
+
+ @Test
+ public void testGeneratePortForwardingRulePair() {
+ final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ assertTrue("DestinationNatRule".equals(rules[0].getType()));
+ assertTrue("SourceNatRule".equals(rules[1].getType()));
+
+ final DestinationNatRule dnr = (DestinationNatRule)rules[0];
+ assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
+ assertTrue(dnr.getToDestinationPort() == 8080);
+ assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
+ assertTrue(dnr.getMatch().getDestinationPort() == 80);
+ assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6);
+
+ final SourceNatRule snr = (SourceNatRule)rules[1];
+ assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
+ assertTrue(snr.getToSourcePort() == 80);
+ assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
+ assertTrue(snr.getMatch().getSourcePort() == 8080);
+ assertTrue(snr.getMatch().getEthertype().equals("IPv4") && rules[1].getMatch().getProtocol() == 6);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/test/resources/config.properties
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/resources/config.properties b/plugins/network-elements/nicira-nvp/src/test/resources/config.properties
new file mode 100644
index 0000000..4006e38d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/resources/config.properties
@@ -0,0 +1,23 @@
+#
+# 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.
+#
+
+
+nvp.host=${nvp-host}
+nvp.admin.user=${nvp-admin-user}
+nvp.admin.pwd=${nvp-admin-pwd}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java
deleted file mode 100644
index bf8ce18..0000000
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java
+++ /dev/null
@@ -1,217 +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 com.cloud.network.element;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.atLeast;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.naming.ConfigurationException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentMatcher;
-
-import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
-
-import com.cloud.agent.AgentManager;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
-import com.cloud.deploy.DeployDestination;
-import com.cloud.domain.Domain;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.host.HostVO;
-import com.cloud.host.dao.HostDao;
-import com.cloud.network.IpAddress;
-import com.cloud.network.Network;
-import com.cloud.network.Network.GuestType;
-import com.cloud.network.Network.Provider;
-import com.cloud.network.Network.Service;
-import com.cloud.network.NetworkModel;
-import com.cloud.network.Networks.BroadcastDomainType;
-import com.cloud.network.Networks.TrafficType;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.network.NiciraNvpRouterMappingVO;
-import com.cloud.network.PublicIpAddress;
-import com.cloud.network.dao.NetworkServiceMapDao;
-import com.cloud.network.dao.NiciraNvpDao;
-import com.cloud.network.dao.NiciraNvpRouterMappingDao;
-import com.cloud.offering.NetworkOffering;
-import com.cloud.resource.ResourceManager;
-import com.cloud.user.Account;
-import com.cloud.utils.net.Ip;
-import com.cloud.vm.ReservationContext;
-
-public class NiciraNvpElementTest {
-
- private static final long NETWORK_ID = 42L;
- NiciraNvpElement element = new NiciraNvpElement();
- NetworkOrchestrationService networkManager = mock(NetworkOrchestrationService.class);
- NetworkModel networkModel = mock(NetworkModel.class);
- NetworkServiceMapDao ntwkSrvcDao = mock(NetworkServiceMapDao.class);
- AgentManager agentManager = mock(AgentManager.class);
- HostDao hostDao = mock(HostDao.class);
- NiciraNvpDao niciraNvpDao = mock(NiciraNvpDao.class);
- NiciraNvpRouterMappingDao niciraNvpRouterMappingDao = mock(NiciraNvpRouterMappingDao.class);
-
- @Before
- public void setUp() throws ConfigurationException {
- element.resourceMgr = mock(ResourceManager.class);
- element.networkManager = networkManager;
- element.ntwkSrvcDao = ntwkSrvcDao;
- element.networkModel = networkModel;
- element.agentMgr = agentManager;
- element.hostDao = hostDao;
- element.niciraNvpDao = niciraNvpDao;
- element.niciraNvpRouterMappingDao = niciraNvpRouterMappingDao;
-
- // Standard responses
- when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true);
-
- element.configure("NiciraNvpTestElement", Collections.<String, Object> emptyMap());
- }
-
- @Test
- public void canHandleTest() {
- final Network net = mock(Network.class);
- when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
- when(net.getId()).thenReturn(NETWORK_ID);
-
- when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true);
- // Golden path
- assertTrue(element.canHandle(net, Service.Connectivity));
-
- when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
- // Only broadcastdomaintype lswitch is supported
- assertFalse(element.canHandle(net, Service.Connectivity));
-
- when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
- when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(false);
- // No nvp provider in the network
- assertFalse(element.canHandle(net, Service.Connectivity));
-
- when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(false);
- when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true);
- // NVP provider does not provide Connectivity for this network
- assertFalse(element.canHandle(net, Service.Connectivity));
-
- when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true);
- // Only service Connectivity is supported
- assertFalse(element.canHandle(net, Service.Dhcp));
-
- }
-
- @Test
- public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
- final Network network = mock(Network.class);
- when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
- when(network.getId()).thenReturn(NETWORK_ID);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- mock(DeployDestination.class);
-
- final Domain dom = mock(Domain.class);
- when(dom.getName()).thenReturn("domain");
- final Account acc = mock(Account.class);
- when(acc.getAccountName()).thenReturn("accountname");
- final ReservationContext context = mock(ReservationContext.class);
- when(context.getDomain()).thenReturn(dom);
- when(context.getAccount()).thenReturn(acc);
- }
-
- @Test
- public void applyIpTest() throws ResourceUnavailableException {
- final Network network = mock(Network.class);
- when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
- when(network.getId()).thenReturn(NETWORK_ID);
- when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
-
- final NetworkOffering offering = mock(NetworkOffering.class);
- when(offering.getId()).thenReturn(NETWORK_ID);
- when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
- when(offering.getGuestType()).thenReturn(GuestType.Isolated);
-
- final List<PublicIpAddress> ipAddresses = new ArrayList<PublicIpAddress>();
- final PublicIpAddress pipReleased = mock(PublicIpAddress.class);
- final PublicIpAddress pipAllocated = mock(PublicIpAddress.class);
- final Ip ipReleased = new Ip("42.10.10.10");
- final Ip ipAllocated = new Ip("10.10.10.10");
- when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated);
- when(pipAllocated.getAddress()).thenReturn(ipAllocated);
- when(pipAllocated.getNetmask()).thenReturn("255.255.255.0");
- when(pipReleased.getState()).thenReturn(IpAddress.State.Releasing);
- when(pipReleased.getAddress()).thenReturn(ipReleased);
- when(pipReleased.getNetmask()).thenReturn("255.255.255.0");
- ipAddresses.add(pipAllocated);
- ipAddresses.add(pipReleased);
-
- final Set<Service> services = new HashSet<Service>();
- services.add(Service.SourceNat);
- services.add(Service.StaticNat);
- services.add(Service.PortForwarding);
-
- final List<NiciraNvpDeviceVO> deviceList = new ArrayList<NiciraNvpDeviceVO>();
- final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class);
- final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class);
- when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO);
- when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde");
- when(nndVO.getHostId()).thenReturn(NETWORK_ID);
- final HostVO hvo = mock(HostVO.class);
- when(hvo.getId()).thenReturn(NETWORK_ID);
- when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde");
- when(hostDao.findById(NETWORK_ID)).thenReturn(hvo);
- deviceList.add(nndVO);
- when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList);
-
- final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class);
- when(answer.getResult()).thenReturn(true);
- when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer);
-
- assertTrue(element.applyIps(network, ipAddresses, services));
-
- verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() {
- @Override
- public boolean matches(final Object argument) {
- final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument;
- if (command.getPublicCidrs().size() == 1)
- return true;
- return false;
- }
- }));
- }
-}
\ No newline at end of file
[49/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Use NSX specific RestClient in API implementation (NiciraNvpApi)
- Simplify public API to return Lists instead of NiciraNvpLists
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/09f71533
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/09f71533
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/09f71533
Branch: refs/heads/deploy-from-snapshot
Commit: 09f715337882c432e8731f81bce6490362e1cc2d
Parents: c6602ee
Author: Miguel Ferreira <mi...@me.com>
Authored: Sat Aug 22 17:30:58 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:17 2015 +0200
----------------------------------------------------------------------
.../cloud/network/nicira/NiciraConstants.java | 42 ++
.../com/cloud/network/nicira/NiciraNvpApi.java | 323 ++++++++-------
.../network/resource/NiciraNvpResource.java | 26 +-
...figurePortForwardingRulesCommandWrapper.java | 7 +-
...ciraNvpConfigurePublicIpsCommandWrapper.java | 9 +-
...vpConfigureStaticNatRulesCommandWrapper.java | 7 +-
...aNvpFindLogicalSwitchPortCommandWrapper.java | 7 +-
.../cloud/network/nicira/NiciraNvpApiIT.java | 202 ++++-----
.../cloud/network/nicira/NiciraNvpApiTest.java | 411 ++++++-------------
.../resource/NiciraNvpRequestWrapperTest.java | 7 +-
.../network/resource/NiciraNvpResourceTest.java | 72 +---
.../utils/rest/HttpUriRequestPathMatcher.java | 43 ++
12 files changed, 539 insertions(+), 617 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java
new file mode 100644
index 0000000..31adf9d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java
@@ -0,0 +1,42 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.nicira;
+
+public class NiciraConstants {
+
+ public static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile";
+ public static final String ACL_URI_PREFIX = "/ws.v1/acl";
+ public static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch";
+ public static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter";
+ public static final String LOGIN_URL = "/ws.v1/login";
+ public static final String CONTROL_CLUSTER_STATUS_URL = "/ws.v1/control-cluster/status";
+
+ public static final String ATTACHMENT_PATH_SEGMENT = "/attachment";
+ public static final String NAT_PATH_SEGMENT = "/nat";
+ public static final String LPORT_PATH_SEGMENT = "/lport";
+
+ public static final String ATTACHMENT_VIF_UUID_QUERY_PARAMETER_NAME = "attachment_vif_uuid";
+ public static final String ATTACHMENT_VLAN_PARAMETER = "attachment_vlan";
+ public static final String ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER = "attachment_gwsvc_uuid";
+ public static final String WILDCARD_QUERY_PARAMETER = "*";
+ public static final String UUID_QUERY_PARAMETER = "uuid";
+ public static final String FIELDS_QUERY_PARAMETER = "fields";
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
index 39262b6..093d90d 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
@@ -20,32 +20,39 @@
package com.cloud.network.nicira;
import java.lang.reflect.Type;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.CloseableHttpClient;
+
import com.cloud.utils.rest.CloudstackRESTException;
import com.cloud.utils.rest.RESTServiceConnector;
-import com.cloud.utils.rest.RESTValidationStrategy;
-import com.google.gson.JsonDeserializationContext;
+import com.google.common.base.Optional;
import com.google.gson.JsonDeserializer;
import com.google.gson.reflect.TypeToken;
@SuppressWarnings("rawtypes")
public class NiciraNvpApi {
- protected static final String GET_METHOD_TYPE = "get";
- protected static final String DELETE_METHOD_TYPE = "delete";
- protected static final String PUT_METHOD_TYPE = "put";
- protected static final String POST_METHOD_TYPE = "post";
- protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile";
- protected static final String ACL_URI_PREFIX = "/ws.v1/acl";
- private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch";
- private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter";
- private static final String LOGIN_URL = "/ws.v1/login";
+ private static final Optional<String> ABSENT = Optional.absent();
+
+ private static final String SWITCH_URI_PREFIX = NiciraConstants.SWITCH_URI_PREFIX;
+ private static final String ROUTER_URI_PREFIX = NiciraConstants.ROUTER_URI_PREFIX;
+
+ private static final String ATTACHMENT_PATH_SEGMENT = NiciraConstants.ATTACHMENT_PATH_SEGMENT;
+ private static final String NAT_PATH_SEGMENT = NiciraConstants.NAT_PATH_SEGMENT;
+ private static final String LPORT_PATH_SEGMENT = NiciraConstants.LPORT_PATH_SEGMENT;
+
+ private static final String ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER = NiciraConstants.ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER;
+ private static final String WILDCARD_QUERY_PARAMETER = NiciraConstants.WILDCARD_QUERY_PARAMETER;
+ private static final String UUID_QUERY_PARAMETER = NiciraConstants.UUID_QUERY_PARAMETER;
+ private static final String FIELDS_QUERY_PARAMETER = NiciraConstants.FIELDS_QUERY_PARAMETER;
+
+ private static final int DEFAULT_MAX_RETRIES = 5;
private final RESTServiceConnector restConnector;
@@ -57,8 +64,8 @@ public class NiciraNvpApi {
static {
prefixMap = new HashMap<Class, String>();
- prefixMap.put(SecurityProfile.class, SEC_PROFILE_URI_PREFIX);
- prefixMap.put(Acl.class, ACL_URI_PREFIX);
+ prefixMap.put(SecurityProfile.class, NiciraConstants.SEC_PROFILE_URI_PREFIX);
+ prefixMap.put(Acl.class, NiciraConstants.ACL_URI_PREFIX);
prefixMap.put(LogicalSwitch.class, SWITCH_URI_PREFIX);
prefixMap.put(LogicalRouter.class, ROUTER_URI_PREFIX);
@@ -73,32 +80,31 @@ public class NiciraNvpApi {
}.getType());
defaultListParams = new HashMap<String, String>();
- defaultListParams.put("fields", "*");
- }
-
- public NiciraNvpApi() {
- final List<Class<?>> classList = new ArrayList<Class<?>>();
- classList.add(NatRule.class);
- classList.add(RoutingConfig.class);
- final List<JsonDeserializer<?>> deserializerList = new ArrayList<JsonDeserializer<?>>();
- deserializerList.add(new NatRuleAdapter());
- deserializerList.add(new RoutingConfigAdapter());
-
- restConnector = new RESTServiceConnector(new RESTValidationStrategy(LOGIN_URL), classList, deserializerList);
+ defaultListParams.put(FIELDS_QUERY_PARAMETER, WILDCARD_QUERY_PARAMETER);
}
- public NiciraNvpApi(final String address, final String username, final String password) {
- this();
- restConnector.setControllerAddress(address);
- restConnector.setAdminCredentials(username, password);
- }
+ private NiciraNvpApi(final Builder builder) {
+ final Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap = new HashMap<>();
+ classToDeserializerMap.put(NatRule.class, new NatRuleAdapter());
+ classToDeserializerMap.put(RoutingConfig.class, new RoutingConfigAdapter());
- public void setControllerAddress(final String address) {
- restConnector.setControllerAddress(address);
+ final NiciraRestClient niciraRestClient = NiciraRestClient.create()
+ .client(builder.httpClient)
+ .clientContext(builder.httpClientContext)
+ .hostname(builder.host)
+ .username(builder.username)
+ .password(builder.password)
+ .loginUrl(NiciraConstants.LOGIN_URL)
+ .executionLimit(DEFAULT_MAX_RETRIES)
+ .build();
+ restConnector = RESTServiceConnector.create()
+ .classToDeserializerMap(classToDeserializerMap)
+ .client(niciraRestClient)
+ .build();
}
- public void setAdminCredentials(final String username, final String password) {
- restConnector.setAdminCredentials(username, password);
+ public static Builder create() {
+ return new Builder();
}
/**
@@ -123,8 +129,7 @@ public class NiciraNvpApi {
private <T> T createWithUri(final T entity, final String uri) throws NiciraNvpApiException {
T createdEntity;
try {
- createdEntity = restConnector.executeCreateObject(entity, new TypeToken<T>() {
- }.getType(), uri, Collections.<String, String> emptyMap());
+ createdEntity = restConnector.executeCreateObject(entity, uri, Collections.<String, String> emptyMap());
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
@@ -145,7 +150,7 @@ public class NiciraNvpApi {
Map<String, String> params = defaultListParams;
if (uuid.isPresent()) {
params = new HashMap<String, String>(defaultListParams);
- params.put("uuid", uuid);
+ params.put(UUID_QUERY_PARAMETER, uuid.get());
}
NiciraNvpList<T> entities;
@@ -159,7 +164,7 @@ public class NiciraNvpApi {
throw new NiciraNvpApiException("Unexpected response from API");
}
- return entities;
+ return entities.getResults();
}
/**
@@ -231,8 +236,8 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<SecurityProfile> findSecurityProfile() throws NiciraNvpApiException {
- return findSecurityProfile(null);
+ public List<SecurityProfile> findSecurityProfile() throws NiciraNvpApiException {
+ return find(ABSENT, SecurityProfile.class);
}
/**
@@ -244,8 +249,8 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<SecurityProfile> findSecurityProfile(final String uuid) throws NiciraNvpApiException {
- return find(uuid, SecurityProfile.class);
+ public List<SecurityProfile> findSecurityProfile(final String uuid) throws NiciraNvpApiException {
+ return find(Optional.fromNullable(uuid), SecurityProfile.class);
}
/**
@@ -286,7 +291,7 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<Acl> findAcl() throws NiciraNvpApiException {
+ public List<Acl> findAcl() throws NiciraNvpApiException {
return findAcl(null);
}
@@ -297,8 +302,8 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<Acl> findAcl(final String uuid) throws NiciraNvpApiException {
- return find(uuid, Acl.class);
+ public List<Acl> findAcl(final String uuid) throws NiciraNvpApiException {
+ return find(Optional.fromNullable(uuid), Acl.class);
}
/**
@@ -332,7 +337,7 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<LogicalSwitch> findLogicalSwitch() throws NiciraNvpApiException {
+ public List<LogicalSwitch> findLogicalSwitch() throws NiciraNvpApiException {
return findLogicalSwitch(null);
}
@@ -343,8 +348,8 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<LogicalSwitch> findLogicalSwitch(final String uuid) throws NiciraNvpApiException {
- return find(uuid, LogicalSwitch.class);
+ public List<LogicalSwitch> findLogicalSwitch(final String uuid) throws NiciraNvpApiException {
+ return find(Optional.fromNullable(uuid), LogicalSwitch.class);
}
/**
@@ -363,100 +368,81 @@ public class NiciraNvpApi {
}
public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
- return createWithUri(logicalSwitchPort, uri);
+ return createWithUri(logicalSwitchPort, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT));
}
public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPort.getUuid();
- updateWithUri(logicalSwitchPort, uri);
+ updateWithUri(logicalSwitchPort, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPort.getUuid().toString()));
}
public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment";
- updateWithUri(attachment, uri);
+ updateWithUri(attachment, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPortUuid) + ATTACHMENT_PATH_SEGMENT);
}
public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid;
- deleteWithUri(uri);
+ deleteWithUri(buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPortUuid));
}
public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("attachment_vif_uuid", vifAttachmentUuid);
- params.put("fields", "uuid");
+ final String uri = buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT);
+ final Map<String, String> params = buildBasicParametersMap(UUID_QUERY_PARAMETER);
+ params.put(NiciraConstants.ATTACHMENT_VIF_UUID_QUERY_PARAMETER_NAME, vifAttachmentUuid);
- NiciraNvpList<LogicalSwitchPort> lspl;
+ NiciraNvpList<LogicalSwitchPort> niciraList;
try {
- lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
- }.getType(), uri, params);
+ final Type niciraListType = new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
+ }.getType();
+ niciraList = restConnector.executeRetrieveObject(niciraListType, uri, params);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
- if (lspl == null || lspl.getResultCount() != 1) {
- throw new NiciraNvpApiException("Unexpected response from API");
+ final List<LogicalSwitchPort> lspl = niciraList.getResults();
+
+ final int listSize = lspl.size();
+ if (listSize != 1) {
+ throw new NiciraNvpApiException("Expected 1 LogicalSwitchPort, but got " + listSize);
}
- final LogicalSwitchPort lsp = lspl.getResults().get(0);
+ final LogicalSwitchPort lsp = lspl.get(0);
return lsp.getUuid();
}
public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException {
- final String uri = "/ws.v1/control-cluster/status";
- ControlClusterStatus ccs;
+ final String uri = NiciraConstants.CONTROL_CLUSTER_STATUS_URL;
try {
- ccs = restConnector.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
- }.getType(), uri, null);
+ return restConnector.executeRetrieveObject(ControlClusterStatus.class, uri, new HashMap<String, String>());
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
-
- return ccs;
}
- public NiciraNvpList<LogicalSwitchPort> findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("uuid", logicalSwitchPortUuid);
- params.put("fields", "uuid");
+ public List<LogicalSwitchPort> findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
+ final String uri = buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT);
+ final Map<String, String> params = buildBasicParametersMap(UUID_QUERY_PARAMETER);
+ params.put(UUID_QUERY_PARAMETER, logicalSwitchPortUuid);
- NiciraNvpList<LogicalSwitchPort> lspl;
try {
- lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
- }.getType(), uri, params);
+ final Type niciraListType = new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
+ }.getType();
+ return restConnector.<NiciraNvpList<LogicalSwitchPort>> executeRetrieveObject(niciraListType, uri, params).getResults();
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
-
- if (lspl == null) {
- throw new NiciraNvpApiException("Unexpected response from API");
- }
-
- return lspl;
}
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("uuid", logicalRouterPortUuid);
- params.put("fields", "uuid");
+ public List<LogicalRouterPort> findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
+ final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT);
+ final Map<String, String> params = buildBasicParametersMap(UUID_QUERY_PARAMETER);
+ params.put(UUID_QUERY_PARAMETER, logicalRouterPortUuid);
- NiciraNvpList<LogicalRouterPort> lrpl;
try {
- lrpl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
- }.getType(), uri, params);
+ final Type niciraListType = new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
+ }.getType();
+ return restConnector.<NiciraNvpList<LogicalRouterPort>> executeRetrieveObject(niciraListType, uri, params).getResults();
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
-
- if (lrpl == null) {
- throw new NiciraNvpApiException("Unexpected response from API");
- }
-
- return lrpl;
}
public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException {
@@ -469,7 +455,7 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<LogicalRouter> findLogicalRouter() throws NiciraNvpApiException {
+ public List<LogicalRouter> findLogicalRouter() throws NiciraNvpApiException {
return findLogicalRouter(null);
}
@@ -480,12 +466,12 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- public NiciraNvpList<LogicalRouter> findLogicalRouter(final String uuid) throws NiciraNvpApiException {
- return find(uuid, LogicalRouter.class);
+ public List<LogicalRouter> findLogicalRouter(final String uuid) throws NiciraNvpApiException {
+ return find(Optional.fromNullable(uuid), LogicalRouter.class);
}
public LogicalRouter findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
- return findLogicalRouter(logicalRouterUuid).getResults().get(0);
+ return findLogicalRouter(logicalRouterUuid).get(0);
}
public void updateLogicalRouter(final LogicalRouter logicalRouter, final String logicalRouterUuid) throws NiciraNvpApiException {
@@ -493,100 +479,149 @@ public class NiciraNvpApi {
}
public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid;
- deleteWithUri(uri);
+ deleteWithUri(buildLogicalRouterUri(logicalRouterUuid));
}
public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- return createWithUri(logicalRouterPort, uri);
+ return createWithUri(logicalRouterPort, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT));
}
public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid;
- deleteWithUri(uri);
+ deleteWithUri(buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPortUuid));
}
public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid();
- updateWithUri(logicalRouterPort, uri);
+ updateWithUri(logicalRouterPort, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPort.getUuid().toString()));
}
public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment";
- updateWithUri(attachment, uri);
+ updateWithUri(attachment, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPortUuid) + ATTACHMENT_PATH_SEGMENT);
}
public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
- return createWithUri(natRule, uri);
+ return createWithUri(natRule, buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT));
}
public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid();
- updateWithUri(natRule, uri);
+ updateWithUri(natRule, buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT, natRule.getUuid().toString()));
}
public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString();
- deleteWithUri(uri);
+ deleteWithUri(buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT, natRuleUuid.toString()));
}
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, final long vlanId)
- throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("attachment_gwsvc_uuid", gatewayServiceUuid);
- params.put("attachment_vlan", Long.toString(vlanId));
- params.put("fields", "*");
+ public List<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, final long vlanId)
+ throws NiciraNvpApiException {
+ final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT);
+ final Map<String, String> params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER);
+ params.put(ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER, gatewayServiceUuid);
+ params.put(NiciraConstants.ATTACHMENT_VLAN_PARAMETER, Long.toString(vlanId));
try {
- return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
- }.getType(), uri, params);
+ final Type niciraListType = new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
+ }.getType();
+ return restConnector.<NiciraNvpList<LogicalRouterPort>> executeRetrieveObject(niciraListType, uri, params).getResults();
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
}
- public NiciraNvpList<NatRule> findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("fields", "*");
+ public List<NatRule> findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
+ final String uri = buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT);
+ final Map<String, String> params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER);
try {
- return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<NatRule>>() {
- }.getType(), uri, params);
+ final Type niciraListType = new TypeToken<NiciraNvpList<NatRule>>() {
+ }.getType();
+ return restConnector.<NiciraNvpList<NatRule>> executeRetrieveObject(niciraListType, uri, params).getResults();
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
}
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid)
- throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("fields", "*");
- params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid);
+ public List<LogicalRouterPort> findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid)
+ throws NiciraNvpApiException {
+ final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT);
+ final Map<String, String> params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER);
+ params.put(ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER, l3GatewayServiceUuid);
try {
- return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
- }.getType(), uri, params);
+ final Type niciraListType = new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
+ }.getType();
+ return restConnector.<NiciraNvpList<LogicalRouterPort>> executeRetrieveObject(niciraListType, uri, params).getResults();
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
}
+ private static Map<String, String> buildBasicParametersMap(final String fieldsQueryValue) {
+ final Map<String, String> params = new HashMap<String, String>();
+ params.put(FIELDS_QUERY_PARAMETER, fieldsQueryValue);
+ return params;
+ }
+ private static String buildUri(final String uriPrefix, final String uuid) {
+ return uriPrefix + "/" + uuid;
+ }
+ private static String buildLogicalSwitchUri(final String logicalSwitchUuid) {
+ return buildUri(SWITCH_URI_PREFIX, logicalSwitchUuid);
+ }
+ private static String buildLogicalSwitchElementUri(final String logicalSwitchUuid, final String logicalElementType) {
+ return buildLogicalSwitchUri(logicalSwitchUuid) + logicalElementType;
+ }
+ private static String buildLogicalSwitchElementUri(final String logicalSwitchUuid, final String logicalElementType, final String elementUuid) {
+ return buildLogicalSwitchElementUri(logicalSwitchUuid, logicalElementType) + "/" + elementUuid.toString();
}
+ private static String buildLogicalRouterUri(final String logicalRouterUuid) {
+ return buildUri(ROUTER_URI_PREFIX, logicalRouterUuid);
+ }
+ private static String buildLogicalRouterElementUri(final String logicalRouterUuid, final String logicalElementType) {
+ return buildLogicalRouterUri(logicalRouterUuid) + logicalElementType;
+ }
+
+ private static String buildLogicalRouterElementUri(final String logicalRouterUuid, final String logicalRouterElementType, final String elementUuid) {
+ return buildLogicalRouterElementUri(logicalRouterUuid, logicalRouterElementType) + "/" + elementUuid.toString();
+ }
+ public static class Builder {
+ private String host;
+ private String username;
+ private String password;
+ private CloseableHttpClient httpClient;
+ private HttpClientContext httpClientContext = HttpClientContext.create();
+ public Builder host(final String host) {
+ this.host = host;
+ return this;
+ }
+
+ public Builder username(final String username) {
+ this.username = username;
+ return this;
+ }
+ public Builder password(final String password) {
+ this.password = password;
+ return this;
+ }
+
+ public Builder httpClient(final CloseableHttpClient httpClient) {
+ this.httpClient = httpClient;
+ return this;
+ }
+
+ public Builder httpClientContext(final HttpClientContext httpClientContext) {
+ this.httpClientContext = httpClientContext;
+ return this;
+ }
+ public NiciraNvpApi build() {
+ return new NiciraNvpApi(this);
}
}
}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
index af5812d..d6355b2 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java
@@ -19,6 +19,9 @@
package com.cloud.network.resource;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
import java.util.Map;
import javax.naming.ConfigurationException;
@@ -42,6 +45,8 @@ import com.cloud.network.nicira.NiciraNvpApiException;
import com.cloud.network.nicira.SourceNatRule;
import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.ServerResource;
+import com.cloud.utils.rest.CloudstackRESTException;
+import com.cloud.utils.rest.HttpClientHelper;
public class NiciraNvpResource implements ServerResource {
@@ -49,6 +54,7 @@ public class NiciraNvpResource implements ServerResource {
public static final int NAME_MAX_LEN = 40;
public static final int NUM_RETRIES = 2;
+ private static final int MAX_REDIRECTS = 5;
private String name;
private String guid;
@@ -58,8 +64,16 @@ public class NiciraNvpResource implements ServerResource {
private NiciraNvpUtilities niciraNvpUtilities;
private CommandRetryUtility retryUtility;
- protected NiciraNvpApi createNiciraNvpApi() {
- return new NiciraNvpApi();
+ protected NiciraNvpApi createNiciraNvpApi(final String host, final String username, final String password) throws CloudstackRESTException {
+ try {
+ return NiciraNvpApi.create().host(host).username(username).password(password).httpClient(HttpClientHelper.createHttpClient(MAX_REDIRECTS)).build();
+ } catch (final KeyManagementException e) {
+ throw new CloudstackRESTException("Could not create HTTP client", e);
+ } catch (final NoSuchAlgorithmException e) {
+ throw new CloudstackRESTException("Could not create HTTP client", e);
+ } catch (final KeyStoreException e) {
+ throw new CloudstackRESTException("Could not create HTTP client", e);
+ }
}
@Override
@@ -99,9 +113,11 @@ public class NiciraNvpResource implements ServerResource {
retryUtility = CommandRetryUtility.getInstance();
retryUtility.setServerResource(this);
- niciraNvpApi = createNiciraNvpApi();
- niciraNvpApi.setControllerAddress(ip);
- niciraNvpApi.setAdminCredentials(adminuser, adminpass);
+ try {
+ niciraNvpApi = createNiciraNvpApi(ip, adminuser, adminpass);
+ } catch (final CloudstackRESTException e) {
+ throw new ConfigurationException("Could not create a Nicira Nvp API client: " + e.getMessage());
+ }
return true;
}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
index 35ab04c..ae0d4ba 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
@@ -21,6 +21,8 @@ package com.cloud.network.resource.wrapper;
import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+import java.util.List;
+
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
@@ -30,7 +32,6 @@ import com.cloud.agent.api.to.PortForwardingRuleTO;
import com.cloud.network.nicira.NatRule;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.resource.NiciraNvpResource;
import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
@@ -45,7 +46,7 @@ public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends C
public Answer execute(final ConfigurePortForwardingRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
try {
- final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
+ final List<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
// Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
// A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
// Any other SourceNat rule should have a corresponding DestinationNat rule
@@ -66,7 +67,7 @@ public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends C
NatRule incoming = null;
NatRule outgoing = null;
- for (final NatRule storedRule : existingRules.getResults()) {
+ for (final NatRule storedRule : existingRules) {
if (storedRule.equalsIgnoreUuid(rulepair[1])) {
// The outgoing rule exists
outgoing = storedRule;
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
index 9d4c711..d584629 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
@@ -21,13 +21,14 @@ package com.cloud.network.resource.wrapper;
import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+import java.util.List;
+
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
import com.cloud.network.nicira.LogicalRouterPort;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.resource.NiciraNvpResource;
import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
@@ -41,11 +42,11 @@ public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrap
final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
try {
- final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid());
- if (ports.getResultCount() != 1) {
+ final List<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid());
+ if (ports.size() != 1) {
return new ConfigurePublicIpsOnLogicalRouterAnswer(command, false, "No logical router ports found, unable to set ip addresses");
}
- final LogicalRouterPort lrp = ports.getResults().get(0);
+ final LogicalRouterPort lrp = ports.get(0);
lrp.setIpAddresses(command.getPublicCidrs());
niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp);
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
index e576db9..ae59784 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
@@ -21,6 +21,8 @@ package com.cloud.network.resource.wrapper;
import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+import java.util.List;
+
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
@@ -30,7 +32,6 @@ import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.network.nicira.NatRule;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.resource.NiciraNvpResource;
import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
@@ -46,7 +47,7 @@ public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends Comman
final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
try {
- final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
+ final List<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
// Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
// A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
// Any other SourceNat rule should have a corresponding DestinationNat rule
@@ -58,7 +59,7 @@ public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends Comman
NatRule incoming = null;
NatRule outgoing = null;
- for (final NatRule storedRule : existingRules.getResults()) {
+ for (final NatRule storedRule : existingRules) {
if (storedRule.equalsIgnoreUuid(rulepair[1])) {
// The outgoing rule exists
outgoing = storedRule;
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
index ea68538..8c11427 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
@@ -21,13 +21,14 @@ package com.cloud.network.resource.wrapper;
import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+import java.util.List;
+
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
import com.cloud.agent.api.FindLogicalSwitchPortCommand;
import com.cloud.network.nicira.LogicalSwitchPort;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.resource.NiciraNvpResource;
import com.cloud.network.utils.CommandRetryUtility;
import com.cloud.resource.CommandWrapper;
@@ -44,8 +45,8 @@ public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandW
final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
try {
- final NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
- if (ports.getResultCount() == 0) {
+ final List<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
+ if (ports.size() == 0) {
return new FindLogicalSwitchPortAnswer(command, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null);
} else {
return new FindLogicalSwitchPortAnswer(command, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09f71533/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
index 3bb4b9d..a95a8d6 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java
@@ -22,16 +22,15 @@ package com.cloud.network.nicira;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-import java.util.Properties;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import com.cloud.utils.PropertiesUtil;
+import com.cloud.utils.rest.HttpClientHelper;
public class NiciraNvpApiIT {
@@ -40,18 +39,23 @@ public class NiciraNvpApiIT {
protected long timestamp = System.currentTimeMillis();
@Before
- public void setup() throws IOException {
- final Properties properties = PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties"));
- api = new NiciraNvpApi();
- api.setControllerAddress(properties.getProperty("nvp.host"));
- api.setAdminCredentials(properties.getProperty("nvp.admin.user"),
- properties.getProperty("nvp.admin.pwd"));
+ public void setup() throws Exception {
+ PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties"));
+ final String host = System.getProperty("nvp.host");
+ final String user = System.getProperty("nvp.admin.user");
+ final String pass = System.getProperty("nvp.admin.pwd");
+ api = NiciraNvpApi.create()
+ .host(host)
+ .username(user)
+ .password(pass)
+ .httpClient(HttpClientHelper.createHttpClient(5))
+ .build();
}
@Test
- public void testCRUDSecurityProfile() throws NiciraNvpApiException {
+ public void testCRUDSecurityProfile() {
SecurityProfile sProfile = new SecurityProfile();
- sProfile.setDisplayName("SecProfile"+timestamp);
+ sProfile.setDisplayName("SecProfile" + timestamp);
final List<SecurityRule> egressRules = new ArrayList<SecurityRule>();
sProfile.setLogicalPortEgressRules(egressRules);
@@ -73,27 +77,23 @@ public class NiciraNvpApiIT {
sProfile = api.createSecurityProfile(sProfile);
// We can now update the new entity
- sProfile.setDisplayName("UpdatedSecProfile"+timestamp);
+ sProfile.setDisplayName("UpdatedSecProfile" + timestamp);
api.updateSecurityProfile(sProfile, sProfile.getUuid());
// Read them all
- NiciraNvpList<SecurityProfile> profiles = api.findSecurityProfile();
+ List<SecurityProfile> profiles = api.findSecurityProfile();
SecurityProfile scInList = null;
- for(final SecurityProfile iProfile : profiles.getResults()) {
+ for (final SecurityProfile iProfile : profiles) {
if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) {
scInList = iProfile;
}
}
- assertEquals("Read a Security Profile different from the one just created and updated",
- sProfile, scInList);
+ assertEquals("Read a Security Profile different from the one just created and updated", sProfile, scInList);
// Read them filtered by uuid (get one)
profiles = api.findSecurityProfile(sProfile.getUuid());
- assertEquals("Read a Security Profile different from the one just created and updated",
- sProfile,
- profiles.getResults().get(0));
- assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item",
- 1, profiles.getResults().size());
+ assertEquals("Read a Security Profile different from the one just created and updated", sProfile, profiles.get(0));
+ assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", 1, profiles.size());
// We can now delete the new entity
api.deleteSecurityProfile(sProfile.getUuid());
@@ -104,25 +104,21 @@ public class NiciraNvpApiIT {
}
@Test
- public void testCRUDAcl() throws NiciraNvpApiException {
+ public void testCRUDAcl() {
Acl acl = new Acl();
- acl.setDisplayName("Acl"+timestamp);
+ acl.setDisplayName("Acl" + timestamp);
// Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type
// Note that if the protocol is 1 (ICMP) then you cannot put ports
final List<AclRule> egressRules = new ArrayList<AclRule>();
acl.setLogicalPortEgressRules(egressRules);
- egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null,
- "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
- egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null,
- "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
+ egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
+ egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
final List<AclRule> ingressRules = new ArrayList<AclRule>();
acl.setLogicalPortIngressRules(ingressRules);
- ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null,
- "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
- ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null,
- "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
+ ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
+ ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));
final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
acl.setTags(tags);
@@ -134,27 +130,23 @@ public class NiciraNvpApiIT {
acl = api.createAcl(acl);
// We can now update the new entity
- acl.setDisplayName("UpdatedAcl"+timestamp);
+ acl.setDisplayName("UpdatedAcl" + timestamp);
api.updateAcl(acl, acl.getUuid());
// Read them all
- NiciraNvpList<Acl> acls = api.findAcl();
+ List<Acl> acls = api.findAcl();
Acl scInList = null;
- for(final Acl iAcl : acls.getResults()) {
+ for (final Acl iAcl : acls) {
if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) {
scInList = iAcl;
}
}
- assertEquals("Read a ACL different from the one just created and updated",
- acl, scInList);
+ assertEquals("Read a ACL different from the one just created and updated", acl, scInList);
// Read them filtered by uuid (get one)
acls = api.findAcl(acl.getUuid());
- assertEquals("Read a ACL different from the one just created and updated",
- acl,
- acls.getResults().get(0));
- assertEquals("Read a ACL filtered by unique id (UUID) with more than one item",
- 1, acls.getResults().size());
+ assertEquals("Read a ACL different from the one just created and updated", acl, acls.get(0));
+ assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", 1, acls.size());
// We can now delete the new entity
api.deleteAcl(acl.getUuid());
@@ -165,9 +157,9 @@ public class NiciraNvpApiIT {
}
@Test
- public void testCRUDLogicalSwitch() throws NiciraNvpApiException {
+ public void testCRUDLogicalSwitch() throws Exception {
LogicalSwitch logicalSwitch = new LogicalSwitch();
- logicalSwitch.setDisplayName("LogicalSwitch"+timestamp);
+ logicalSwitch.setDisplayName("LogicalSwitch" + timestamp);
logicalSwitch.setPortIsolationEnabled(true);
logicalSwitch.setReplicationMode("service");
logicalSwitch.setTags(new ArrayList<NiciraNvpTag>());
@@ -175,78 +167,65 @@ public class NiciraNvpApiIT {
// In the creation we don't get to specify UUID, href or schema: they don't exist yet
- try {
- logicalSwitch = api.createLogicalSwitch(logicalSwitch);
+ logicalSwitch = api.createLogicalSwitch(logicalSwitch);
- // We can now update the new entity
- logicalSwitch.setDisplayName("UpdatedLogicalSwitch"+timestamp);
- api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid());
+ // We can now update the new entity
+ logicalSwitch.setDisplayName("UpdatedLogicalSwitch" + timestamp);
+ api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid());
- // Read them all
- NiciraNvpList<LogicalSwitch> logicalSwitches = api.findLogicalSwitch();
- for(final LogicalSwitch iLogicalSwitch : logicalSwitches.getResults()) {
- if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) {
- assertEquals("Read a LogicalSwitch different from the one just created and updated",
- logicalSwitch, iLogicalSwitch);
- }
+ // Read them all
+ List<LogicalSwitch> logicalSwitches = api.findLogicalSwitch();
+ for (final LogicalSwitch iLogicalSwitch : logicalSwitches) {
+ if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) {
+ assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, iLogicalSwitch);
}
+ }
- // Read them filtered by uuid (get one)
- logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid());
- assertEquals("Read a LogicalSwitch different from the one just created and updated",
- logicalSwitch,
- logicalSwitches.getResults().get(0));
- assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item",
- 1, logicalSwitches.getResults().size());
-
- // Before deleting the test LogicalSwitch, test its ports
- final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
- tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
+ // Read them filtered by uuid (get one)
+ logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid());
+ assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, logicalSwitches.get(0));
+ assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item", 1, logicalSwitches.size());
- LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort"+timestamp, tags, true);
- logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
+ // Before deleting the test LogicalSwitch, test its ports
+ final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+ tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
- logicalSwitchPort.setDisplayName("UpdatedLSwitchPort"+timestamp);
- api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
+ LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort" + timestamp, tags, true);
+ logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
- final NiciraNvpList<LogicalSwitchPort> logicalSwitchePorts =
- api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
- for(final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts.getResults()) {
- if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) {
- assertEquals("Read a LogicalSwitchPort different from the one just created and updated",
- logicalSwitchPort, iLSwitchPort);
- }
+ logicalSwitchPort.setDisplayName("UpdatedLSwitchPort" + timestamp);
+ api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
+
+ final List<LogicalSwitchPort> logicalSwitchePorts = api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
+ for (final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts) {
+ if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) {
+ assertEquals("Read a LogicalSwitchPort different from the one just created and updated", logicalSwitchPort, iLSwitchPort);
}
+ }
- // And finally test attachments
- final String attachmentUuid = UUID.randomUUID().toString();
- final VifAttachment vifAttachment = new VifAttachment(attachmentUuid);
- api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(),
- vifAttachment);
+ // And finally test attachments
+ final String attachmentUuid = UUID.randomUUID().toString();
+ final VifAttachment vifAttachment = new VifAttachment(attachmentUuid);
+ api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), vifAttachment);
- assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
- api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()),
- logicalSwitchPort.getUuid());
+ assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
+ api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()), logicalSwitchPort.getUuid());
- api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
+ api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
- // We can now delete the new entity
- api.deleteLogicalSwitch(logicalSwitch.getUuid());
- } catch (final NiciraNvpApiException e) {
- e.printStackTrace();
- assertTrue("Errors in LogicalSwitch CRUD", false);
- }
+ // We can now delete the new entity
+ api.deleteLogicalSwitch(logicalSwitch.getUuid());
}
@Test
- public void testCRUDLogicalRouter() throws NiciraNvpApiException {
+ public void testCRUDLogicalRouter() {
LogicalRouter logicalRouter = new LogicalRouter();
- logicalRouter.setDisplayName("LogicalRouter"+timestamp);
+ logicalRouter.setDisplayName("LogicalRouter" + timestamp);
logicalRouter.setDistributed(true);
logicalRouter.setNatSynchronizationEnabled(true);
logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE);
final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig(
- new RouterNextHop("192.168.10.20"));
+ new RouterNextHop("192.168.10.20"));
logicalRouter.setRoutingConfig(routingConfig);
// In the creation we don't get to specify UUID, href or schema: they don't exist yet
@@ -255,37 +234,32 @@ public class NiciraNvpApiIT {
logicalRouter = api.createLogicalRouter(logicalRouter);
// We can now update the new entity
- logicalRouter.setDisplayName("UpdatedLogicalSwitch"+timestamp);
+ logicalRouter.setDisplayName("UpdatedLogicalSwitch" + timestamp);
api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid());
// Read them all
- NiciraNvpList<LogicalRouter> logicalRouters = api.findLogicalRouter();
+ List<LogicalRouter> logicalRouters = api.findLogicalRouter();
LogicalRouter lsInList = null;
- for(final LogicalRouter iLogicalRouter : logicalRouters.getResults()) {
+ for (final LogicalRouter iLogicalRouter : logicalRouters) {
if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) {
lsInList = iLogicalRouter;
}
}
- assertEquals("Read a LogicalRouter different from the one just created and updated",
- logicalRouter, lsInList);
+ assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, lsInList);
// Read them filtered by uuid (get one)
logicalRouters = api.findLogicalRouter(logicalRouter.getUuid());
- assertEquals("Read a LogicalRouter different from the one just created and updated",
- logicalRouter,
- logicalRouters.getResults().get(0));
- assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item",
- 1, logicalRouters.getResults().size());
+ assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, logicalRouters.get(0));
+ assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item", 1, logicalRouters.size());
- assertEquals("", logicalRouters.getResults().get(0),
- api.findOneLogicalRouterByUuid(logicalRouter.getUuid()));
+ assertEquals(logicalRouters.get(0), api.findOneLogicalRouterByUuid(logicalRouter.getUuid()));
// Before deleting the test LogicalRouter, test its ports
final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
LogicalRouterPort logicalRouterPort = new LogicalRouterPort();
- logicalRouterPort.setDisplayName("LRouterPort"+timestamp);
+ logicalRouterPort.setDisplayName("LRouterPort" + timestamp);
logicalRouterPort.setTags(tags);
logicalRouterPort.setAdminStatusEnabled(true);
logicalRouterPort.setPortno(1024);
@@ -296,15 +270,13 @@ public class NiciraNvpApiIT {
logicalRouterPort.setIpAddresses(ipAddresses);
logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
- logicalRouterPort.setDisplayName("UpdatedLRouterPort"+timestamp);
+ logicalRouterPort.setDisplayName("UpdatedLRouterPort" + timestamp);
api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
- final NiciraNvpList<LogicalRouterPort> logicalRouterePorts =
- api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid());
- for(final LogicalRouterPort iLRouterPort : logicalRouterePorts.getResults()) {
+ final List<LogicalRouterPort> logicalRouterePorts = api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid());
+ for (final LogicalRouterPort iLRouterPort : logicalRouterePorts) {
if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) {
- assertEquals("Read a LogicalRouterPort different from the one just created and updated",
- logicalRouterPort, iLRouterPort);
+ assertEquals("Read a LogicalRouterPort different from the one just created and updated", logicalRouterPort, iLRouterPort);
}
}
@@ -339,8 +311,8 @@ public class NiciraNvpApiIT {
public void testGetControlClusterStatus() throws NiciraNvpApiException {
final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus();
final String clusterStatus = controlClusterStatus.getClusterStatus();
- final boolean correctStatus = (clusterStatus.equalsIgnoreCase("stable") ||
- clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"));
+ final boolean correctStatus = clusterStatus.equalsIgnoreCase("stable") ||
+ clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable");
assertTrue("Not recognizable cluster status", correctStatus);
}
[40/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java
deleted file mode 100644
index 6cc8f5d..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java
+++ /dev/null
@@ -1,108 +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 com.cloud.api.commands;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.inject.Inject;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.ApiErrorCode;
-import org.apache.cloudstack.api.BaseListCmd;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.api.response.ListResponse;
-import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
-
-import com.cloud.api.response.NiciraNvpDeviceResponse;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.ResourceAllocationException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.network.element.NiciraNvpElementService;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-@APICommand(name = "listNiciraNvpDevices", responseObject = NiciraNvpDeviceResponse.class, description = "Lists Nicira NVP devices",
- requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
-public class ListNiciraNvpDevicesCmd extends BaseListCmd {
- private static final String s_name = "listniciranvpdeviceresponse";
-
- @Inject
- protected NiciraNvpElementService niciraNvpElementService;
-
- /////////////////////////////////////////////////////
- //////////////// API parameters /////////////////////
- /////////////////////////////////////////////////////
-
- @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "the Physical Network ID")
- private Long physicalNetworkId;
-
- @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID, type = CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, description = "nicira nvp device ID")
- private Long niciraNvpDeviceId;
-
- /////////////////////////////////////////////////////
- /////////////////// Accessors ///////////////////////
- /////////////////////////////////////////////////////
-
- public Long getNiciraNvpDeviceId() {
- return niciraNvpDeviceId;
- }
-
- public Long getPhysicalNetworkId() {
- return physicalNetworkId;
- }
-
- /////////////////////////////////////////////////////
- /////////////// API Implementation///////////////////
- /////////////////////////////////////////////////////
-
- @Override
- public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {
- try {
- List<NiciraNvpDeviceVO> niciraDevices = niciraNvpElementService.listNiciraNvpDevices(this);
- ListResponse<NiciraNvpDeviceResponse> response = new ListResponse<NiciraNvpDeviceResponse>();
- List<NiciraNvpDeviceResponse> niciraDevicesResponse = new ArrayList<NiciraNvpDeviceResponse>();
-
- if (niciraDevices != null && !niciraDevices.isEmpty()) {
- for (NiciraNvpDeviceVO niciraDeviceVO : niciraDevices) {
- NiciraNvpDeviceResponse niciraDeviceResponse = niciraNvpElementService.createNiciraNvpDeviceResponse(niciraDeviceVO);
- niciraDevicesResponse.add(niciraDeviceResponse);
- }
- }
-
- response.setResponses(niciraDevicesResponse);
- response.setResponseName(getCommandName());
- setResponseObject(response);
- } catch (InvalidParameterValueException invalidParamExcp) {
- throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
- } catch (CloudRuntimeException runtimeExcp) {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
- }
- }
-
- @Override
- public String getCommandName() {
- return s_name;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java
deleted file mode 100644
index 46287aa..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java
+++ /dev/null
@@ -1,89 +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 com.cloud.api.response;
-
-import com.google.gson.annotations.SerializedName;
-
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.BaseResponse;
-import org.apache.cloudstack.api.EntityReference;
-
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.serializer.Param;
-
-@EntityReference(value = NiciraNvpDeviceVO.class)
-public class NiciraNvpDeviceResponse extends BaseResponse {
- @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID)
- @Param(description = "device id of the Nicire Nvp")
- private String id;
-
- @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID)
- @Param(description = "the physical network to which this Nirica Nvp belongs to")
- private String physicalNetworkId;
-
- @SerializedName(ApiConstants.PROVIDER)
- @Param(description = "name of the provider")
- private String providerName;
-
- @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_NAME)
- @Param(description = "device name")
- private String deviceName;
-
- @SerializedName(ApiConstants.HOST_NAME)
- @Param(description = "the controller Ip address")
- private String hostName;
-
- @SerializedName(ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID)
- @Param(description = "the transport zone Uuid")
- private String transportZoneUuid;
-
- @SerializedName(ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID)
- @Param(description = "this L3 gateway service Uuid")
- private String l3GatewayServiceUuid;
-
- public void setId(String nvpDeviceId) {
- this.id = nvpDeviceId;
- }
-
- public void setPhysicalNetworkId(final String physicalNetworkId) {
- this.physicalNetworkId = physicalNetworkId;
- }
-
- public void setProviderName(final String providerName) {
- this.providerName = providerName;
- }
-
- public void setDeviceName(final String deviceName) {
- this.deviceName = deviceName;
- }
-
- public void setHostName(final String hostName) {
- this.hostName = hostName;
- }
-
- public void setTransportZoneUuid(final String transportZoneUuid) {
- this.transportZoneUuid = transportZoneUuid;
- }
-
- public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) {
- this.l3GatewayServiceUuid = l3GatewayServiceUuid;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java
deleted file mode 100644
index 431e855..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java
+++ /dev/null
@@ -1,99 +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 com.cloud.network;
-
-import java.util.UUID;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.apache.cloudstack.api.InternalIdentity;
-
-@Entity
-@Table(name = "external_nicira_nvp_devices")
-public class NiciraNvpDeviceVO implements InternalIdentity {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "id")
- private long id;
-
- @Column(name = "uuid")
- private String uuid;
-
- @Column(name = "host_id")
- private long hostId;
-
- @Column(name = "physical_network_id")
- private long physicalNetworkId;
-
- @Column(name = "provider_name")
- private String providerName;
-
- @Column(name = "device_name")
- private String deviceName;
-
- public NiciraNvpDeviceVO() {
- uuid = UUID.randomUUID().toString();
- }
-
- public NiciraNvpDeviceVO(final long hostId, final long physicalNetworkId, final String providerName, final String deviceName) {
- super();
- this.hostId = hostId;
- this.physicalNetworkId = physicalNetworkId;
- this.providerName = providerName;
- this.deviceName = deviceName;
- uuid = UUID.randomUUID().toString();
- }
-
- @Override
- public long getId() {
- return id;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
- public long getPhysicalNetworkId() {
- return physicalNetworkId;
- }
-
- public long getHostId() {
- return hostId;
- }
-
- public String getProviderName() {
- return providerName;
- }
-
- public String getDeviceName() {
- return deviceName;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java
deleted file mode 100644
index 9b13780..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java
+++ /dev/null
@@ -1,87 +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 com.cloud.network;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.apache.cloudstack.api.InternalIdentity;
-
-@Entity
-@Table(name = "nicira_nvp_nic_map")
-public class NiciraNvpNicMappingVO implements InternalIdentity {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "id")
- private long id;
-
- @Column(name = "logicalswitch")
- private String logicalSwitchUuid;
-
- @Column(name = "logicalswitchport")
- private String logicalSwitchPortUuid;
-
- @Column(name = "nic")
- private String nicUuid;
-
- public NiciraNvpNicMappingVO() {
- }
-
- public NiciraNvpNicMappingVO(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final String nicUuid) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- this.logicalSwitchPortUuid = logicalSwitchPortUuid;
- this.nicUuid = nicUuid;
- }
-
- public String getLogicalSwitchUuid() {
- return logicalSwitchUuid;
- }
-
- public void setLogicalSwitchUuid(final String logicalSwitchUuid) {
- this.logicalSwitchUuid = logicalSwitchUuid;
- }
-
- public String getLogicalSwitchPortUuid() {
- return logicalSwitchPortUuid;
- }
-
- public void setLogicalSwitchPortUuid(final String logicalSwitchPortUuid) {
- this.logicalSwitchPortUuid = logicalSwitchPortUuid;
- }
-
- public String getNicUuid() {
- return nicUuid;
- }
-
- public void setNicUuid(String nicUuid) {
- this.nicUuid = nicUuid;
- }
-
- @Override
- public long getId() {
- return id;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java
deleted file mode 100644
index 9fae3cd..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java
+++ /dev/null
@@ -1,85 +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 com.cloud.network;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.apache.cloudstack.api.InternalIdentity;
-
-@Entity
-@Table(name = "nicira_nvp_router_map")
-public class NiciraNvpRouterMappingVO implements InternalIdentity {
- //FIXME the ddl for this table should be in one of the upgrade scripts
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "id")
- private long id;
-
- @Column(name = "logicalrouter_uuid")
- private String logicalRouterUuid;
-
- @Column(name = "network_id")
- private long networkId;
-
- public NiciraNvpRouterMappingVO() {
- }
-
- public NiciraNvpRouterMappingVO(final String logicalRouterUuid, final long networkId) {
- this.logicalRouterUuid = logicalRouterUuid;
- this.networkId = networkId;
- }
-
- public NiciraNvpRouterMappingVO(final long id, final String logicalRouterUuid, final long networkId) {
- this.id = id;
- this.logicalRouterUuid = logicalRouterUuid;
- this.networkId = networkId;
- }
-
- @Override
- public long getId() {
- return id;
- }
-
- public void setId(final long id) {
- this.id = id;
- }
-
- public String getLogicalRouterUuid() {
- return logicalRouterUuid;
- }
-
- public void setLogicalRouterUuid(final String logicalRouterUuid) {
- this.logicalRouterUuid = logicalRouterUuid;
- }
-
- public long getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(final long networkId) {
- this.networkId = networkId;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDao.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDao.java
deleted file mode 100644
index f2a9754..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDao.java
+++ /dev/null
@@ -1,35 +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 com.cloud.network.dao;
-
-import java.util.List;
-
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.utils.db.GenericDao;
-
-public interface NiciraNvpDao extends GenericDao<NiciraNvpDeviceVO, Long> {
- /**
- * list all the nicira nvp devices added in to this physical network
- * @param physicalNetworkId physical Network Id
- * @return list of NiciraNvpDeviceVO for this physical network.
- */
- List<NiciraNvpDeviceVO> listByPhysicalNetwork(long physicalNetworkId);
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java
deleted file mode 100644
index 3144c81..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java
+++ /dev/null
@@ -1,53 +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 com.cloud.network.dao;
-
-import java.util.List;
-
-import javax.ejb.Local;
-
-import org.springframework.stereotype.Component;
-
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.utils.db.GenericDaoBase;
-import com.cloud.utils.db.SearchBuilder;
-import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.SearchCriteria.Op;
-
-@Component
-@Local(value = NiciraNvpDao.class)
-public class NiciraNvpDaoImpl extends GenericDaoBase<NiciraNvpDeviceVO, Long> implements NiciraNvpDao {
-
- protected final SearchBuilder<NiciraNvpDeviceVO> physicalNetworkIdSearch;
-
- public NiciraNvpDaoImpl() {
- physicalNetworkIdSearch = createSearchBuilder();
- physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ);
- physicalNetworkIdSearch.done();
- }
-
- @Override
- public List<NiciraNvpDeviceVO> listByPhysicalNetwork(final long physicalNetworkId) {
- SearchCriteria<NiciraNvpDeviceVO> sc = physicalNetworkIdSearch.create();
- sc.setParameters("physicalNetworkId", physicalNetworkId);
- return search(sc, null);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java
deleted file mode 100644
index ff81b759..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java
+++ /dev/null
@@ -1,32 +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 com.cloud.network.dao;
-
-import com.cloud.network.NiciraNvpNicMappingVO;
-import com.cloud.utils.db.GenericDao;
-
-public interface NiciraNvpNicMappingDao extends GenericDao<NiciraNvpNicMappingVO, Long> {
-
- /** find the mapping for a nic
- * @param nicUuid the Uuid of a nic attached to a logical switch port
- * @return NiciraNvpNicMapping for this nic uuid or null if it does not exist
- */
- public NiciraNvpNicMappingVO findByNicUuid(String nicUuid);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java
deleted file mode 100644
index 603855c..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java
+++ /dev/null
@@ -1,51 +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 com.cloud.network.dao;
-
-import javax.ejb.Local;
-
-import org.springframework.stereotype.Component;
-
-import com.cloud.network.NiciraNvpNicMappingVO;
-import com.cloud.utils.db.GenericDaoBase;
-import com.cloud.utils.db.SearchBuilder;
-import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.SearchCriteria.Op;
-
-@Component
-@Local(value = NiciraNvpNicMappingDao.class)
-public class NiciraNvpNicMappingDaoImpl extends GenericDaoBase<NiciraNvpNicMappingVO, Long> implements NiciraNvpNicMappingDao {
-
- protected final SearchBuilder<NiciraNvpNicMappingVO> nicSearch;
-
- public NiciraNvpNicMappingDaoImpl() {
- nicSearch = createSearchBuilder();
- nicSearch.and("nicUuid", nicSearch.entity().getNicUuid(), Op.EQ);
- nicSearch.done();
- }
-
- @Override
- public NiciraNvpNicMappingVO findByNicUuid(final String nicUuid) {
- SearchCriteria<NiciraNvpNicMappingVO> sc = nicSearch.create();
- sc.setParameters("nicUuid", nicUuid);
- return findOneBy(sc);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java
deleted file mode 100644
index b64fb90..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java
+++ /dev/null
@@ -1,28 +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 com.cloud.network.dao;
-
-import com.cloud.network.NiciraNvpRouterMappingVO;
-import com.cloud.utils.db.GenericDao;
-
-public interface NiciraNvpRouterMappingDao extends GenericDao<NiciraNvpRouterMappingVO, Long> {
-
- public NiciraNvpRouterMappingVO findByNetworkId(long id);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java
deleted file mode 100644
index 67d3658..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java
+++ /dev/null
@@ -1,51 +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 com.cloud.network.dao;
-
-import javax.ejb.Local;
-
-import org.springframework.stereotype.Component;
-
-import com.cloud.network.NiciraNvpRouterMappingVO;
-import com.cloud.utils.db.GenericDaoBase;
-import com.cloud.utils.db.SearchBuilder;
-import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.SearchCriteria.Op;
-
-@Component
-@Local(value = NiciraNvpRouterMappingDao.class)
-public class NiciraNvpRouterMappingDaoImpl extends GenericDaoBase<NiciraNvpRouterMappingVO, Long> implements NiciraNvpRouterMappingDao {
-
- protected final SearchBuilder<NiciraNvpRouterMappingVO> networkSearch;
-
- public NiciraNvpRouterMappingDaoImpl() {
- networkSearch = createSearchBuilder();
- networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ);
- networkSearch.done();
- }
-
- @Override
- public NiciraNvpRouterMappingVO findByNetworkId(final long id) {
- SearchCriteria<NiciraNvpRouterMappingVO> sc = networkSearch.create();
- sc.setParameters("network_id", id);
- return findOneBy(sc);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java
deleted file mode 100644
index 0243e2d..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java
+++ /dev/null
@@ -1,849 +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 com.cloud.network.element;
-
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.ejb.Local;
-import javax.inject.Inject;
-import javax.naming.ConfigurationException;
-
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
-import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
-import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
-
-import com.cloud.agent.AgentManager;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalRouterAnswer;
-import com.cloud.agent.api.CreateLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
-import com.cloud.agent.api.DeleteLogicalRouterAnswer;
-import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
-import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
-import com.cloud.agent.api.FindLogicalSwitchPortCommand;
-import com.cloud.agent.api.StartupCommand;
-import com.cloud.agent.api.StartupNiciraNvpCommand;
-import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
-import com.cloud.agent.api.to.PortForwardingRuleTO;
-import com.cloud.agent.api.to.StaticNatRuleTO;
-import com.cloud.api.ApiDBUtils;
-import com.cloud.api.commands.AddNiciraNvpDeviceCmd;
-import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;
-import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;
-import com.cloud.api.commands.ListNiciraNvpDevicesCmd;
-import com.cloud.api.response.NiciraNvpDeviceResponse;
-import com.cloud.configuration.ConfigurationManager;
-import com.cloud.dc.Vlan;
-import com.cloud.dc.dao.VlanDao;
-import com.cloud.deploy.DeployDestination;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.host.DetailVO;
-import com.cloud.host.Host;
-import com.cloud.host.HostVO;
-import com.cloud.host.dao.HostDao;
-import com.cloud.host.dao.HostDetailsDao;
-import com.cloud.network.IpAddress;
-import com.cloud.network.IpAddressManager;
-import com.cloud.network.Network;
-import com.cloud.network.Network.Capability;
-import com.cloud.network.Network.Provider;
-import com.cloud.network.Network.Service;
-import com.cloud.network.NetworkModel;
-import com.cloud.network.Networks;
-import com.cloud.network.Networks.BroadcastDomainType;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.network.NiciraNvpNicMappingVO;
-import com.cloud.network.NiciraNvpRouterMappingVO;
-import com.cloud.network.PhysicalNetwork;
-import com.cloud.network.PhysicalNetworkServiceProvider;
-import com.cloud.network.PublicIpAddress;
-import com.cloud.network.addr.PublicIp;
-import com.cloud.network.dao.NetworkDao;
-import com.cloud.network.dao.NetworkServiceMapDao;
-import com.cloud.network.dao.NetworkVO;
-import com.cloud.network.dao.NiciraNvpDao;
-import com.cloud.network.dao.NiciraNvpNicMappingDao;
-import com.cloud.network.dao.NiciraNvpRouterMappingDao;
-import com.cloud.network.dao.PhysicalNetworkDao;
-import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
-import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
-import com.cloud.network.dao.PhysicalNetworkVO;
-import com.cloud.network.resource.NiciraNvpResource;
-import com.cloud.network.rules.PortForwardingRule;
-import com.cloud.network.rules.StaticNat;
-import com.cloud.offering.NetworkOffering;
-import com.cloud.resource.ResourceManager;
-import com.cloud.resource.ResourceState;
-import com.cloud.resource.ResourceStateAdapter;
-import com.cloud.resource.ServerResource;
-import com.cloud.resource.UnableDeleteHostException;
-import com.cloud.user.Account;
-import com.cloud.utils.component.AdapterBase;
-import com.cloud.utils.db.DB;
-import com.cloud.utils.db.Transaction;
-import com.cloud.utils.db.TransactionCallback;
-import com.cloud.utils.db.TransactionStatus;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.net.NetUtils;
-import com.cloud.vm.NicProfile;
-import com.cloud.vm.NicVO;
-import com.cloud.vm.ReservationContext;
-import com.cloud.vm.VirtualMachineProfile;
-import com.cloud.vm.dao.NicDao;
-
-@Component
-@Local(value = {NetworkElement.class, ConnectivityProvider.class, SourceNatServiceProvider.class, StaticNatServiceProvider.class, PortForwardingServiceProvider.class,
- IpDeployer.class})
-public class NiciraNvpElement extends AdapterBase implements ConnectivityProvider, SourceNatServiceProvider, PortForwardingServiceProvider, StaticNatServiceProvider,
-NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
-
- private static final int MAX_PORT = 65535;
- private static final int MIN_PORT = 0;
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpElement.class);
-
- private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
-
- @Inject
- protected NicDao nicDao;
- @Inject
- protected ResourceManager resourceMgr;
- @Inject
- protected PhysicalNetworkDao physicalNetworkDao;
- @Inject
- protected PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao;
- @Inject
- protected NiciraNvpDao niciraNvpDao;
- @Inject
- protected HostDetailsDao hostDetailsDao;
- @Inject
- protected HostDao hostDao;
- @Inject
- protected AgentManager agentMgr;
- @Inject
- protected NiciraNvpNicMappingDao niciraNvpNicMappingDao;
- @Inject
- protected NiciraNvpRouterMappingDao niciraNvpRouterMappingDao;
- @Inject
- protected NetworkDao networkDao;
- @Inject
- protected NetworkOrchestrationService networkManager;
- @Inject
- protected NetworkModel networkModel;
- @Inject
- protected ConfigurationManager configMgr;
- @Inject
- protected NetworkServiceMapDao ntwkSrvcDao;
- @Inject
- protected VlanDao vlanDao;
- @Inject
- protected IpAddressManager ipAddrMgr;
-
- @Override
- public Map<Service, Map<Capability, String>> getCapabilities() {
- return capabilities;
- }
-
- @Override
- public Provider getProvider() {
- return Provider.NiciraNvp;
- }
-
- protected boolean canHandle(Network network, Service service) {
- s_logger.debug("Checking if NiciraNvpElement can handle service " + service.getName() + " on network " + network.getDisplayText());
- if (network.getBroadcastDomainType() != BroadcastDomainType.Lswitch) {
- return false;
- }
-
- if (!networkModel.isProviderForNetwork(getProvider(), network.getId())) {
- s_logger.debug("NiciraNvpElement is not a provider for network " + network.getDisplayText());
- return false;
- }
-
- if (!ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, Network.Provider.NiciraNvp)) {
- s_logger.debug("NiciraNvpElement can't provide the " + service.getName() + " service on network " + network.getDisplayText());
- return false;
- }
-
- return true;
- }
-
- @Override
- public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
- super.configure(name, params);
- resourceMgr.registerResourceStateAdapter(name, this);
- return true;
- }
-
- @Override
- public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
- ResourceUnavailableException, InsufficientCapacityException {
- s_logger.debug("entering NiciraNvpElement implement function for network " + network.getDisplayText() + " (state " + network.getState() + ")");
-
- if (!canHandle(network, Service.Connectivity)) {
- return false;
- }
-
- if (network.getBroadcastUri() == null) {
- s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
- return false;
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
- hostDao.loadDetails(niciraNvpHost);
-
- Account owner = context.getAccount();
-
- /*
- * TODO Shouldn't we lock the network as we might need to do
- * multiple operations that should be done only once.
- */
-
- // Implement SourceNat immediately as we have al the info already
- if (networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.NiciraNvp)) {
- s_logger.debug("Apparently we are supposed to provide SourceNat on this network");
-
- PublicIp sourceNatIp = ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network);
- String publicCidr = sourceNatIp.getAddress().addr() + "/" + NetUtils.getCidrSize(sourceNatIp.getVlanNetmask());
- String internalCidr = network.getGateway() + "/" + network.getCidr().split("/")[1];
- // assuming a vlan:
- String vtag = sourceNatIp.getVlanTag();
- BroadcastDomainType tiep = null;
- try {
- tiep = BroadcastDomainType.getTypeOf(vtag);
- } catch (URISyntaxException use) {
- throw new CloudRuntimeException("vlantag for sourceNatIp is not valid: " + vtag, use);
- }
- if (tiep == BroadcastDomainType.Vlan) {
- vtag = BroadcastDomainType.Vlan.getValueFrom(BroadcastDomainType.fromString(vtag));
- } else if (!(tiep == BroadcastDomainType.UnDecided || tiep == BroadcastDomainType.Native)) {
- throw new CloudRuntimeException("only vlans are supported for sourceNatIp, at this moment: " + vtag);
- }
- long vlanid = (Vlan.UNTAGGED.equals(vtag)) ? 0 : Long.parseLong(vtag);
-
- CreateLogicalRouterCommand cmd =
- new CreateLogicalRouterCommand(niciraNvpHost.getDetail("l3gatewayserviceuuid"), vlanid, BroadcastDomainType.getValue(network.getBroadcastUri()),
- "router-" + network.getDisplayText(), publicCidr, sourceNatIp.getGateway(), internalCidr, context.getDomain().getName() + "-" +
- context.getAccount().getAccountName());
- CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
- if (answer.getResult() == false) {
- s_logger.error("Failed to create Logical Router for network " + network.getDisplayText());
- return false;
- }
-
- // Store the uuid so we can easily find it during cleanup
- NiciraNvpRouterMappingVO routermapping = new NiciraNvpRouterMappingVO(answer.getLogicalRouterUuid(), network.getId());
- niciraNvpRouterMappingDao.persist(routermapping);
- }
-
- return true;
- }
-
- @Override
- public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
- throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
-
- if (!canHandle(network, Service.Connectivity)) {
- return false;
- }
-
- if (network.getBroadcastUri() == null) {
- s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
- return false;
- }
-
- NicVO nicVO = nicDao.findById(nic.getId());
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
-
- NiciraNvpNicMappingVO existingNicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid());
- if (existingNicMap != null) {
- FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchUuid(), existingNicMap.getLogicalSwitchPortUuid());
- FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), findCmd);
-
- if (answer.getResult()) {
- s_logger.warn("Existing Logical Switchport found for nic " + nic.getName() + " with uuid " + existingNicMap.getLogicalSwitchPortUuid());
- UpdateLogicalSwitchPortCommand cmd =
- new UpdateLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchPortUuid(), BroadcastDomainType.getValue(network.getBroadcastUri()),
- nicVO.getUuid(), context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName());
- agentMgr.easySend(niciraNvpHost.getId(), cmd);
- return true;
- } else {
- s_logger.error("Stale entry found for nic " + nic.getName() + " with logical switchport uuid " + existingNicMap.getLogicalSwitchPortUuid());
- niciraNvpNicMappingDao.remove(existingNicMap.getId());
- }
- }
-
- CreateLogicalSwitchPortCommand cmd =
- new CreateLogicalSwitchPortCommand(BroadcastDomainType.getValue(network.getBroadcastUri()), nicVO.getUuid(), context.getDomain().getName() + "-" +
- context.getAccount().getAccountName(), nic.getName());
- CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
-
- if (answer == null || !answer.getResult()) {
- s_logger.error("CreateLogicalSwitchPortCommand failed");
- return false;
- }
-
- NiciraNvpNicMappingVO nicMap =
- new NiciraNvpNicMappingVO(BroadcastDomainType.getValue(network.getBroadcastUri()), answer.getLogicalSwitchPortUuid(), nicVO.getUuid());
- niciraNvpNicMappingDao.persist(nicMap);
-
- return true;
- }
-
- @Override
- public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException,
- ResourceUnavailableException {
-
- if (!canHandle(network, Service.Connectivity)) {
- return false;
- }
-
- if (network.getBroadcastUri() == null) {
- s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
- return false;
- }
-
- NicVO nicVO = nicDao.findById(nic.getId());
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
-
- NiciraNvpNicMappingVO nicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid());
- if (nicMap == null) {
- s_logger.error("No mapping for nic " + nic.getName());
- return false;
- }
-
- DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand(nicMap.getLogicalSwitchUuid(), nicMap.getLogicalSwitchPortUuid());
- DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
-
- if (answer == null || !answer.getResult()) {
- s_logger.error("DeleteLogicalSwitchPortCommand failed");
- return false;
- }
-
- niciraNvpNicMappingDao.remove(nicMap.getId());
-
- return true;
- }
-
- @Override
- public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
- if (!canHandle(network, Service.Connectivity)) {
- return false;
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
-
- if (networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.NiciraNvp)) {
- s_logger.debug("Apparently we were providing SourceNat on this network");
-
- // Deleting the LogicalRouter will also take care of all provisioned
- // nat rules.
- NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
- if (routermapping == null) {
- s_logger.warn("No logical router uuid found for network " + network.getDisplayText());
- // This might be cause by a failed deployment, so don't make shutdown fail as well.
- return true;
- }
-
- DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid());
- DeleteLogicalRouterAnswer answer = (DeleteLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
- if (answer.getResult() == false) {
- s_logger.error("Failed to delete LogicalRouter for network " + network.getDisplayText());
- return false;
- }
-
- niciraNvpRouterMappingDao.remove(routermapping.getId());
- }
-
- return true;
- }
-
- @Override
- public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
- if (!canHandle(network, Service.Connectivity)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public boolean isReady(PhysicalNetworkServiceProvider provider) {
- return true;
- }
-
- @Override
- public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
- ResourceUnavailableException {
- // Nothing to do here.
- return true;
- }
-
- @Override
- public boolean canEnableIndividualServices() {
- return true;
- }
-
- @Override
- public boolean verifyServicesCombination(Set<Service> services) {
- // This element can only function in a Nicra Nvp based
- // SDN network, so Connectivity needs to be present here
- if (!services.contains(Service.Connectivity)) {
- s_logger.warn("Unable to provide services without Connectivity service enabled for this element");
- return false;
- }
- if ((services.contains(Service.PortForwarding) || services.contains(Service.StaticNat)) && !services.contains(Service.SourceNat)) {
- s_logger.warn("Unable to provide StaticNat and/or PortForwarding without the SourceNat service");
- return false;
- }
- return true;
- }
-
- private static Map<Service, Map<Capability, String>> setCapabilities() {
- Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
-
- // L2 Support : SDN provisioning
- capabilities.put(Service.Connectivity, null);
-
- // L3 Support : Generic?
- capabilities.put(Service.Gateway, null);
-
- // L3 Support : SourceNat
- Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>();
- sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "peraccount");
- sourceNatCapabilities.put(Capability.RedundantRouter, "false");
- capabilities.put(Service.SourceNat, sourceNatCapabilities);
-
- // L3 Support : Port Forwarding
- capabilities.put(Service.PortForwarding, null);
-
- // L3 support : StaticNat
- capabilities.put(Service.StaticNat, null);
-
- return capabilities;
- }
-
- @Override
- public List<Class<?>> getCommands() {
- List<Class<?>> cmdList = new ArrayList<Class<?>>();
- cmdList.add(AddNiciraNvpDeviceCmd.class);
- cmdList.add(DeleteNiciraNvpDeviceCmd.class);
- cmdList.add(ListNiciraNvpDeviceNetworksCmd.class);
- cmdList.add(ListNiciraNvpDevicesCmd.class);
- return cmdList;
- }
-
- @Override
- @DB
- public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) {
- ServerResource resource = new NiciraNvpResource();
- final String deviceName = Network.Provider.NiciraNvp.getName();
- NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
- if (networkDevice == null) {
- throw new CloudRuntimeException("No network device found for " + deviceName);
- }
- final Long physicalNetworkId = cmd.getPhysicalNetworkId();
- PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
- if (physicalNetwork == null) {
- throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
- }
- long zoneId = physicalNetwork.getDataCenterId();
-
- final PhysicalNetworkServiceProviderVO ntwkSvcProvider =
- physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
- if (ntwkSvcProvider == null) {
- throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " +
- physicalNetworkId + "to add this device");
- } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
- throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " +
- physicalNetworkId + "to add this device");
- }
-
- if (niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) {
- throw new CloudRuntimeException("A NiciraNvp device is already configured on this physical network");
- }
-
- Map<String, String> params = new HashMap<String, String>();
- params.put("guid", UUID.randomUUID().toString());
- params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
- params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
- params.put("name", "Nicira Controller - " + cmd.getHost());
- params.put("ip", cmd.getHost());
- params.put("adminuser", cmd.getUsername());
- params.put("adminpass", cmd.getPassword());
- params.put("transportzoneuuid", cmd.getTransportzoneUuid());
- // FIXME What to do with multiple isolation types
- params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase());
- if (cmd.getL3GatewayServiceUuid() != null) {
- params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid());
- }
-
- Map<String, Object> hostdetails = new HashMap<String, Object>();
- hostdetails.putAll(params);
-
- try {
- resource.configure(cmd.getHost(), hostdetails);
-
- final Host host = resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
- if (host != null) {
- return Transaction.execute(new TransactionCallback<NiciraNvpDeviceVO>() {
- @Override
- public NiciraNvpDeviceVO doInTransaction(TransactionStatus status) {
- NiciraNvpDeviceVO niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
- niciraNvpDao.persist(niciraNvpDevice);
-
- DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice.getId()));
- hostDetailsDao.persist(detail);
-
- return niciraNvpDevice;
- }
- });
- } else {
- throw new CloudRuntimeException("Failed to add Nicira Nvp Device due to internal error.");
- }
- } catch (ConfigurationException e) {
- throw new CloudRuntimeException(e.getMessage());
- }
- }
-
- @Override
- public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(NiciraNvpDeviceVO niciraNvpDeviceVO) {
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDeviceVO.getHostId());
- hostDao.loadDetails(niciraNvpHost);
-
- NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse();
- response.setDeviceName(niciraNvpDeviceVO.getDeviceName());
- PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(niciraNvpDeviceVO.getPhysicalNetworkId());
- if (pnw != null) {
- response.setPhysicalNetworkId(pnw.getUuid());
- }
- response.setId(niciraNvpDeviceVO.getUuid());
- response.setProviderName(niciraNvpDeviceVO.getProviderName());
- response.setHostName(niciraNvpHost.getDetail("ip"));
- response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid"));
- response.setL3GatewayServiceUuid(niciraNvpHost.getDetail("l3gatewayserviceuuid"));
- response.setObjectName("niciranvpdevice");
- return response;
- }
-
- @Override
- public boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd) {
- Long niciraDeviceId = cmd.getNiciraNvpDeviceId();
- NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraDeviceId);
- if (niciraNvpDevice == null) {
- throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId);
- }
-
- // Find the physical network we work for
- Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId();
- PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
- if (physicalNetwork != null) {
- // Lets see if there are networks that use us
- // Find the nicira networks on this physical network
- List<NetworkVO> networkList = networkDao.listByPhysicalNetwork(physicalNetworkId);
- if (networkList != null) {
- // Networks with broadcast type lswitch are ours
- for (NetworkVO network : networkList) {
- if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
- if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) {
- throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack.");
- }
- }
- }
- }
- }
-
- HostVO niciraHost = hostDao.findById(niciraNvpDevice.getHostId());
- Long hostId = niciraHost.getId();
-
- niciraHost.setResourceState(ResourceState.Maintenance);
- hostDao.update(hostId, niciraHost);
- resourceMgr.deleteHost(hostId, false, false);
-
- niciraNvpDao.remove(niciraDeviceId);
- return true;
- }
-
- @Override
- public List<NiciraNvpDeviceVO> listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd) {
- Long physicalNetworkId = cmd.getPhysicalNetworkId();
- Long niciraNvpDeviceId = cmd.getNiciraNvpDeviceId();
- List<NiciraNvpDeviceVO> responseList = new ArrayList<NiciraNvpDeviceVO>();
-
- if (physicalNetworkId == null && niciraNvpDeviceId == null) {
- throw new InvalidParameterValueException("Either physical network Id or nicira device Id must be specified");
- }
-
- if (niciraNvpDeviceId != null) {
- NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraNvpDeviceId);
- if (niciraNvpDevice == null) {
- throw new InvalidParameterValueException("Could not find Nicira Nvp device with id: " + niciraNvpDevice);
- }
- responseList.add(niciraNvpDevice);
- } else {
- PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
- if (physicalNetwork == null) {
- throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId);
- }
- responseList = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
- }
-
- return responseList;
- }
-
- @Override
- public List<? extends Network> listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd) {
- Long niciraDeviceId = cmd.getNiciraNvpDeviceId();
- NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraDeviceId);
- if (niciraNvpDevice == null) {
- throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId);
- }
-
- // Find the physical network we work for
- Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId();
- PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
- if (physicalNetwork == null) {
- // No such physical network, so no provisioned networks
- return Collections.emptyList();
- }
-
- // Find the nicira networks on this physical network
- List<NetworkVO> networkList = networkDao.listByPhysicalNetwork(physicalNetworkId);
- if (networkList == null) {
- return Collections.emptyList();
- }
-
- // Networks with broadcast type lswitch are ours
- List<NetworkVO> responseList = new ArrayList<NetworkVO>();
- for (NetworkVO network : networkList) {
- if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
- responseList.add(network);
- }
- }
-
- return responseList;
- }
-
- @Override
- public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details, List<String> hostTags) {
- if (!(startup[0] instanceof StartupNiciraNvpCommand)) {
- return null;
- }
- host.setType(Host.Type.L2Networking);
- return host;
- }
-
- @Override
- public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
- if (!(host.getType() == Host.Type.L2Networking)) {
- return null;
- }
- return new DeleteHostAnswer(true);
- }
-
- /**
- * From interface SourceNatServiceProvider
- */
- @Override
- public IpDeployer getIpDeployer(Network network) {
- return this;
- }
-
- /**
- * From interface IpDeployer
- *
- * @param network
- * @param ipAddress
- * @param services
- * @return
- * @throws ResourceUnavailableException
- */
- @Override
- public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> services) throws ResourceUnavailableException {
- if (services.contains(Service.SourceNat)) {
- // Only if we need to provide SourceNat we need to configure the logical router
- // SourceNat is required for StaticNat and PortForwarding
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
- hostDao.loadDetails(niciraNvpHost);
-
- NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
- if (routermapping == null) {
- s_logger.error("No logical router uuid found for network " + network.getDisplayText());
- return false;
- }
-
- List<String> cidrs = new ArrayList<String>();
- for (PublicIpAddress ip : ipAddress) {
- if (ip.getState() == IpAddress.State.Releasing) {
- // If we are releasing we don't need to push this ip to
- // the Logical Router
- continue;
- }
- cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask()));
- }
- ConfigurePublicIpsOnLogicalRouterCommand cmd =
- new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs);
- ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
- //FIXME answer can be null if the host is down
- return answer.getResult();
- } else {
- s_logger.debug("No need to provision ip addresses as we are not providing L3 services.");
- }
-
- return true;
- }
-
- /**
- * From interface StaticNatServiceProvider
- */
- @Override
- public boolean applyStaticNats(Network network, List<? extends StaticNat> rules) throws ResourceUnavailableException {
- if (!canHandle(network, Service.StaticNat)) {
- return false;
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
-
- NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
- if (routermapping == null) {
- s_logger.error("No logical router uuid found for network " + network.getDisplayText());
- return false;
- }
-
- List<StaticNatRuleTO> staticNatRules = new ArrayList<StaticNatRuleTO>();
- for (StaticNat rule : rules) {
- IpAddress sourceIp = networkModel.getIp(rule.getSourceIpAddressId());
- // Force the nat rule into the StaticNatRuleTO, no use making a new TO object
- // we only need the source and destination ip. Unfortunately no mention if a rule
- // is new.
- StaticNatRuleTO ruleTO =
- new StaticNatRuleTO(1, sourceIp.getAddress().addr(), MIN_PORT, MAX_PORT, rule.getDestIpAddress(), MIN_PORT, MAX_PORT, "any", rule.isForRevoke(), false);
- staticNatRules.add(ruleTO);
- }
-
- ConfigureStaticNatRulesOnLogicalRouterCommand cmd = new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules);
- ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
-
- return answer.getResult();
- }
-
- /**
- * From interface PortForwardingServiceProvider
- */
- @Override
- public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException {
- if (!canHandle(network, Service.PortForwarding)) {
- return false;
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
- return false;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
-
- NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
- if (routermapping == null) {
- s_logger.error("No logical router uuid found for network " + network.getDisplayText());
- return false;
- }
-
- List<PortForwardingRuleTO> portForwardingRules = new ArrayList<PortForwardingRuleTO>();
- for (PortForwardingRule rule : rules) {
- IpAddress sourceIp = networkModel.getIp(rule.getSourceIpAddressId());
- Vlan vlan = vlanDao.findById(sourceIp.getVlanId());
- PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr());
- portForwardingRules.add(ruleTO);
- }
-
- ConfigurePortForwardingRulesOnLogicalRouterCommand cmd =
- new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules);
- ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
-
- return answer.getResult();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java
deleted file mode 100644
index dae1a0f..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java
+++ /dev/null
@@ -1,45 +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 com.cloud.network.element;
-
-import java.util.List;
-
-import com.cloud.api.commands.AddNiciraNvpDeviceCmd;
-import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;
-import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;
-import com.cloud.api.commands.ListNiciraNvpDevicesCmd;
-import com.cloud.api.response.NiciraNvpDeviceResponse;
-import com.cloud.network.Network;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.utils.component.PluggableService;
-
-public interface NiciraNvpElementService extends PluggableService {
-
- public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd);
-
- public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(NiciraNvpDeviceVO niciraDeviceVO);
-
- boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd);
-
- List<? extends Network> listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd);
-
- List<NiciraNvpDeviceVO> listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd);
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
deleted file mode 100644
index 640d8a5..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
+++ /dev/null
@@ -1,256 +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 com.cloud.network.guru;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.List;
-
-import javax.ejb.Local;
-import javax.inject.Inject;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.agent.AgentManager;
-import com.cloud.agent.api.CreateLogicalSwitchAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchCommand;
-import com.cloud.dc.DataCenter;
-import com.cloud.dc.DataCenter.NetworkType;
-import com.cloud.dc.dao.DataCenterDao;
-import com.cloud.deploy.DeployDestination;
-import com.cloud.deploy.DeploymentPlan;
-import com.cloud.exception.InsufficientAddressCapacityException;
-import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
-import com.cloud.host.HostVO;
-import com.cloud.host.dao.HostDao;
-import com.cloud.host.dao.HostDetailsDao;
-import com.cloud.network.Network;
-import com.cloud.network.Network.GuestType;
-import com.cloud.network.Network.Service;
-import com.cloud.network.Network.State;
-import com.cloud.network.NetworkModel;
-import com.cloud.network.NetworkProfile;
-import com.cloud.network.Networks.BroadcastDomainType;
-import com.cloud.network.NiciraNvpDeviceVO;
-import com.cloud.network.PhysicalNetwork;
-import com.cloud.network.PhysicalNetwork.IsolationMethod;
-import com.cloud.network.dao.NetworkDao;
-import com.cloud.network.dao.NetworkVO;
-import com.cloud.network.dao.NiciraNvpDao;
-import com.cloud.network.dao.PhysicalNetworkDao;
-import com.cloud.network.dao.PhysicalNetworkVO;
-import com.cloud.offering.NetworkOffering;
-import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
-import com.cloud.resource.ResourceManager;
-import com.cloud.user.Account;
-import com.cloud.user.dao.AccountDao;
-import com.cloud.vm.NicProfile;
-import com.cloud.vm.ReservationContext;
-import com.cloud.vm.VirtualMachineProfile;
-
-@Local(value = NetworkGuru.class)
-public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
- private static final int MAX_NAME_LENGTH = 40;
-
- private static final Logger s_logger = Logger.getLogger(NiciraNvpGuestNetworkGuru.class);
-
- @Inject
- protected NetworkModel networkModel;
- @Inject
- protected NetworkDao networkDao;
- @Inject
- protected DataCenterDao zoneDao;
- @Inject
- protected PhysicalNetworkDao physicalNetworkDao;
- @Inject
- protected AccountDao accountDao;
- @Inject
- protected NiciraNvpDao niciraNvpDao;
- @Inject
- protected HostDao hostDao;
- @Inject
- protected ResourceManager resourceMgr;
- @Inject
- protected AgentManager agentMgr;
- @Inject
- protected HostDetailsDao hostDetailsDao;
- @Inject
- protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao;
-
- public NiciraNvpGuestNetworkGuru() {
- super();
- _isolationMethods = new IsolationMethod[] {IsolationMethod.STT, IsolationMethod.VXLAN};
- }
-
- @Override
- protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
- // This guru handles only Guest Isolated network that supports Source nat service
- if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated &&
- isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) {
- return true;
- } else {
- s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced);
- return false;
- }
- }
-
- @Override
- public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final Account owner) {
- // Check of the isolation type of the related physical network is supported
- PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId());
- DataCenter dc = _dcDao.findById(plan.getDataCenterId());
- if (!canHandle(offering, dc.getNetworkType(), physnet)) {
- s_logger.debug("Refusing to design this network");
- return null;
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + physnet.getName());
- return null;
- }
- s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId());
-
- s_logger.debug("Physical isolation type is supported, asking GuestNetworkGuru to design this network");
- NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner);
- if (networkObject == null) {
- return null;
- }
- // Override the broadcast domain type
- networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch);
-
- return networkObject;
- }
-
- @Override
- public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context)
- throws InsufficientVirtualNetworkCapacityException {
- assert (network.getState() == State.Implementing) : "Why are we implementing " + network;
-
- long dcId = dest.getDataCenter().getId();
-
- //get physical network id
- Long physicalNetworkId = network.getPhysicalNetworkId();
-
- // physical network id can be null in Guest Network in Basic zone, so locate the physical network
- if (physicalNetworkId == null) {
- physicalNetworkId = networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType());
- }
-
- NetworkVO implemented =
- new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated,
- network.getDataCenterId(), physicalNetworkId, offering.getRedundantRouter());
-
- if (network.getGateway() != null) {
- implemented.setGateway(network.getGateway());
- }
-
- if (network.getCidr() != null) {
- implemented.setCidr(network.getCidr());
- }
-
- // Name is either the given name or the uuid
- String name = network.getName();
- if (name == null || name.isEmpty()) {
- name = ((NetworkVO)network).getUuid();
- }
- if (name.length() > MAX_NAME_LENGTH) {
- name = name.substring(0, MAX_NAME_LENGTH - 1); // max length 40
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + physicalNetworkId);
- return null;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
- hostDao.loadDetails(niciraNvpHost);
- String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid");
- String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype");
-
- CreateLogicalSwitchCommand cmd =
- new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-" + context.getAccount().getAccountName());
- CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
-
- if (answer == null || !answer.getResult()) {
- s_logger.error("CreateLogicalSwitchCommand failed");
- return null;
- }
-
- try {
- implemented.setBroadcastUri(new URI("lswitch", answer.getLogicalSwitchUuid(), null));
- implemented.setBroadcastDomainType(BroadcastDomainType.Lswitch);
- s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString());
- } catch (URISyntaxException e) {
- s_logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e);
- return null;
- }
-
- return implemented;
- }
-
- @Override
- public void reserve(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context)
- throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
- // TODO Auto-generated method stub
- super.reserve(nic, network, vm, dest, context);
- }
-
- @Override
- public boolean release(final NicProfile nic, final VirtualMachineProfile vm, final String reservationId) {
- // TODO Auto-generated method stub
- return super.release(nic, vm, reservationId);
- }
-
- @Override
- public void shutdown(final NetworkProfile profile, final NetworkOffering offering) {
- NetworkVO networkObject = networkDao.findById(profile.getId());
- if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch || networkObject.getBroadcastUri() == null) {
- s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText());
- return;
- }
-
- List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
- if (devices.isEmpty()) {
- s_logger.error("No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId());
- return;
- }
- NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
- HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
-
- DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
- DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
-
- if (answer == null || !answer.getResult()) {
- s_logger.error("DeleteLogicalSwitchCommand failed");
- }
-
- super.shutdown(profile, offering);
- }
-
- @Override
- public boolean trash(final Network network, final NetworkOffering offering) {
- return super.trash(network, offering);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java
deleted file mode 100644
index b5291dc..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java
+++ /dev/null
@@ -1,44 +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 com.cloud.network.nicira;
-
-import java.util.List;
-
-public abstract class AccessConfiguration<T extends AccessRule> extends BaseNiciraNamedEntity {
-
- protected List<T> logicalPortEgressRules;
- protected List<T> logicalPortIngressRules;
-
- public List<T> getLogicalPortEgressRules() {
- return logicalPortEgressRules;
- }
-
- public void setLogicalPortEgressRules(final List<T> logicalPortEgressRules) {
- this.logicalPortEgressRules = logicalPortEgressRules;
- }
-
- public List<T> getLogicalPortIngressRules() {
- return logicalPortIngressRules;
- }
-
- public void setLogicalPortIngressRules(final List<T> logicalPortIngressRules) {
- this.logicalPortIngressRules = logicalPortIngressRules;
- }
-}
[10/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/testcase/NioTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/testcase/NioTest.java b/utils/src/test/java/com/cloud/utils/testcase/NioTest.java
new file mode 100644
index 0000000..fc16684
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/testcase/NioTest.java
@@ -0,0 +1,216 @@
+//
+// 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 com.cloud.utils.testcase;
+
+import java.nio.channels.ClosedChannelException;
+import java.util.Random;
+
+import junit.framework.TestCase;
+
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+
+import com.cloud.utils.nio.HandlerFactory;
+import com.cloud.utils.nio.Link;
+import com.cloud.utils.nio.NioClient;
+import com.cloud.utils.nio.NioServer;
+import com.cloud.utils.nio.Task;
+import com.cloud.utils.nio.Task.Type;
+
+/**
+ *
+ *
+ *
+ *
+ */
+
+public class NioTest extends TestCase {
+
+ private static final Logger s_logger = Logger.getLogger(NioTest.class);
+
+ private NioServer _server;
+ private NioClient _client;
+
+ private Link _clientLink;
+
+ private int _testCount;
+ private int _completedCount;
+
+ private boolean isTestsDone() {
+ boolean result;
+ synchronized (this) {
+ result = (_testCount == _completedCount);
+ }
+ return result;
+ }
+
+ private void getOneMoreTest() {
+ synchronized (this) {
+ _testCount++;
+ }
+ }
+
+ private void oneMoreTestDone() {
+ synchronized (this) {
+ _completedCount++;
+ }
+ }
+
+ @Override
+ public void setUp() {
+ s_logger.info("Test");
+
+ _testCount = 0;
+ _completedCount = 0;
+
+ _server = new NioServer("NioTestServer", 7777, 5, new NioTestServer());
+ _server.start();
+
+ _client = new NioClient("NioTestServer", "127.0.0.1", 7777, 5, new NioTestClient());
+ _client.start();
+
+ while (_clientLink == null) {
+ try {
+ s_logger.debug("Link is not up! Waiting ...");
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void tearDown() {
+ while (!isTestsDone()) {
+ try {
+ s_logger.debug(this._completedCount + "/" + this._testCount + " tests done. Waiting for completion");
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ stopClient();
+ stopServer();
+ }
+
+ protected void stopClient() {
+ _client.stop();
+ s_logger.info("Client stopped.");
+ }
+
+ protected void stopServer() {
+ _server.stop();
+ s_logger.info("Server stopped.");
+ }
+
+ protected void setClientLink(Link link) {
+ _clientLink = link;
+ }
+
+ Random randomGenerator = new Random();
+
+ byte[] _testBytes;
+
+ public void testConnection() {
+ _testBytes = new byte[1000000];
+ randomGenerator.nextBytes(_testBytes);
+ try {
+ getOneMoreTest();
+ _clientLink.send(_testBytes);
+ s_logger.info("Client: Data sent");
+ getOneMoreTest();
+ _clientLink.send(_testBytes);
+ s_logger.info("Client: Data sent");
+ } catch (ClosedChannelException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ protected void doServerProcess(byte[] data) {
+ oneMoreTestDone();
+ Assert.assertArrayEquals(_testBytes, data);
+ s_logger.info("Verify done.");
+ }
+
+ public class NioTestClient implements HandlerFactory {
+
+ @Override
+ public Task create(Type type, Link link, byte[] data) {
+ return new NioTestClientHandler(type, link, data);
+ }
+
+ public class NioTestClientHandler extends Task {
+
+ public NioTestClientHandler(Type type, Link link, byte[] data) {
+ super(type, link, data);
+ }
+
+ @Override
+ public void doTask(final Task task) {
+ if (task.getType() == Task.Type.CONNECT) {
+ s_logger.info("Client: Received CONNECT task");
+ setClientLink(task.getLink());
+ } else if (task.getType() == Task.Type.DATA) {
+ s_logger.info("Client: Received DATA task");
+ } else if (task.getType() == Task.Type.DISCONNECT) {
+ s_logger.info("Client: Received DISCONNECT task");
+ stopClient();
+ } else if (task.getType() == Task.Type.OTHER) {
+ s_logger.info("Client: Received OTHER task");
+ }
+ }
+
+ }
+ }
+
+ public class NioTestServer implements HandlerFactory {
+
+ @Override
+ public Task create(Type type, Link link, byte[] data) {
+ return new NioTestServerHandler(type, link, data);
+ }
+
+ public class NioTestServerHandler extends Task {
+
+ public NioTestServerHandler(Type type, Link link, byte[] data) {
+ super(type, link, data);
+ }
+
+ @Override
+ public void doTask(final Task task) {
+ if (task.getType() == Task.Type.CONNECT) {
+ s_logger.info("Server: Received CONNECT task");
+ } else if (task.getType() == Task.Type.DATA) {
+ s_logger.info("Server: Received DATA task");
+ doServerProcess(task.getData());
+ } else if (task.getType() == Task.Type.DISCONNECT) {
+ s_logger.info("Server: Received DISCONNECT task");
+ stopServer();
+ } else if (task.getType() == Task.Type.OTHER) {
+ s_logger.info("Server: Received OTHER task");
+ }
+ }
+
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject.java b/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject.java
new file mode 100644
index 0000000..faaf980
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject.java
@@ -0,0 +1,53 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.xmlobject;
+
+import org.junit.Test;
+
+public class TestXmlObject {
+
+ void p(String str) {
+ System.out.println(str);
+ }
+
+ @Test
+ public void test() {
+
+ // deprecated, since we no longer use component.xml.in any more
+ /*
+ XmlObject xo = XmlObjectParser.parseFromFile("z:/components.xml.in");
+ p(xo.getTag());
+ p((String) xo.get("system-integrity-checker.checker").toString());
+ List<XmlObject> lst = xo.get("management-server.adapters");
+ for (XmlObject x : lst) {
+ List<XmlObject> lst1 = x.getAsList("adapter");
+ for (XmlObject y : lst1) {
+ p(y.toString());
+ }
+ }
+ */
+
+ XmlObject xml = new XmlObject("vlan").putElement("vlan-id", String.valueOf(19)).putElement("tagged",
+ new XmlObject("teng").putElement("name", "0/0")
+ ).putElement("shutdown", "false");
+ System.out.println(xml.toString());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject2.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject2.java b/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject2.java
new file mode 100644
index 0000000..9a27ca1
--- /dev/null
+++ b/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject2.java
@@ -0,0 +1,54 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.xmlobject;
+
+import org.junit.Test;
+
+public class TestXmlObject2 {
+ void p(String str) {
+ System.out.println(str);
+ }
+
+ XmlObject xo(String name) {
+ return new XmlObject(name);
+ }
+
+ @Test
+ public void test() {
+ XmlObject root = new XmlObject("test");
+ root.putElement("key1", "value1").putElement("key2", "value2");
+ p(root.dump());
+
+ XmlObject c1 = new XmlObject("child1");
+ XmlObject c2 = new XmlObject("child2");
+ c2.putElement("ckey1", "value1");
+ c1.putElement(c2.getTag(), c2);
+ root.putElement(c1.getTag(), c1);
+ p(root.dump());
+
+ root =
+ xo("test2").putElement("key1", "value1")
+ .putElement("child1", xo("child1").setText("yyy"))
+ .putElement("child1", xo("child1").putElement("child2", xo("child2").putElement("child3", xo("child3").putElement("key3", "value3").setText("xxxxx"))));
+
+ p(root.dump());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/src/test/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java b/utils/src/test/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java
new file mode 100644
index 0000000..ace765a
--- /dev/null
+++ b/utils/src/test/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java
@@ -0,0 +1,54 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package org.apache.cloudstack.utils.imagestore;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.UUID;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ImageStoreUtilTest {
+
+ @Test
+ public void testgeneratePostUploadUrl() throws MalformedURLException {
+ String ssvmdomain = "*.realhostip.com";
+ String ipAddress = "10.147.28.14";
+ String uuid = UUID.randomUUID().toString();
+
+ //ssvm domain is not set
+ String url = ImageStoreUtil.generatePostUploadUrl(null, ipAddress, uuid);
+ assertPostUploadUrl(url, ipAddress, uuid);
+
+ //ssvm domain is set to empty value
+ url = ImageStoreUtil.generatePostUploadUrl("", ipAddress, uuid);
+ assertPostUploadUrl(url, ipAddress, uuid);
+
+ //ssvm domain is set to a valid value
+ url = ImageStoreUtil.generatePostUploadUrl(ssvmdomain, ipAddress, uuid);
+ assertPostUploadUrl(url, ipAddress.replace(".", "-") + ssvmdomain.substring(1), uuid);
+ }
+
+ private void assertPostUploadUrl(String urlStr, String domain, String uuid) throws MalformedURLException {
+ URL url = new URL(urlStr);
+ Assert.assertNotNull(url);
+ Assert.assertEquals(url.getHost(), domain);
+ Assert.assertEquals(url.getPath(), "/upload/" + uuid);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/resources/com/cloud/utils/QualifierTestContext.xml
----------------------------------------------------------------------
diff --git a/utils/src/test/resources/com/cloud/utils/QualifierTestContext.xml b/utils/src/test/resources/com/cloud/utils/QualifierTestContext.xml
new file mode 100644
index 0000000..39f494b
--- /dev/null
+++ b/utils/src/test/resources/com/cloud/utils/QualifierTestContext.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/tx
+ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/aop
+ http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ <context:annotation-config />
+ <context:component-scan base-package="org.apache.cloudstack, com.cloud" />
+
+</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
----------------------------------------------------------------------
diff --git a/utils/src/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml b/utils/src/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
new file mode 100644
index 0000000..81ca058
--- /dev/null
+++ b/utils/src/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/tx
+ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/aop
+ http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ <context:annotation-config />
+ <context:component-scan base-package="org.apache.cloudstack, com.cloud" />
+
+ <aop:config proxy-target-class="true">
+ <aop:aspect id="dbContextBuilder" ref="transactionContextBuilder">
+ <aop:pointcut id="captureAnyMethod"
+ expression="execution(* *(..))" />
+ <aop:around pointcut-ref="captureAnyMethod" method="AroundAnyMethod"/>
+ </aop:aspect>
+ </aop:config>
+
+ <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
+
+</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/resources/log4j.xml
----------------------------------------------------------------------
diff --git a/utils/src/test/resources/log4j.xml b/utils/src/test/resources/log4j.xml
new file mode 100755
index 0000000..cdae2fa
--- /dev/null
+++ b/utils/src/test/resources/log4j.xml
@@ -0,0 +1,118 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
+
+ <throwableRenderer class="com.cloud.utils.log.CglibThrowableRenderer"/>
+ <!-- ================================= -->
+ <!-- Preserve messages in a local file -->
+ <!-- ================================= -->
+
+ <!-- A regular appender FIXME implement code that will close/reopen logs on SIGHUP by logrotate FIXME make the paths configurable using the build system -->
+<!-- <appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
+ <param name="Append" value="true"/>
+ <param name="Threshold" value="TRACE"/>
+ <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
+ <param name="FileNamePattern" value="@MSLOG@.%d{yyyy-MM-dd}.gz"/>
+ <param name="ActiveFileName" value="@MSLOG@"/>
+ </rollingPolicy>
+ <layout class="org.apache.log4j.EnhancedPatternLayout">
+ <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
+ </layout>
+ </appender>
+ -->
+ <!--
+ <appender name="APISERVER" class="org.apache.log4j.rolling.RollingFileAppender">
+ <param name="Append" value="true"/>
+ <param name="Threshold" value="TRACE"/>
+ <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
+ <param name="FileNamePattern" value="@APISERVERLOG@.%d{yyyy-MM-dd}.gz"/>
+ <param name="ActiveFileName" value="@APISERVERLOG@"/>
+ </rollingPolicy>
+ <layout class="org.apache.log4j.EnhancedPatternLayout">
+ <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
+ </layout>
+ </appender>
+ -->
+
+
+ <!-- ============================== -->
+ <!-- Append warnings+ to the syslog if it is listening on UDP port FIXME make sysloghost configurable! -->
+ <!-- ============================== -->
+<!--
+ <appender name="SYSLOG" class="org.apache.log4j.net.SyslogAppender">
+ <param name="Threshold" value="WARN"/>
+ <param name="SyslogHost" value="localhost"/>
+ <param name="Facility" value="LOCAL6"/>
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="%-5p [%c{3}] (%t:%x) %m%n"/>
+ </layout>
+ </appender>
+-->
+ <!-- ============================== -->
+ <!-- Append messages to the console -->
+ <!-- ============================== -->
+
+ <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
+ <param name="Target" value="System.out"/>
+ <param name="Threshold" value="TRACE"/>
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
+ </layout>
+ </appender>
+
+ <!-- ================ -->
+ <!-- Limit categories -->
+ <!-- ================ -->
+
+ <category name="com.cloud">
+ <priority value="DEBUG"/>
+ </category>
+
+ <!-- Limit the org.apache category to INFO as its DEBUG is verbose -->
+ <category name="org.apache">
+ <priority value="INFO"/>
+ </category>
+
+ <category name="org">
+ <priority value="INFO"/>
+ </category>
+
+ <category name="net">
+ <priority value="INFO"/>
+ </category>
+
+ <category name="apiserver.com.cloud">
+ <priority value="DEBUG"/>
+ </category>
+
+ <!-- ======================= -->
+ <!-- Setup the Root category -->
+ <!-- ======================= -->
+
+ <root>
+ <level value="INFO"/>
+ <appender-ref ref="CONSOLE"/>
+ </root>
+
+</log4j:configuration>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/resources/testContext.xml
----------------------------------------------------------------------
diff --git a/utils/src/test/resources/testContext.xml b/utils/src/test/resources/testContext.xml
new file mode 100644
index 0000000..cb5b9b8
--- /dev/null
+++ b/utils/src/test/resources/testContext.xml
@@ -0,0 +1,52 @@
+<!--
+
+ 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.
+
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/tx
+ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/aop
+ http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+
+ <context:annotation-config />
+
+ <context:component-scan base-package="org.apache.cloudstack, com.cloud" />
+
+ <!--
+ @DB support
+ -->
+ <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
+
+ <bean id="instantiatePostProcessor" class="com.cloud.utils.component.ComponentInstantiationPostProcessor">
+ <property name="Interceptors">
+ <list>
+ <ref bean="transactionContextBuilder" />
+ </list>
+ </property>
+ </bean>
+
+</beans>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/DateUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/DateUtilTest.java b/utils/test/com/cloud/utils/DateUtilTest.java
deleted file mode 100644
index ba88505..0000000
--- a/utils/test/com/cloud/utils/DateUtilTest.java
+++ /dev/null
@@ -1,60 +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 com.cloud.utils;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.TimeZone;
-
-import com.cloud.utils.DateUtil.IntervalType;
-
-
-public class DateUtilTest {
-
- // command line test tool
- public static void main(String[] args) {
- TimeZone localTimezone = Calendar.getInstance().getTimeZone();
- TimeZone gmtTimezone = TimeZone.getTimeZone("GMT");
- TimeZone estTimezone = TimeZone.getTimeZone("EST");
-
- Date time = new Date();
- System.out.println("local time :" + DateUtil.getDateDisplayString(localTimezone, time));
- System.out.println("GMT time :" + DateUtil.getDateDisplayString(gmtTimezone, time));
- System.out.println("EST time :" + DateUtil.getDateDisplayString(estTimezone, time));
- //Test next run time. Expects interval and schedule as arguments
- if (args.length == 2) {
- System.out.println("Next run time: " + DateUtil.getNextRunTime(IntervalType.getIntervalType(args[0]), args[1], "GMT", time).toString());
- }
-
- time = new Date();
- DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z");
- String str = dfDate.format(time);
- System.out.println("Formated TZ time string : " + str);
- try {
- Date dtParsed = DateUtil.parseTZDateString(str);
- System.out.println("Parsed TZ time string : " + dtParsed.toString());
- } catch (ParseException e) {
- System.err.println("Parsing failed\n string : " + str + "\nexception :" + e.getLocalizedMessage());
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/DummyImpl.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/DummyImpl.java b/utils/test/com/cloud/utils/DummyImpl.java
deleted file mode 100644
index e2360c0..0000000
--- a/utils/test/com/cloud/utils/DummyImpl.java
+++ /dev/null
@@ -1,31 +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 com.cloud.utils;
-
-import org.springframework.stereotype.Component;
-
-@Component
-public class DummyImpl implements DummyInterface {
-
- @Override
- public void foo() {
- System.out.println("Basic foo implementation");
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/DummyInterface.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/DummyInterface.java b/utils/test/com/cloud/utils/DummyInterface.java
deleted file mode 100644
index 4f6a777..0000000
--- a/utils/test/com/cloud/utils/DummyInterface.java
+++ /dev/null
@@ -1,24 +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 com.cloud.utils;
-
-public interface DummyInterface {
- void foo();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/DummyPremiumImpl.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/DummyPremiumImpl.java b/utils/test/com/cloud/utils/DummyPremiumImpl.java
deleted file mode 100644
index 9c71368..0000000
--- a/utils/test/com/cloud/utils/DummyPremiumImpl.java
+++ /dev/null
@@ -1,28 +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 com.cloud.utils;
-
-public class DummyPremiumImpl implements DummyInterface {
-
- @Override
- public void foo() {
- System.out.println("Premium foo implementation");
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/HttpUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/HttpUtilsTest.java b/utils/test/com/cloud/utils/HttpUtilsTest.java
deleted file mode 100644
index e10a5a3..0000000
--- a/utils/test/com/cloud/utils/HttpUtilsTest.java
+++ /dev/null
@@ -1,94 +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 com.cloud.utils;
-
-import org.junit.Test;
-import org.springframework.mock.web.MockHttpSession;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpSession;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-public class HttpUtilsTest {
-
- @Test
- public void findCookieTest() {
- Cookie[] cookies = null;
- String cookieName = null;
-
- // null test
- assertNull(HttpUtils.findCookie(cookies, cookieName));
- cookieName = "";
- assertNull(HttpUtils.findCookie(cookies, cookieName));
-
- // value test
- cookieName = "daakuBandar";
- cookies = new Cookie[]{new Cookie(cookieName, "someValue")};
- assertNull(HttpUtils.findCookie(cookies, "aalasiLangur"));
- assertNotNull(HttpUtils.findCookie(cookies, cookieName));
- }
-
- @Test
- public void validateSessionKeyTest() {
- HttpSession session = null;
- Map<String, Object[]> params = null;
- String sessionKeyString = null;
- Cookie[] cookies = null;
- final String sessionKeyValue = "randomUniqueSessionID";
-
- // session and sessionKeyString null test
- assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
- sessionKeyString = "sessionkey";
- assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
-
- // param and cookie null test
- session = new MockHttpSession();
- session.setAttribute(sessionKeyString, sessionKeyValue);
- assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
-
- // param null, cookies not null test
- params = null;
- cookies = new Cookie[]{new Cookie(sessionKeyString, sessionKeyValue)};
- assertFalse(HttpUtils.validateSessionKey(session, params, cookies, "randomString"));
- assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
-
- // param not null, cookies null test
- params = new HashMap<String, Object[]>();
- params.put(sessionKeyString, new String[]{"randomString"});
- cookies = null;
- assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
- params.put(sessionKeyString, new String[]{sessionKeyValue});
- assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
-
- // both param and cookies not null test
- params = new HashMap<String, Object[]>();
- cookies = new Cookie[]{new Cookie(sessionKeyString, sessionKeyValue)};
- params.put(sessionKeyString, new String[]{"incorrectValue"});
- assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
- params.put(sessionKeyString, new String[]{sessionKeyValue});
- assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/NumbersUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/NumbersUtilTest.java b/utils/test/com/cloud/utils/NumbersUtilTest.java
deleted file mode 100644
index 82b2305..0000000
--- a/utils/test/com/cloud/utils/NumbersUtilTest.java
+++ /dev/null
@@ -1,47 +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 com.cloud.utils;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Locale;
-
-import org.junit.Test;
-
-public class NumbersUtilTest {
-
- @Test
- public void toReadableSize() {
- Locale.setDefault(Locale.US); // Fixed locale for the test
- assertEquals("1.0000 TB", NumbersUtil.toReadableSize((1024l * 1024l * 1024l * 1024l)));
- assertEquals("1.00 GB", NumbersUtil.toReadableSize(1024 * 1024 * 1024));
- assertEquals("1.00 MB", NumbersUtil.toReadableSize(1024 * 1024));
- assertEquals("1.00 KB", NumbersUtil.toReadableSize((1024)));
- assertEquals("1023 bytes", NumbersUtil.toReadableSize((1023)));
- }
-
- @Test
- public void bytesToLong() {
- assertEquals(0, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 0}));
- assertEquals(1, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 1}));
- assertEquals(257, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 1, 1}));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/PasswordGeneratorTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/PasswordGeneratorTest.java b/utils/test/com/cloud/utils/PasswordGeneratorTest.java
deleted file mode 100644
index 413b866..0000000
--- a/utils/test/com/cloud/utils/PasswordGeneratorTest.java
+++ /dev/null
@@ -1,42 +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 com.cloud.utils;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class PasswordGeneratorTest {
- @Test
- public void generateRandomPassword() {
- // actual length is requested length, minimum length is 3
- Assert.assertTrue(PasswordGenerator.generateRandomPassword(0).length() == 3);
- Assert.assertTrue(PasswordGenerator.generateRandomPassword(1).length() == 3);
- Assert.assertTrue(PasswordGenerator.generateRandomPassword(5).length() == 5);
- String password = PasswordGenerator.generateRandomPassword(8);
- // TODO: this might give more help to bruteforcing than desired
- // the actual behavior is that the first character is a random lowercase
- // char
- Assert.assertTrue(Character.isLowerCase(password.charAt(0)));
- // the second character is a random upper case char
- Assert.assertTrue(Character.isUpperCase(password.charAt(1)));
- // and the third is a digit
- Assert.assertTrue(Character.isDigit(password.charAt(2)));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/ProcessUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/ProcessUtilTest.java b/utils/test/com/cloud/utils/ProcessUtilTest.java
deleted file mode 100644
index 38e25a3..0000000
--- a/utils/test/com/cloud/utils/ProcessUtilTest.java
+++ /dev/null
@@ -1,76 +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 com.cloud.utils;
-
-import java.io.File;
-import java.io.IOException;
-
-import javax.naming.ConfigurationException;
-
-import junit.framework.Assert;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.SystemUtils;
-import org.junit.After;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Test;
-
-public class ProcessUtilTest {
-
- File pidFile;
-
- @Before
- public void setup() throws IOException {
- pidFile = File.createTempFile("test", ".pid");
- }
-
- @After
- public void cleanup() {
- FileUtils.deleteQuietly(pidFile);
- }
-
- @Test
- public void pidCheck() throws ConfigurationException, IOException {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- FileUtils.writeStringToFile(pidFile, "123456\n");
- ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
- String pidStr = FileUtils.readFileToString(pidFile);
- Assert.assertFalse("pid can not be blank", pidStr.isEmpty());
- int pid = Integer.parseInt(pidStr.trim());
- int maxPid = Integer.parseInt(FileUtils.readFileToString(new File("/proc/sys/kernel/pid_max")).trim());
- Assert.assertTrue(pid <= maxPid);
- }
-
- @Test(expected = ConfigurationException.class)
- public void pidCheckBadPid() throws ConfigurationException, IOException {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- FileUtils.writeStringToFile(pidFile, "intentionally not number");
- ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
- }
-
- @Test(expected = ConfigurationException.class)
- public void pidCheckEmptyPid() throws ConfigurationException, IOException {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- FileUtils.writeStringToFile(pidFile, "intentionally not number");
- ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/PropertiesUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/PropertiesUtilsTest.java b/utils/test/com/cloud/utils/PropertiesUtilsTest.java
deleted file mode 100644
index e20d7bf..0000000
--- a/utils/test/com/cloud/utils/PropertiesUtilsTest.java
+++ /dev/null
@@ -1,64 +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 com.cloud.utils;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class PropertiesUtilsTest {
- @Test
- public void findConfigFile() {
- File configFile = PropertiesUtil.findConfigFile("notexistingresource");
- Assert.assertNull(configFile);
- }
-
- @Test
- public void loadFromFile() throws IOException {
- File file = File.createTempFile("test", ".properties");
- FileUtils.writeStringToFile(file, "a=b\nc=d\n");
- Properties properties = new Properties();
- PropertiesUtil.loadFromFile(properties, file);
- Assert.assertEquals("b", properties.get("a"));
- }
-
- @Test
- public void loadPropertiesFromFile() throws IOException {
- File file = File.createTempFile("test", ".properties");
- FileUtils.writeStringToFile(file, "a=b\nc=d\n");
- Properties properties = PropertiesUtil.loadFromFile(file);
- Assert.assertEquals("b", properties.get("a"));
- }
-
- @Test
- public void processConfigFile() throws IOException {
- File tempFile = File.createTempFile("temp", ".properties");
- FileUtils.writeStringToFile(tempFile, "a=b\nc=d\n");
- Map<String, String> config = PropertiesUtil.processConfigFile(new String[] {tempFile.getAbsolutePath()});
- Assert.assertEquals("b", config.get("a"));
- Assert.assertEquals("d", config.get("c"));
- tempFile.delete();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/ReflectUtilTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/ReflectUtilTest.java b/utils/test/com/cloud/utils/ReflectUtilTest.java
deleted file mode 100644
index c024a2e..0000000
--- a/utils/test/com/cloud/utils/ReflectUtilTest.java
+++ /dev/null
@@ -1,148 +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 com.cloud.utils;
-
-import static com.cloud.utils.ReflectUtil.flattenProperties;
-import static com.google.common.collect.Lists.newArrayList;
-import static java.lang.Boolean.TRUE;
-import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertEquals;
-
-import java.lang.reflect.Field;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public final class ReflectUtilTest {
-
- @Test
- public void testFlattenNonNullProperties() throws Exception {
-
- final List<String> expectedResult = newArrayList("booleanProperty", TRUE.toString(), "intProperty", "1", "stringProperty", "foo");
-
- final Bean bean = new Bean(1, true, "foo");
-
- assertEquals(expectedResult, flattenProperties(bean, Bean.class));
-
- }
-
- @Test
- public void testFlattenNullProperties() throws Exception {
-
- final List<String> expectedResult = newArrayList("booleanProperty", TRUE.toString(), "intProperty", "1", "stringProperty", "null");
-
- final Bean bean = new Bean(1, true, null);
-
- assertEquals(expectedResult, flattenProperties(bean, Bean.class));
-
- }
-
- @Test
- public void testFlattenPropertiesNullTarget() throws Exception {
- assertEquals(emptyList(), flattenProperties(null, Bean.class));
- }
-
- public static final class Bean {
-
- private final int intProperty;
- private final boolean booleanProperty;
- private final String stringProperty;
-
- private Bean(final int intProperty, final boolean booleanProperty, final String stringProperty) {
-
- super();
-
- this.intProperty = intProperty;
- this.booleanProperty = booleanProperty;
- this.stringProperty = stringProperty;
-
- }
-
- public int getIntProperty() {
- return intProperty;
- }
-
- public boolean isBooleanProperty() {
- return booleanProperty;
- }
-
- public String getStringProperty() {
- return stringProperty;
- }
-
- }
-
- static class Empty {
- }
-
- static class Foo {
- String fooField;
- int fooIntField;
- }
-
- static class Bar extends Foo {
- String barField;
- int barIntField;
- }
-
- static class Baz extends Foo {
- String bazField;
- int bazIntField;
- }
-
- @Test
- public void getAllFieldsForClassWithFoo() throws NoSuchFieldException, SecurityException {
- Set<Field> fooFields = ReflectUtil.getAllFieldsForClass(Foo.class, new Class<?>[] {});
- Assert.assertNotNull(fooFields);
- Assert.assertTrue(fooFields.contains(Foo.class.getDeclaredField("fooField")));
- Assert.assertTrue(fooFields.contains(Foo.class.getDeclaredField("fooIntField")));
- }
-
- @Test
- public void getAllFieldsForClassWithBar() throws NoSuchFieldException, SecurityException {
- Set<Field> barFields = ReflectUtil.getAllFieldsForClass(Bar.class, new Class<?>[] {});
- Assert.assertNotNull(barFields);
- Assert.assertTrue(barFields.contains(Foo.class.getDeclaredField("fooField")));
- Assert.assertTrue(barFields.contains(Foo.class.getDeclaredField("fooIntField")));
- Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barField")));
- Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barIntField")));
- }
-
- @Test
- public void getAllFieldsForClassWithBarWithoutFoo() throws NoSuchFieldException, SecurityException {
- Set<Field> barFields = ReflectUtil.getAllFieldsForClass(Bar.class, new Class<?>[] {Foo.class});
- Assert.assertNotNull(barFields);
- Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barField")));
- Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barIntField")));
- }
-
- @Test
- public void getAllFieldsForClassWithBazWithoutBar() throws NoSuchFieldException, SecurityException {
- Set<Field> bazFields = ReflectUtil.getAllFieldsForClass(Baz.class, new Class<?>[] {Bar.class});
- Assert.assertNotNull(bazFields);
- Assert.assertTrue(bazFields.contains(Foo.class.getDeclaredField("fooField")));
- Assert.assertTrue(bazFields.contains(Foo.class.getDeclaredField("fooIntField")));
- Assert.assertTrue(bazFields.contains(Baz.class.getDeclaredField("bazField")));
- Assert.assertTrue(bazFields.contains(Baz.class.getDeclaredField("bazIntField")));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/ScriptTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/ScriptTest.java b/utils/test/com/cloud/utils/ScriptTest.java
deleted file mode 100644
index 99059bf..0000000
--- a/utils/test/com/cloud/utils/ScriptTest.java
+++ /dev/null
@@ -1,135 +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 com.cloud.utils;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-
-import org.apache.commons.lang.SystemUtils;
-import org.apache.log4j.Logger;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Matchers;
-import org.mockito.Mockito;
-
-import com.cloud.utils.script.OutputInterpreter;
-import com.cloud.utils.script.Script;
-
-public class ScriptTest {
- @Test
- public void testEcho() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Script script = new Script("/bin/echo");
- script.add("bar");
- OutputInterpreter.AllLinesParser resultParser = new OutputInterpreter.AllLinesParser();
- String result = script.execute(resultParser);
- // With allLinesParser, result is not comming from the return value
- Assert.assertNull(result);
- Assert.assertEquals("bar\n", resultParser.getLines());
- }
-
- @Test
- public void testLogger() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Logger mock = Mockito.mock(Logger.class);
- Mockito.doNothing().when(mock).debug(Matchers.any());
- Script script = new Script("/bin/echo", mock);
- script.execute();
- }
-
- @Test
- public void testToString() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Script script = new Script("/bin/echo");
- script.add("foo");
- Assert.assertEquals("/bin/echo foo ", script.toString());
- }
-
- @Test
- public void testSet() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Script script = new Script("/bin/echo");
- script.add("foo");
- script.add("bar", "baz");
- script.set("blah", "blah");
- Assert.assertEquals("/bin/echo foo bar baz blah blah ",
- script.toString());
- }
-
- @Test
- @Ignore
- public void testExecute() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Logger mock = Mockito.mock(Logger.class);
- Mockito.doNothing().when(mock).debug(Matchers.any());
- for (int i = 0; i < 100000; i++) {
- Script script = new Script("/bin/false", mock);
- script.execute();
- }
- }
-
- @Test
- public void testRunSimpleBashScript() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Assert.assertEquals("hello world!",
- Script.runSimpleBashScript("echo 'hello world!'"));
- }
-
- @Test
- public void executeWithOutputInterpreter() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Script script = new Script("/bin/bash");
- script.add("-c");
- script.add("echo 'hello world!'");
- String value = script.execute(new OutputInterpreter() {
-
- @Override
- public String interpret(BufferedReader reader) throws IOException {
- throw new IllegalArgumentException();
- }
- });
- // it is a stack trace in this case as string
- Assert.assertNotNull(value);
- }
-
- @Test
- public void runSimpleBashScriptNotExisting() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- String output = Script.runSimpleBashScript("/not/existing/scripts/"
- + System.currentTimeMillis());
- Assert.assertNull(output);
- }
-
- @Test
- public void testRunSimpleBashScriptWithTimeout() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- Assert.assertEquals("hello world!",
- Script.runSimpleBashScript("echo 'hello world!'", 1000));
- }
-
- @Test
- public void testFindScript() {
- Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
- String script = Script.findScript("/bin", "pwd");
- Assert.assertNotNull("/bin/pwd shoud be there on linux", script);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/StringUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/StringUtilsTest.java b/utils/test/com/cloud/utils/StringUtilsTest.java
deleted file mode 100644
index 3619ede..0000000
--- a/utils/test/com/cloud/utils/StringUtilsTest.java
+++ /dev/null
@@ -1,253 +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 com.cloud.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.junit.Test;
-
-public class StringUtilsTest {
-
- @Test
- public void testGetPreferredCharset() {
- final boolean ifUtf8Supported = StringUtils.isUtf8Supported();
- if (ifUtf8Supported) {
- assertEquals(StringUtils.getPreferredCharset(), Charset.forName("UTF-8"));
- } else {
- assertNotEquals(StringUtils.getPreferredCharset(), Charset.forName("UTF-8"));
- }
- }
-
- @Test
- public void testGetDefaultCharset() {
- // Is this test irrelevant? Is wrapping the Charset.defaultCharset() too much?
- // This test was added in order to cover the new StringUtils.getDefaultCharset().
- // One cannot be sure that StringUtils.getPreferredCharset() will always be
- // equals to Charset.defaultCharset()
- assertEquals(StringUtils.getDefaultCharset(), Charset.defaultCharset());
- }
-
- @Test
- public void testCleanPasswordFromJsonObjectAtEnd() {
- final String input = "{\"foo\":\"bar\",\"password\":\"test\"}";
- //TODO: It would be nice to clean up the regex in question to not
- //have to return the trailing comma in the expected string below
- final String expected = "{\"foo\":\"bar\",}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromJsonObjectInMiddle() {
- final String input = "{\"foo\":\"bar\",\"password\":\"test\",\"test\":\"blah\"}";
- final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromJsonObjectAlone() {
- final String input = "{\"password\":\"test\"}";
- final String expected = "{}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromJsonObjectAtStart() {
- final String input = "{\"password\":\"test\",\"test\":\"blah\"}";
- final String expected = "{\"test\":\"blah\"}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromJsonObjectWithMultiplePasswords() {
- final String input = "{\"description\":\"foo\"}],\"password\":\"bar\",\"nic\":[{\"password\":\"bar2\",\"id\":\"1\"}]}";
- final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromRequestString() {
- final String input = "username=foo&password=bar&url=foobar";
- final String expected = "username=foo&url=foobar";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromEncodedRequestString() {
- final String input = "name=SS1&provider=SMB&zoneid=5a60af2b-3025-4f2a-9ecc-8e33bf2b94e3&url=cifs%3A%2F%2F10.102.192.150%2FSMB-Share%2Fsowmya%2Fsecondary%3Fuser%3Dsowmya%26password%3DXXXXX%40123%26domain%3DBLR";
- final String expected = "name=SS1&provider=SMB&zoneid=5a60af2b-3025-4f2a-9ecc-8e33bf2b94e3&url=cifs%3A%2F%2F10.102.192.150%2FSMB-Share%2Fsowmya%2Fsecondary%3Fuser%3Dsowmya%26domain%3DBLR";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromRequestStringWithMultiplePasswords() {
- final String input = "username=foo&password=bar&url=foobar&password=bar2&test=4";
- final String expected = "username=foo&url=foobar&test=4";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromRequestStringMatchedAtEndSingleQuote() {
- final String input = "'username=foo&password=bar'";
- final String expected = "'username=foo'";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromRequestStringMatchedAtEndDoubleQuote() {
- final String input = "\"username=foo&password=bar\"";
- final String expected = "\"username=foo\"";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanPasswordFromRequestStringMatchedAtMiddleDoubleQuote() {
- final String input = "\"username=foo&password=bar&goo=sdf\"";
- final String expected = "\"username=foo&goo=sdf\"";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testJoin() {
- assertEquals("a-b-c", StringUtils.join("-", "a", "b", "c"));
- assertEquals("", StringUtils.join("-"));
- }
-
- @Test
- public void testCleanSecretkeyFromJsonObjectAtEnd() {
- final String input = "{\"foo\":\"bar\",\"secretkey\":\"test\"}";
- // TODO: It would be nice to clean up the regex in question to not
- // have to return the trailing comma in the expected string below
- final String expected = "{\"foo\":\"bar\",}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanSecretkeyFromJsonObjectInMiddle() {
- final String input = "{\"foo\":\"bar\",\"secretkey\":\"test\",\"test\":\"blah\"}";
- final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanSecretkeyFromJsonObjectAlone() {
- final String input = "{\"secretkey\":\"test\"}";
- final String expected = "{}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanSecretkeyFromJsonObjectAtStart() {
- final String input = "{\"secretkey\":\"test\",\"test\":\"blah\"}";
- final String expected = "{\"test\":\"blah\"}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanSecretkeyFromJsonObjectWithMultiplePasswords() {
- final String input = "{\"description\":\"foo\"}],\"secretkey\":\"bar\",\"nic\":[{\"secretkey\":\"bar2\",\"id\":\"1\"}]}";
- final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanAccesskeyFromJsonObjectAtEnd() {
- final String input = "{\"foo\":\"bar\",\"accesskey\":\"test\"}";
- // TODO: It would be nice to clean up the regex in question to not
- // have to return the trailing comma in the expected string below
- final String expected = "{\"foo\":\"bar\",}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanAccesskeyFromJsonObjectInMiddle() {
- final String input = "{\"foo\":\"bar\",\"accesskey\":\"test\",\"test\":\"blah\"}";
- final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanAccesskeyFromJsonObjectAlone() {
- final String input = "{\"accesskey\":\"test\"}";
- final String expected = "{}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanAccesskeyFromJsonObjectAtStart() {
- final String input = "{\"accesskey\":\"test\",\"test\":\"blah\"}";
- final String expected = "{\"test\":\"blah\"}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanAccesskeyFromJsonObjectWithMultiplePasswords() {
- final String input = "{\"description\":\"foo\"}],\"accesskey\":\"bar\",\"nic\":[{\"accesskey\":\"bar2\",\"id\":\"1\"}]}";
- final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanAccesskeyFromRequestString() {
- final String input = "username=foo&accesskey=bar&url=foobar";
- final String expected = "username=foo&url=foobar";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void testCleanSecretkeyFromRequestString() {
- final String input = "username=foo&secretkey=bar&url=foobar";
- final String expected = "username=foo&url=foobar";
- final String result = StringUtils.cleanString(input);
- assertEquals(result, expected);
- }
-
- @Test
- public void listToCsvTags() {
- assertEquals("a,b,c", StringUtils.listToCsvTags(Arrays.asList("a","b", "c")));
- assertEquals("", StringUtils.listToCsvTags(new ArrayList<String>()));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/TernaryTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/TernaryTest.java b/utils/test/com/cloud/utils/TernaryTest.java
deleted file mode 100644
index cacbecb..0000000
--- a/utils/test/com/cloud/utils/TernaryTest.java
+++ /dev/null
@@ -1,34 +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 com.cloud.utils;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class TernaryTest {
- @Test
- public void testEquals() {
- Assert.assertEquals(new Ternary<String, String, String>("a", "b", "c"), new Ternary<String, String, String>("a", "b", "c"));
- Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(new Ternary<String, String, String>("a", "b", "d")));
- Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(""));
- Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(null));
- Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(new Pair<String, String>("a", "b")));
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/TestProfiler.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/TestProfiler.java b/utils/test/com/cloud/utils/TestProfiler.java
deleted file mode 100644
index 2306cd7..0000000
--- a/utils/test/com/cloud/utils/TestProfiler.java
+++ /dev/null
@@ -1,116 +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 com.cloud.utils;
-
-import org.apache.log4j.Logger;
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.cloud.utils.testcase.Log4jEnabledTestCase;
-
-public class TestProfiler extends Log4jEnabledTestCase {
- protected final static Logger s_logger = Logger.getLogger(TestProfiler.class);
-
- private static final long ONE_SECOND = 1000l;
- private static final long MILLIS_FACTOR = 1000l;
- private static final int MARGIN = 100;
- private static final double EXPONENT = 3d;
-
- @Test
- public void testProfilerInMillis() {
- s_logger.info("testProfiler() started");
-
- final Profiler pf = new Profiler();
- pf.start();
- try {
- Thread.sleep(ONE_SECOND);
- } catch (final InterruptedException e) {
- }
- pf.stop();
-
- final long durationInMillis = pf.getDurationInMillis();
- s_logger.info("Duration in Millis: " + durationInMillis);
-
- // An error margin in order to cover the time taken by the star/stop calls.
- // 100 milliseconds margin seems too much, but it will avoid assertion error
- // and also fail in case a duration in nanoseconds is used instead.
- Assert.assertTrue(durationInMillis >= MILLIS_FACTOR && durationInMillis <= MILLIS_FACTOR + MARGIN);
-
- s_logger.info("testProfiler() stopped");
- }
-
- @Test
- public void testProfilerInNano() {
- final Profiler pf = new Profiler();
- pf.start();
- try {
- Thread.sleep(ONE_SECOND);
- } catch (final InterruptedException e) {
- }
- pf.stop();
-
- final long duration = pf.getDuration();
- s_logger.info("Duration in Nano: " + duration);
- Assert.assertTrue(duration >= Math.pow(MILLIS_FACTOR, EXPONENT));
- }
-
- @Test
- public void testProfilerNoStart() {
- final Profiler pf = new Profiler();
- try {
- Thread.sleep(20);
- } catch (final InterruptedException e) {
- }
- pf.stop();
-
- Assert.assertTrue(pf.getDurationInMillis() == -1);
- Assert.assertFalse(pf.isStarted());
- }
-
- @Test
- public void testProfilerNoStop() {
- final Profiler pf = new Profiler();
- pf.start();
- try {
- Thread.sleep(20);
- } catch (final InterruptedException e) {
- }
-
- Assert.assertTrue(pf.getDurationInMillis() == -1);
- Assert.assertFalse(pf.isStopped());
- }
-
- @Test
- public void testResolution() {
- long nanoTime1 = 0l;
- long nanoTime2 = 0l;
- nanoTime1 = System.nanoTime();
- nanoTime2 = System.nanoTime();
-
- // Using sysout here because is faster than the logger and we don't want to
- // waste time.
- System.out.println("Nano time 1: " + nanoTime1);
- System.out.println("Nano time 2: " + nanoTime2);
-
- // We are measuring the elapsed time in 2 consecutive calls of System.nanoTime()
- // That's the same as 0.002 milliseconds or 2000 nanoseconds.
- Assert.assertTrue("Expected exactly 2 but it took more than 3 microseconds between 2 consecutive calls to System.nanoTime().", nanoTime2 - nanoTime1 <= 3000);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/UriUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/UriUtilsTest.java b/utils/test/com/cloud/utils/UriUtilsTest.java
deleted file mode 100644
index d2fd997..0000000
--- a/utils/test/com/cloud/utils/UriUtilsTest.java
+++ /dev/null
@@ -1,60 +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 com.cloud.utils;
-
-import junit.framework.Assert;
-
-import org.junit.Test;
-
-public class UriUtilsTest {
- @Test
- public void encodeURIComponent() {
- Assert.assertEquals("http://localhost",
- UriUtils.encodeURIComponent("http://localhost"));
- Assert.assertEquals("http://localhost/",
- UriUtils.encodeURIComponent("http://localhost/"));
- Assert.assertEquals("http://localhost/foo/bar",
- UriUtils.encodeURIComponent("http://localhost/foo/bar"));
- }
-
- @Test
- public void getUpdateUri() {
- // no password param, no request for encryption
- Assert.assertEquals("http://localhost/foo/bar?param=true", UriUtils
- .getUpdateUri("http://localhost/foo/bar?param=true", false));
- // there is password param but still no request for encryption, should
- // be unchanged
- Assert.assertEquals("http://localhost/foo/bar?password=1234", UriUtils
- .getUpdateUri("http://localhost/foo/bar?password=1234", false));
- // if there is password param and encryption is requested then it may or
- // may not be changed depending on how the EncrytionUtils is setup, but
- // at least it needs to start with the same url
- Assert.assertTrue(UriUtils.getUpdateUri(
- "http://localhost/foo/bar?password=1234", true).startsWith(
- "http://localhost/foo/bar"));
-
- //just to see if it is still ok with multiple parameters
- Assert.assertEquals("http://localhost/foo/bar?param1=true¶m2=12345", UriUtils
- .getUpdateUri("http://localhost/foo/bar?param1=true¶m2=12345", false));
-
- //XXX: Interesting cases not covered:
- // * port is ignored and left out from the return value
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/UuidUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/UuidUtilsTest.java b/utils/test/com/cloud/utils/UuidUtilsTest.java
deleted file mode 100644
index 2ef6bbd..0000000
--- a/utils/test/com/cloud/utils/UuidUtilsTest.java
+++ /dev/null
@@ -1,42 +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 com.cloud.utils;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class UuidUtilsTest {
-
- @Test
- public void testValidateUUIDPass() throws Exception {
- String serviceUuid = "f81a9aa3-1f7d-466f-b04b-f2b101486bae";
-
- assertTrue(UuidUtils.validateUUID(serviceUuid));
- }
-
- @Test
- public void testValidateUUIDFail() throws Exception {
- String serviceUuid = "6fc6ce7-d503-4f95-9e68-c9cd281b13df";
-
- assertFalse(UuidUtils.validateUUID(serviceUuid));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/test/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java b/utils/test/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java
deleted file mode 100644
index d397511..0000000
--- a/utils/test/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java
+++ /dev/null
@@ -1,112 +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 com.cloud.utils.backoff.impl;
-
-import java.util.HashMap;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ConstantTimeBackoffTest {
- final static private Log LOG = LogFactory.getLog(ConstantTimeBackoffTest.class);
-
- @Test
- public void waitBeforeRetryWithInterrupt() throws InterruptedException {
- final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
- backoff.setTimeToWait(10);
- Assert.assertTrue(backoff.getWaiters().isEmpty());
- Thread waitThread = new Thread(new Runnable() {
- @Override
- public void run() {
- backoff.waitBeforeRetry();
- }
- });
- waitThread.start();
- Thread.sleep(100);
- Assert.assertFalse(backoff.getWaiters().isEmpty());
- waitThread.interrupt();
- Thread.sleep(100);
- Assert.assertTrue(backoff.getWaiters().isEmpty());
- }
-
- @Test
- public void waitBeforeRetry() throws InterruptedException {
- final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
- // let's not wait too much in a test
- backoff.setTimeToWait(0);
- // check if the list of waiters is empty
- Assert.assertTrue(backoff.getWaiters().isEmpty());
- // call the waitBeforeRetry which will wait 0 ms and return
- backoff.waitBeforeRetry();
- // on normal exit the list of waiters should be cleared
- Assert.assertTrue(backoff.getWaiters().isEmpty());
- }
-
- @Test
- public void configureEmpty() {
- // at this point this is the only way rhe configure method gets invoked,
- // therefore have to make sure it works correctly
- final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
- backoff.configure("foo", new HashMap<String, Object>());
- Assert.assertEquals(5000, backoff.getTimeToWait());
- }
-
- @Test
- public void configureWithValue() {
- final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
- HashMap<String, Object> params = new HashMap<String, Object>();
- params.put("seconds", "100");
- backoff.configure("foo", params);
- Assert.assertEquals(100000, backoff.getTimeToWait());
- }
-
- /**
- * Test that wakeup returns false when trying to wake a non existing thread.
- */
- @Test
- public void wakeupNotExisting() {
- final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
- Assert.assertFalse(backoff.wakeup("NOT EXISTING THREAD"));
- }
-
- /**
- * Test that wakeup will return true if the thread is waiting.
- */
- @Test
- public void wakeupExisting() throws InterruptedException {
- final ConstantTimeBackoff backoff = new ConstantTimeBackoff();
- backoff.setTimeToWait(10);
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- LOG.debug("before");
- backoff.waitBeforeRetry();
- LOG.debug("after");
- }
- });
- thread.start();
- LOG.debug("thread started");
- Thread.sleep(100);
- LOG.debug("testing wakeup");
- Assert.assertTrue(backoff.wakeup(thread.getName()));
- }
-}
[20/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/HttpUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/HttpUtils.java b/utils/src/main/java/com/cloud/utils/HttpUtils.java
new file mode 100644
index 0000000..d2e844a
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/HttpUtils.java
@@ -0,0 +1,114 @@
+//
+// 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 com.cloud.utils;
+
+import org.apache.log4j.Logger;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.util.Map;
+
+public class HttpUtils {
+
+ public static final Logger s_logger = Logger.getLogger(HttpUtils.class);
+
+ public static final String UTF_8 = "UTF-8";
+ public static final String RESPONSE_TYPE_JSON = "json";
+ public static final String RESPONSE_TYPE_XML = "xml";
+ public static final String JSON_CONTENT_TYPE = "application/json; charset=UTF-8";
+ public static final String XML_CONTENT_TYPE = "text/xml; charset=UTF-8";
+
+ public static void addSecurityHeaders(final HttpServletResponse resp) {
+ if (resp.containsHeader("X-Content-Type-Options")) {
+ resp.setHeader("X-Content-Type-Options", "nosniff");
+ }
+ else {
+ resp.addHeader("X-Content-Type-Options", "nosniff");
+ }
+ if (resp.containsHeader("X-XSS-Protection")) {
+ resp.setHeader("X-XSS-Protection", "1;mode=block");
+ }
+ else {
+ resp.addHeader("X-XSS-Protection", "1;mode=block");
+ }
+ }
+
+ public static void writeHttpResponse(final HttpServletResponse resp, final String response,
+ final Integer responseCode, final String responseType, final String jsonContentType) {
+ try {
+ if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
+ if (jsonContentType != null && !jsonContentType.isEmpty()) {
+ resp.setContentType(jsonContentType);
+ } else {
+ resp.setContentType(JSON_CONTENT_TYPE);
+ }
+ } else if (RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)){
+ resp.setContentType(XML_CONTENT_TYPE);
+ }
+ if (responseCode != null) {
+ resp.setStatus(responseCode);
+ }
+ addSecurityHeaders(resp);
+ resp.getWriter().print(response);
+ } catch (final IOException ioex) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Exception writing http response: " + ioex);
+ }
+ } catch (final Exception ex) {
+ if (!(ex instanceof IllegalStateException)) {
+ s_logger.error("Unknown exception writing http response", ex);
+ }
+ }
+ }
+
+ public static String findCookie(final Cookie[] cookies, final String key) {
+ if (cookies == null || key == null || key.isEmpty()) {
+ return null;
+ }
+ for (Cookie cookie: cookies) {
+ if (cookie != null && cookie.getName().equals(key)) {
+ return cookie.getValue();
+ }
+ }
+ return null;
+ }
+
+ public static boolean validateSessionKey(final HttpSession session, final Map<String, Object[]> params, final Cookie[] cookies, final String sessionKeyString) {
+ if (session == null || sessionKeyString == null) {
+ return false;
+ }
+ final String sessionKey = (String) session.getAttribute(sessionKeyString);
+ final String sessionKeyFromCookie = HttpUtils.findCookie(cookies, sessionKeyString);
+ String[] sessionKeyFromParams = null;
+ if (params != null) {
+ sessionKeyFromParams = (String[]) params.get(sessionKeyString);
+ }
+ if ((sessionKey == null)
+ || (sessionKeyFromParams == null && sessionKeyFromCookie == null)
+ || (sessionKeyFromParams != null && !sessionKey.equals(sessionKeyFromParams[0]))
+ || (sessionKeyFromCookie != null && !sessionKey.equals(sessionKeyFromCookie))) {
+ return false;
+ }
+ return true;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/IteratorUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/IteratorUtil.java b/utils/src/main/java/com/cloud/utils/IteratorUtil.java
new file mode 100644
index 0000000..8ab88f5
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/IteratorUtil.java
@@ -0,0 +1,72 @@
+//
+// 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 com.cloud.utils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+
+public class IteratorUtil {
+ public static <T> Iterable<T> enumerationAsIterable(final Enumeration<T> e) {
+ return new Iterable<T>() {
+ @Override
+ public Iterator<T> iterator() {
+ return new Iterator<T>() {
+ @Override
+ public boolean hasNext() {
+ return e.hasMoreElements();
+ }
+
+ @Override
+ public T next() {
+ return e.nextElement();
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+ };
+ }
+
+ public static <T> Enumeration<T> iteratorAsEnumeration(final Iterator<T> it) {
+ return new Enumeration<T>() {
+ @Override
+ public boolean hasMoreElements() {
+ return it.hasNext();
+ }
+
+ @Override
+ public T nextElement() {
+ return it.next();
+ }
+ };
+ }
+
+ public static <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
+ List<T> list = new ArrayList<T>(c);
+ java.util.Collections.sort(list);
+ return list;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/Journal.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/Journal.java b/utils/src/main/java/com/cloud/utils/Journal.java
new file mode 100644
index 0000000..e88dba3
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/Journal.java
@@ -0,0 +1,104 @@
+//
+// 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 com.cloud.utils;
+
+import java.util.ArrayList;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+
+/**
+ * Journal is used to kept what has happened during a process so someone can track
+ * what happens during a process.
+ *
+ */
+public class Journal {
+ String _name;
+ ArrayList<Pair<String, Object[]>> _entries;
+
+ public Journal(String name) {
+ _name = name;
+ _entries = new ArrayList<Pair<String, Object[]>>();
+ }
+
+ final private void log(String msg, Object... params) {
+ Pair<String, Object[]> entry = new Pair<String, Object[]>(msg, params);
+ assert msg != null : "Message can not be null or else it's useless!";
+ _entries.add(entry);
+ }
+
+ public void record(String msg, Object... params) {
+ log(msg, params);
+ }
+
+ public void record(Logger logger, Level p, String msg, Object... params) {
+ if (logger.isEnabledFor(p)) {
+ StringBuilder buf = new StringBuilder();
+ toString(buf, msg, params);
+ String entry = buf.toString();
+ log(entry);
+ logger.log(p, entry);
+ } else {
+ log(msg, params);
+ }
+ }
+
+ protected void toString(StringBuilder buf, String msg, Object[] params) {
+ buf.append(msg);
+ if (params != null) {
+ buf.append(" - ");
+ int i = 0;
+ for (Object obj : params) {
+ buf.append('P').append(i).append('=');
+ buf.append(obj != null ? obj.toString() : "null");
+ buf.append(", ");
+ }
+ buf.delete(buf.length() - 2, buf.length());
+ }
+ }
+
+ public String toString(String separator) {
+ StringBuilder buf = new StringBuilder(_name).append(": ");
+ for (Pair<String, Object[]> entry : _entries) {
+ toString(buf, entry.first(), entry.second());
+ buf.append(separator);
+ }
+ return buf.toString();
+ }
+
+ @Override
+ public String toString() {
+ return toString("; ");
+ }
+
+ public static class LogJournal extends Journal {
+ Logger _logger;
+
+ public LogJournal(String name, Logger logger) {
+ super(name);
+ _logger = logger;
+ }
+
+ @Override
+ public void record(String msg, Object... params) {
+ record(_logger, Level.DEBUG, msg, params);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/LogUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/LogUtils.java b/utils/src/main/java/com/cloud/utils/LogUtils.java
new file mode 100644
index 0000000..d86766c
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/LogUtils.java
@@ -0,0 +1,45 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.xml.DOMConfigurator;
+
+public class LogUtils {
+ public static final Logger s_logger = Logger.getLogger(LogUtils.class);
+
+ public static void initLog4j(String log4jConfigFileName) {
+ assert (log4jConfigFileName != null);
+ File file = PropertiesUtil.findConfigFile(log4jConfigFileName);
+ if (file != null) {
+ s_logger.info("log4j configuration found at " + file.getAbsolutePath());
+ DOMConfigurator.configureAndWatch(file.getAbsolutePath());
+ } else {
+ String nameWithoutExtension = log4jConfigFileName.substring(0, log4jConfigFileName.lastIndexOf('.'));
+ file = PropertiesUtil.findConfigFile(nameWithoutExtension + ".properties");
+ if (file != null) {
+ s_logger.info("log4j configuration found at " + file.getAbsolutePath());
+ DOMConfigurator.configureAndWatch(file.getAbsolutePath());
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/MethodCapturer.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/MethodCapturer.java b/utils/src/main/java/com/cloud/utils/MethodCapturer.java
new file mode 100644
index 0000000..655a45d
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/MethodCapturer.java
@@ -0,0 +1,113 @@
+//
+// 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 com.cloud.utils;
+
+import java.lang.reflect.Method;
+import java.util.WeakHashMap;
+
+import net.sf.cglib.proxy.Callback;
+import net.sf.cglib.proxy.CallbackFilter;
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodInterceptor;
+import net.sf.cglib.proxy.MethodProxy;
+
+/*
+ * This helper class provides a way to retrieve Method in a strong-type way. It takes advantage of power of
+ * Intelligent IDE(Eclipse) in code-editing
+ *
+ * DummyImpl dummy = new DummyImpl();
+ * MethodCapturer<DummyImpl> capturer = MethodCapturer.capture(dummy);
+ * Method method = capturer.get(capturer.instance().foo2());
+ *
+ */
+public class MethodCapturer<T> {
+
+ private final static int CACHE_SIZE = 1024;
+
+ private T _instance;
+ private Method _method;
+
+ private static WeakHashMap<Object, Object> s_cache = new WeakHashMap<Object, Object>();
+
+ private MethodCapturer() {
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> MethodCapturer<T> capture(T obj) {
+ synchronized (s_cache) {
+ MethodCapturer<T> capturer = (MethodCapturer<T>)s_cache.get(obj);
+ if (capturer != null) {
+ return capturer;
+ }
+
+ final MethodCapturer<T> capturerNew = new MethodCapturer<T>();
+
+ Enhancer en = new Enhancer();
+ en.setSuperclass(obj.getClass());
+ en.setCallbacks(new Callback[] {new MethodInterceptor() {
+ @Override
+ public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
+ capturerNew.setMethod(arg1);
+ return null;
+ }
+ }, new MethodInterceptor() {
+ @Override
+ public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
+ return null;
+ }
+ }});
+ en.setCallbackFilter(new CallbackFilter() {
+ @Override
+ public int accept(Method method) {
+ if (method.getParameterTypes().length == 0 && method.getName().equals("finalize")) {
+ return 1;
+ }
+ return 0;
+ }
+ });
+
+ capturerNew.setInstance((T)en.create());
+
+ // We expect MethodCapturer is only used for singleton objects here, so we only maintain a limited cache
+ // here
+ if (s_cache.size() < CACHE_SIZE) {
+ s_cache.put(obj, capturerNew);
+ }
+
+ return capturerNew;
+ }
+ }
+
+ public T instance() {
+ return _instance;
+ }
+
+ private void setInstance(T instance) {
+ _instance = instance;
+ }
+
+ public Method get(Object... useless) {
+ return _method;
+ }
+
+ private void setMethod(Method method) {
+ _method = method;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/NumbersUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/NumbersUtil.java b/utils/src/main/java/com/cloud/utils/NumbersUtil.java
new file mode 100644
index 0000000..8b93a40
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/NumbersUtil.java
@@ -0,0 +1,139 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils;
+
+import java.nio.ByteBuffer;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Formatter;
+import java.util.Locale;
+
+import org.apache.commons.lang.math.NumberUtils;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class NumbersUtil {
+ public static long parseLong(String s, long defaultValue) {
+ return NumberUtils.toLong(s, defaultValue);
+ }
+
+ public static int parseInt(String s, int defaultValue) {
+ return NumberUtils.toInt(s, defaultValue);
+ }
+
+ public static float parseFloat(String s, float defaultValue) {
+ return NumberUtils.toFloat(s, defaultValue);
+ }
+
+ /**
+ * Converts bytes to long on input.
+ */
+ public static long bytesToLong(byte b[]) {
+ return bytesToLong(b, 0);
+ }
+
+ public static long bytesToLong(byte b[], int pos) {
+ return ByteBuffer.wrap(b, pos, 8).getLong();
+ }
+
+ /**
+ * Converts a byte array to a hex readable string.
+ **/
+ public static String bytesToString(byte[] data, int start, int end) {
+ StringBuilder buf = new StringBuilder();
+ if (end > data.length) {
+ end = data.length;
+ }
+ for (int i = start; i < end; i++) {
+ buf.append(" ");
+ buf.append(Integer.toHexString(data[i] & 0xff));
+ }
+ return buf.toString();
+ }
+
+ protected static final long KB = 1024;
+ protected static final long MB = 1024 * KB;
+ protected static final long GB = 1024 * MB;
+ protected static final long TB = 1024 * GB;
+
+ public static String toReadableSize(long bytes) {
+ if (bytes < KB && bytes >= 0) {
+ return Long.toString(bytes) + " bytes";
+ }
+ StringBuilder builder = new StringBuilder();
+ Formatter format = new Formatter(builder, Locale.getDefault());
+ if (bytes < MB) {
+ format.format("%.2f KB", (float)bytes / (float)KB);
+ } else if (bytes < GB) {
+ format.format("%.2f MB", (float)bytes / (float)MB);
+ } else if (bytes < TB) {
+ format.format("%.2f GB", (float)bytes / (float)GB);
+ } else {
+ format.format("%.4f TB", (float)bytes / (float)TB);
+ }
+ format.close();
+ return builder.toString();
+ }
+
+ /**
+ * Converts a string of the format 'yy-MM-dd'T'HH:mm:ss.SSS" into ms.
+ *
+ * @param str containing the interval.
+ * @param defaultValue value to return if str doesn't parse. If -1, throws VmopsRuntimeException
+ * @return interval in ms
+ */
+ public static long parseInterval(String str, long defaultValue) {
+ try {
+ if (str == null) {
+ throw new ParseException("String is wrong", 0);
+ }
+
+ SimpleDateFormat sdf = null;
+ if (str.contains("D")) {
+ sdf = new SimpleDateFormat("dd'D'HH'h'mm'M'ss'S'SSS'ms'");
+ } else if (str.contains("h")) {
+ sdf = new SimpleDateFormat("HH'h'mm'M'ss'S'SSS'ms'");
+ } else if (str.contains("M")) {
+ sdf = new SimpleDateFormat("mm'M'ss'S'SSS'ms'");
+ } else if (str.contains("S")) {
+ sdf = new SimpleDateFormat("ss'S'SSS'ms'");
+ } else if (str.contains("ms")) {
+ sdf = new SimpleDateFormat("SSS'ms'");
+ }
+ if (sdf == null) {
+ throw new ParseException("String is wrong", 0);
+ }
+
+ Date date = sdf.parse(str);
+ return date.getTime();
+ } catch (ParseException e) {
+ if (defaultValue != -1) {
+ return defaultValue;
+ } else {
+ throw new CloudRuntimeException("Unable to parse: " + str, e);
+ }
+ }
+ }
+
+ public static int hash(long value) {
+ return (int)(value ^ (value >>> 32));
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/Pair.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/Pair.java b/utils/src/main/java/com/cloud/utils/Pair.java
new file mode 100644
index 0000000..73d3562
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/Pair.java
@@ -0,0 +1,87 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.Serializable;
+
+public class Pair<T, U> implements Serializable {
+ private static final long serialVersionUID = 2L;
+ T t;
+ U u;
+
+ protected Pair() {
+
+ }
+
+ public Pair(T t, U u) {
+ this.t = t;
+ this.u = u;
+ }
+
+ public T first() {
+ return t;
+ }
+
+ public U second() {
+ return u;
+ }
+
+ public U second(U value) {
+ u = value;
+ return u;
+ }
+
+ public T first(T value) {
+ t = value;
+ return t;
+ }
+
+ public void set(T t, U u) {
+ this.t = t;
+ this.u = u;
+ }
+
+ @Override
+ // Note: This means any two pairs with null for both values will match each
+ // other but what can I do? This is due to stupid type erasure.
+ public
+ int hashCode() {
+ return (t != null ? t.hashCode() : 0) | (u != null ? u.hashCode() : 0);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Pair)) {
+ return false;
+ }
+ Pair<?, ?> that = (Pair<?, ?>)obj;
+ return (t != null ? t.equals(that.t) : that.t == null) && (u != null ? u.equals(that.u) : that.u == null);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder("P[");
+ b.append((t != null) ? t.toString() : "null");
+ b.append(":");
+ b.append((u != null) ? u.toString() : "null");
+ b.append("]");
+ return b.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/PasswordGenerator.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/PasswordGenerator.java b/utils/src/main/java/com/cloud/utils/PasswordGenerator.java
new file mode 100644
index 0000000..0d79143
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/PasswordGenerator.java
@@ -0,0 +1,90 @@
+//
+// 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 com.cloud.utils;
+
+import java.security.SecureRandom;
+import java.util.Random;
+
+/**
+ * Generate random passwords
+ *
+ */
+public class PasswordGenerator {
+ //Leave out visually confusing l,L,1,o,O,0
+ static private char[] lowerCase = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
+ static private char[] upperCase = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
+ static private char[] numeric = new char[] {'2', '3', '4', '5', '6', '7', '8', '9'};
+
+ static private char[] alphaNumeric = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
+ 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9'};
+
+ static private int minLength = 3;
+
+ public static String generateRandomPassword(int num) {
+ Random r = new SecureRandom();
+ StringBuilder password = new StringBuilder();
+
+ //Guard for num < minLength
+ if (num < minLength) {
+ //Add alphanumeric chars at random
+ for (int i = 0; i < minLength; i++) {
+ password.append(generateAlphaNumeric(r));
+ }
+ } else {
+ // Generate random 3-character string with a lowercase character,
+ // uppercase character, and a digit
+ password.append(generateLowercaseChar(r)).append(generateUppercaseChar(r)).append(generateDigit(r));
+
+ // Generate a random n-character string with only lowercase
+ // characters
+ for (int i = 0; i < num - 3; i++) {
+ password.append(generateLowercaseChar(r));
+ }
+ }
+
+ return password.toString();
+ }
+
+ private static char generateLowercaseChar(Random r) {
+ return lowerCase[r.nextInt(lowerCase.length)];
+ }
+
+ private static char generateDigit(Random r) {
+ return numeric[r.nextInt(numeric.length)];
+ }
+
+ private static char generateUppercaseChar(Random r) {
+ return upperCase[r.nextInt(upperCase.length)];
+ }
+
+ private static char generateAlphaNumeric(Random r) {
+ return alphaNumeric[r.nextInt(alphaNumeric.length)];
+ }
+
+ public static String generatePresharedKey(int numChars) {
+ Random r = new SecureRandom();
+ StringBuilder psk = new StringBuilder();
+ for (int i = 0; i < numChars; i++) {
+ psk.append(generateAlphaNumeric(r));
+ }
+ return psk.toString();
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/Predicate.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/Predicate.java b/utils/src/main/java/com/cloud/utils/Predicate.java
new file mode 100644
index 0000000..6079d16
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/Predicate.java
@@ -0,0 +1,24 @@
+//
+// 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 com.cloud.utils;
+
+public interface Predicate {
+ boolean checkCondition();
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ProcessUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ProcessUtil.java b/utils/src/main/java/com/cloud/utils/ProcessUtil.java
new file mode 100644
index 0000000..53137c4
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ProcessUtil.java
@@ -0,0 +1,112 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.OutputInterpreter;
+import com.cloud.utils.script.Script;
+
+public class ProcessUtil {
+ private static final Logger s_logger = Logger.getLogger(ProcessUtil.class.getName());
+
+ // paths cannot be hardcoded
+ public static void pidCheck(String pidDir, String run) throws ConfigurationException {
+
+ String dir = pidDir == null ? "/var/run" : pidDir;
+
+ try {
+ final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
+ if (propsFile == null) {
+ s_logger.debug("environment.properties could not be opened");
+ } else {
+ final Properties props = PropertiesUtil.loadFromFile(propsFile);
+ dir = props.getProperty("paths.pid");
+ if (dir == null) {
+ dir = pidDir == null ? "/var/run" : pidDir;
+ }
+ }
+ } catch (IOException e) {
+ s_logger.debug("environment.properties could not be opened");
+ }
+
+ final File pidFile = new File(dir + File.separator + run);
+ try {
+ if (!pidFile.createNewFile()) {
+ if (!pidFile.exists()) {
+ throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath() + ". Are you sure you're running as root?");
+ }
+
+ final String pidLine = FileUtils.readFileToString(pidFile).trim();
+ if (pidLine.isEmpty()) {
+ throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
+ }
+ try {
+ final long pid = Long.parseLong(pidLine);
+ final Script script = new Script("bash", 120000, s_logger);
+ script.add("-c", "ps -p " + pid);
+ final String result = script.execute();
+ if (result == null) {
+ throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
+ }
+ if (!pidFile.delete()) {
+ throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
+ }
+ if (!pidFile.createNewFile()) {
+ throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
+ }
+ } catch (final NumberFormatException e) {
+ throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
+ }
+ }
+ pidFile.deleteOnExit();
+
+ final Script script = new Script("bash", 120000, s_logger);
+ script.add("-c", "echo $PPID");
+ final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
+ script.execute(parser);
+
+ final String pid = parser.getLine();
+
+ FileUtils.writeStringToFile(pidFile, pid + "\n");
+ } catch (final IOException e) {
+ throw new CloudRuntimeException("Unable to create the " + pidFile.getAbsolutePath() + ". Are you running as root?", e);
+ }
+ }
+
+ public static String dumpStack() {
+ StringBuilder sb = new StringBuilder();
+ StackTraceElement[] elems = Thread.currentThread().getStackTrace();
+ if (elems != null && elems.length > 0) {
+ for (StackTraceElement elem : elems) {
+ sb.append("\tat ").append(elem.getMethodName()).append("(").append(elem.getFileName()).append(":").append(elem.getLineNumber()).append(")\n");
+ }
+ }
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/Profiler.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/Profiler.java b/utils/src/main/java/com/cloud/utils/Profiler.java
new file mode 100644
index 0000000..f8e44bd
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/Profiler.java
@@ -0,0 +1,91 @@
+//
+// 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 com.cloud.utils;
+
+public class Profiler {
+
+ private static final long MILLIS_FACTOR = 1000l;
+ private static final double EXPONENT = 2d;
+
+
+ private Long startTickNanoSeconds;
+ private Long stopTickNanoSeconds;
+
+ public long start() {
+ startTickNanoSeconds = System.nanoTime();
+ return startTickNanoSeconds;
+ }
+
+ public long stop() {
+ stopTickNanoSeconds = System.nanoTime();
+ return stopTickNanoSeconds;
+ }
+
+ /**
+ * 1 millisecond = 1e+6 nanoseconds
+ * 1 second = 1000 milliseconds = 1e+9 nanoseconds
+ *
+ * @return the duration in nanoseconds.
+ */
+ public long getDuration() {
+ if (startTickNanoSeconds != null && stopTickNanoSeconds != null) {
+ final long timeInNanoSeconds = stopTickNanoSeconds - startTickNanoSeconds;
+ return timeInNanoSeconds;
+ }
+
+ return -1;
+ }
+
+ /**
+ * 1 millisecond = 1e+6 nanoseconds
+ * 1 second = 1000 millisecond = 1e+9 nanoseconds
+ *
+ * @return the duration in milliseconds.
+ */
+ public long getDurationInMillis() {
+ if (startTickNanoSeconds != null && stopTickNanoSeconds != null) {
+ final long timeInMillis = (stopTickNanoSeconds - startTickNanoSeconds) / (long)Math.pow(MILLIS_FACTOR, EXPONENT);
+ return timeInMillis;
+ }
+
+ return -1;
+ }
+
+ public boolean isStarted() {
+ return startTickNanoSeconds != null;
+ }
+
+ public boolean isStopped() {
+ return stopTickNanoSeconds != null;
+ }
+
+ @Override
+ public String toString() {
+ if (startTickNanoSeconds == null) {
+ return "Not Started";
+ }
+
+ if (stopTickNanoSeconds == null) {
+ return "Started but not stopped";
+ }
+
+ return "Done. Duration: " + getDurationInMillis() + "ms";
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/PropertiesUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/PropertiesUtil.java b/utils/src/main/java/com/cloud/utils/PropertiesUtil.java
new file mode 100644
index 0000000..4cb89f7
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/PropertiesUtil.java
@@ -0,0 +1,196 @@
+//
+// 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 com.cloud.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+
+public class PropertiesUtil {
+ private static final Logger s_logger = Logger.getLogger(PropertiesUtil.class);
+
+ /**
+ * Searches the class path and local paths to find the config file.
+ * @param path path to find. if it starts with / then it's absolute path.
+ * @return File or null if not found at all.
+ */
+
+ public static File findConfigFile(String path) {
+ ClassLoader cl = PropertiesUtil.class.getClassLoader();
+ URL url = cl.getResource(path);
+
+ if (url != null && "file".equals(url.getProtocol())) {
+ return new File(url.getFile());
+ }
+
+ url = ClassLoader.getSystemResource(path);
+ if (url != null && "file".equals(url.getProtocol())) {
+ return new File(url.getFile());
+ }
+
+ File file = new File(path);
+ if (file.exists()) {
+ return file;
+ }
+
+ String newPath = "conf" + (path.startsWith(File.separator) ? "" : "/") + path;
+ url = ClassLoader.getSystemResource(newPath);
+ if (url != null && "file".equals(url.getProtocol())) {
+ return new File(url.getFile());
+ }
+
+ url = cl.getResource(newPath);
+ if (url != null && "file".equals(url.getProtocol())) {
+ return new File(url.getFile());
+ }
+
+ newPath = "conf" + (path.startsWith(File.separator) ? "" : File.separator) + path;
+ file = new File(newPath);
+ if (file.exists()) {
+ return file;
+ }
+
+ newPath = System.getProperty("catalina.home");
+ if (newPath == null) {
+ newPath = System.getenv("CATALINA_HOME");
+ }
+
+ if (newPath == null) {
+ newPath = System.getenv("CATALINA_BASE");
+ }
+
+ if (newPath == null) {
+ return null;
+ }
+
+ file = new File(newPath + File.separator + "conf" + File.separator + path);
+ if (file.exists()) {
+ return file;
+ }
+
+ return null;
+ }
+
+ public static Map<String, Object> toMap(Properties props) {
+ Set<String> names = props.stringPropertyNames();
+ HashMap<String, Object> map = new HashMap<String, Object>(names.size());
+ for (String name : names) {
+ map.put(name, props.getProperty(name));
+ }
+
+ return map;
+ }
+
+ /*
+ * Returns an InputStream for the given resource
+ * This is needed to read the files within a jar in classpath.
+ */
+ public static InputStream openStreamFromURL(String path) {
+ ClassLoader cl = PropertiesUtil.class.getClassLoader();
+ URL url = cl.getResource(path);
+ if (url != null) {
+ try {
+ InputStream stream = url.openStream();
+ return stream;
+ } catch (IOException ioex) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ public static void loadFromJar(Properties properties, String configFile) throws IOException {
+ InputStream stream = PropertiesUtil.openStreamFromURL(configFile);
+ if (stream != null) {
+ properties.load(stream);
+ } else {
+ s_logger.error("Unable to find properties file: " + configFile);
+ }
+ }
+
+ // Returns key=value pairs by parsing a commands.properties/config file
+ // with syntax; key=cmd;value (with this syntax cmd is stripped) and key=value
+ public static Map<String, String> processConfigFile(String[] configFiles) {
+ Map<String, String> configMap = new HashMap<String, String>();
+ Properties preProcessedCommands = new Properties();
+ for (String configFile : configFiles) {
+ File commandsFile = findConfigFile(configFile);
+ if (commandsFile != null) {
+ try {
+ loadFromFile(preProcessedCommands, commandsFile);
+ } catch (IOException ioe) {
+ s_logger.error("IO Exception loading properties file", ioe);
+ }
+ }
+ else {
+ // in case of a file within a jar in classpath, try to open stream using url
+ try {
+ loadFromJar(preProcessedCommands, configFile);
+ } catch (IOException e) {
+ s_logger.error("IO Exception loading properties file from jar", e);
+ }
+ }
+ }
+
+ for (Object key : preProcessedCommands.keySet()) {
+ String preProcessedCommand = preProcessedCommands.getProperty((String)key);
+ int splitIndex = preProcessedCommand.lastIndexOf(";");
+ String value = preProcessedCommand.substring(splitIndex + 1);
+ configMap.put((String)key, value);
+ }
+
+ return configMap;
+ }
+
+ /**
+ * Load a Properties object with contents from a File.
+ * @param properties the properties object to be loaded
+ * @param file the file to load from
+ * @throws IOException
+ */
+ public static void loadFromFile(final Properties properties, final File file)
+ throws IOException {
+ try (final InputStream stream = new FileInputStream(file)) {
+ properties.load(stream);
+ }
+ }
+
+ /**
+ * Load the file and return the contents as a Properties object.
+ * @param file the file to load
+ * @return A Properties object populated
+ * @throws IOException
+ */
+ public static Properties loadFromFile(final File file)
+ throws IOException {
+ final Properties properties = new Properties();
+ loadFromFile(properties, file);
+ return properties;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ReflectUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ReflectUtil.java b/utils/src/main/java/com/cloud/utils/ReflectUtil.java
new file mode 100644
index 0000000..c8ae954
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ReflectUtil.java
@@ -0,0 +1,213 @@
+//
+// 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 com.cloud.utils;
+
+import static java.beans.Introspector.getBeanInfo;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.unmodifiableList;
+
+import java.beans.BeanInfo;
+import java.beans.IntrospectionException;
+import java.beans.PropertyDescriptor;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.reflections.Reflections;
+import org.reflections.util.ConfigurationBuilder;
+import org.reflections.util.ClasspathHelper;
+import org.reflections.scanners.SubTypesScanner;
+import org.reflections.scanners.TypeAnnotationsScanner;
+
+import com.google.common.collect.ImmutableSet;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class ReflectUtil {
+
+ private static final Logger s_logger = Logger.getLogger(ReflectUtil.class);
+ private static final Logger logger = Logger.getLogger(Reflections.class);
+
+ public static Pair<Class<?>, Field> getAnyField(Class<?> clazz, String fieldName) {
+ try {
+ return new Pair<Class<?>, Field>(clazz, clazz.getDeclaredField(fieldName));
+ } catch (SecurityException e) {
+ throw new CloudRuntimeException("How the heck?", e);
+ } catch (NoSuchFieldException e) {
+ // Do I really want this? No I don't but what can I do? It only throws the NoSuchFieldException.
+ Class<?> parent = clazz.getSuperclass();
+ if (parent != null) {
+ return getAnyField(parent, fieldName);
+ }
+ return null;
+ }
+ }
+
+ // Gets all classes with some annotation from a package
+ public static Set<Class<?>> getClassesWithAnnotation(Class<? extends Annotation> annotation, String[] packageNames) {
+ Reflections reflections;
+ Set<Class<?>> classes = new HashSet<Class<?>>();
+ ConfigurationBuilder builder=new ConfigurationBuilder();
+ for (String packageName : packageNames) {
+ builder.addUrls(ClasspathHelper.forPackage(packageName));
+ }
+ builder.setScanners(new SubTypesScanner(),new TypeAnnotationsScanner());
+ reflections = new Reflections(builder);
+ classes.addAll(reflections.getTypesAnnotatedWith(annotation));
+ return classes;
+ }
+
+ // Checks against posted search classes if cmd is async
+ public static boolean isCmdClassAsync(Class<?> cmdClass, Class<?>[] searchClasses) {
+ boolean isAsync = false;
+ Class<?> superClass = cmdClass;
+
+ while (superClass != null && superClass != Object.class) {
+ String superName = superClass.getName();
+ for (Class<?> baseClass : searchClasses) {
+ if (superName.equals(baseClass.getName())) {
+ isAsync = true;
+ break;
+ }
+ }
+ if (isAsync)
+ break;
+ superClass = superClass.getSuperclass();
+ }
+ return isAsync;
+ }
+
+ // Returns all fields until a base class for a cmd class
+ public static List<Field> getAllFieldsForClass(Class<?> cmdClass, Class<?> baseClass) {
+ List<Field> fields = new ArrayList<Field>();
+ Collections.addAll(fields, cmdClass.getDeclaredFields());
+ Class<?> superClass = cmdClass.getSuperclass();
+ while (baseClass.isAssignableFrom(superClass) && baseClass != superClass) {
+ Field[] superClassFields = superClass.getDeclaredFields();
+ if (superClassFields != null)
+ Collections.addAll(fields, superClassFields);
+ superClass = superClass.getSuperclass();
+ }
+ return fields;
+ }
+
+ /**
+ * Returns all unique fields except excludeClasses for a cmd class
+ * @param cmdClass the class in which fields should be collected
+ * @param excludeClasses the classes whose fields must be ignored
+ * @return list of fields
+ */
+ public static Set<Field> getAllFieldsForClass(Class<?> cmdClass, Class<?>[] excludeClasses) {
+ Set<Field> fields = new HashSet<Field>();
+ Collections.addAll(fields, cmdClass.getDeclaredFields());
+ Class<?> superClass = cmdClass.getSuperclass();
+
+ while (superClass != null && superClass != Object.class) {
+ String superName = superClass.getName();
+ boolean isNameEqualToSuperName = false;
+ for (Class<?> baseClass : excludeClasses) {
+ if (superName.equals(baseClass.getName())) {
+ isNameEqualToSuperName = true;
+ }
+ }
+
+ if (!isNameEqualToSuperName) {
+ Field[] superClassFields = superClass.getDeclaredFields();
+ if (superClassFields != null) {
+ Collections.addAll(fields, superClassFields);
+ }
+ }
+ superClass = superClass.getSuperclass();
+ }
+ return fields;
+ }
+
+ public static List<String> flattenProperties(final Object target, final Class<?> clazz) {
+ return flattenPropeties(target, clazz, "class");
+ }
+
+ public static List<String> flattenPropeties(final Object target, final Class<?> clazz, final String... excludedProperties) {
+ return flattenProperties(target, clazz, ImmutableSet.copyOf(excludedProperties));
+ }
+
+ private static List<String> flattenProperties(final Object target, final Class<?> clazz, final ImmutableSet<String> excludedProperties) {
+
+ assert clazz != null;
+
+ if (target == null) {
+ return emptyList();
+ }
+
+ assert clazz.isAssignableFrom(target.getClass());
+
+ try {
+
+ final BeanInfo beanInfo = getBeanInfo(clazz);
+ final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
+
+ final List<String> serializedProperties = new ArrayList<String>();
+ for (final PropertyDescriptor descriptor : descriptors) {
+
+ if (excludedProperties.contains(descriptor.getName())) {
+ continue;
+ }
+
+ serializedProperties.add(descriptor.getName());
+ final Object value = descriptor.getReadMethod().invoke(target);
+ serializedProperties.add(value != null ? value.toString() : "null");
+
+ }
+
+ return unmodifiableList(serializedProperties);
+
+ } catch (IntrospectionException e) {
+ s_logger.warn("Ignored IntrospectionException when serializing class " + target.getClass().getCanonicalName(), e);
+ } catch (IllegalArgumentException e) {
+ s_logger.warn("Ignored IllegalArgumentException when serializing class " + target.getClass().getCanonicalName(), e);
+ } catch (IllegalAccessException e) {
+ s_logger.warn("Ignored IllegalAccessException when serializing class " + target.getClass().getCanonicalName(), e);
+ } catch (InvocationTargetException e) {
+ s_logger.warn("Ignored InvocationTargetException when serializing class " + target.getClass().getCanonicalName(), e);
+ }
+
+ return emptyList();
+
+ }
+
+ public static String getEntityName(Class clz){
+ if(clz == null)
+ return null;
+
+ String entityName = clz.getName();
+ int index = entityName.lastIndexOf(".");
+ if (index != -1) {
+ return entityName.substring(index + 1);
+ }else{
+ return entityName;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/ReflectionUse.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/ReflectionUse.java b/utils/src/main/java/com/cloud/utils/ReflectionUse.java
new file mode 100644
index 0000000..a5a78e2
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/ReflectionUse.java
@@ -0,0 +1,31 @@
+//
+// 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 com.cloud.utils;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Target({METHOD})
+@Retention(RUNTIME)
+public @interface ReflectionUse {
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/S3Utils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/S3Utils.java b/utils/src/main/java/com/cloud/utils/S3Utils.java
new file mode 100644
index 0000000..6efe76b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/S3Utils.java
@@ -0,0 +1,603 @@
+//
+// 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 com.cloud.utils;
+
+import static com.amazonaws.Protocol.HTTP;
+import static com.amazonaws.Protocol.HTTPS;
+import static com.cloud.utils.StringUtils.join;
+import static java.io.File.createTempFile;
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.singletonList;
+import static java.util.Collections.unmodifiableList;
+import static org.apache.commons.lang.ArrayUtils.isEmpty;
+import static org.apache.commons.lang.StringUtils.isBlank;
+import static org.apache.commons.lang.StringUtils.isNotBlank;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.log4j.Logger;
+
+import com.amazonaws.AmazonClientException;
+import com.amazonaws.ClientConfiguration;
+import com.amazonaws.HttpMethod;
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.BasicAWSCredentials;
+import com.amazonaws.services.s3.AmazonS3;
+import com.amazonaws.services.s3.AmazonS3Client;
+import com.amazonaws.services.s3.model.Bucket;
+import com.amazonaws.services.s3.model.CannedAccessControlList;
+import com.amazonaws.services.s3.model.GetObjectRequest;
+import com.amazonaws.services.s3.model.ListObjectsRequest;
+import com.amazonaws.services.s3.model.ObjectListing;
+import com.amazonaws.services.s3.model.ObjectMetadata;
+import com.amazonaws.services.s3.model.PutObjectRequest;
+import com.amazonaws.services.s3.model.S3Object;
+import com.amazonaws.services.s3.model.S3ObjectSummary;
+import com.amazonaws.services.s3.transfer.TransferManager;
+import com.amazonaws.services.s3.transfer.Upload;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class S3Utils {
+
+ private static final Logger LOGGER = Logger.getLogger(S3Utils.class);
+
+ public static final String SEPARATOR = "/";
+
+ private static final int MIN_BUCKET_NAME_LENGTH = 3;
+ private static final int MAX_BUCKET_NAME_LENGTH = 63;
+
+ private S3Utils() {
+ super();
+ }
+
+ public static AmazonS3 acquireClient(final ClientOptions clientOptions) {
+
+ final AWSCredentials credentials = new BasicAWSCredentials(clientOptions.getAccessKey(), clientOptions.getSecretKey());
+
+ final ClientConfiguration configuration = new ClientConfiguration();
+
+ if (clientOptions.isHttps() != null) {
+ configuration.setProtocol(clientOptions.isHttps() == true ? HTTPS : HTTP);
+ }
+
+ if (clientOptions.getConnectionTimeout() != null) {
+ configuration.setConnectionTimeout(clientOptions.getConnectionTimeout());
+ }
+
+ if (clientOptions.getMaxErrorRetry() != null) {
+ configuration.setMaxErrorRetry(clientOptions.getMaxErrorRetry());
+ }
+
+ if (clientOptions.getSocketTimeout() != null) {
+ configuration.setSocketTimeout(clientOptions.getSocketTimeout());
+ }
+
+ if (clientOptions.getUseTCPKeepAlive() != null) {
+ //configuration.setUseTcpKeepAlive(clientOptions.getUseTCPKeepAlive());
+ LOGGER.debug("useTCPKeepAlive not supported by old AWS SDK");
+ }
+
+ if (clientOptions.getConnectionTtl() != null) {
+ //configuration.setConnectionTTL(clientOptions.getConnectionTtl());
+ LOGGER.debug("connectionTtl not supported by old AWS SDK");
+ }
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Creating S3 client with configuration: [protocol: %1$s, connectionTimeOut: " + "%2$s, maxErrorRetry: %3$s, socketTimeout: %4$s, useTCPKeepAlive: %5$s, connectionTtl: %6$s]",
+ configuration.getProtocol(), configuration.getConnectionTimeout(), configuration.getMaxErrorRetry(), configuration.getSocketTimeout(),
+ -1, -1));
+ }
+
+ final AmazonS3Client client = new AmazonS3Client(credentials, configuration);
+
+ if (isNotBlank(clientOptions.getEndPoint())) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Setting the end point for S3 client %1$s to %2$s.", client, clientOptions.getEndPoint()));
+ }
+ client.setEndpoint(clientOptions.getEndPoint());
+ }
+
+ return client;
+
+ }
+
+ public static void putFile(final ClientOptions clientOptions, final File sourceFile, final String bucketName, final String key) {
+
+ assert clientOptions != null;
+ assert sourceFile != null;
+ assert !isBlank(bucketName);
+ assert !isBlank(key);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Sending file %1$s as S3 object %2$s in " + "bucket %3$s", sourceFile.getName(), key, bucketName));
+ }
+
+ acquireClient(clientOptions).putObject(bucketName, key, sourceFile);
+
+ }
+
+ public static void putObject(final ClientOptions clientOptions, final InputStream sourceStream, final String bucketName, final String key) {
+
+ assert clientOptions != null;
+ assert sourceStream != null;
+ assert !isBlank(bucketName);
+ assert !isBlank(key);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Sending stream as S3 object %1$s in " + "bucket %2$s", key, bucketName));
+ }
+
+ acquireClient(clientOptions).putObject(bucketName, key, sourceStream, null);
+
+ }
+
+ public static void putObject(final ClientOptions clientOptions, final PutObjectRequest req) {
+
+ assert clientOptions != null;
+ assert req != null;
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Sending stream as S3 object using PutObjectRequest"));
+ }
+
+ acquireClient(clientOptions).putObject(req);
+
+ }
+
+ // multi-part upload file
+ public static void mputFile(final ClientOptions clientOptions, final File sourceFile, final String bucketName, final String key) throws InterruptedException {
+
+ assert clientOptions != null;
+ assert sourceFile != null;
+ assert !isBlank(bucketName);
+ assert !isBlank(key);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Multipart sending file %1$s as S3 object %2$s in " + "bucket %3$s", sourceFile.getName(), key, bucketName));
+ }
+ TransferManager tm = new TransferManager(S3Utils.acquireClient(clientOptions));
+ Upload upload = tm.upload(bucketName, key, sourceFile);
+ upload.waitForCompletion();
+ }
+
+ // multi-part upload object
+ public static void mputObject(final ClientOptions clientOptions, final InputStream sourceStream, final String bucketName, final String key)
+ throws InterruptedException {
+
+ assert clientOptions != null;
+ assert sourceStream != null;
+ assert !isBlank(bucketName);
+ assert !isBlank(key);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Multipart sending stream as S3 object %1$s in " + "bucket %2$s", key, bucketName));
+ }
+ TransferManager tm = new TransferManager(S3Utils.acquireClient(clientOptions));
+ Upload upload = tm.upload(bucketName, key, sourceStream, null);
+ upload.waitForCompletion();
+ }
+
+ // multi-part upload object
+ public static void mputObject(final ClientOptions clientOptions, final PutObjectRequest req) throws InterruptedException {
+
+ assert clientOptions != null;
+ assert req != null;
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Multipart sending object to S3 using PutObjectRequest");
+ }
+ TransferManager tm = new TransferManager(S3Utils.acquireClient(clientOptions));
+ Upload upload = tm.upload(req);
+ upload.waitForCompletion();
+
+ }
+
+ public static void setObjectAcl(final ClientOptions clientOptions, final String bucketName, final String key, final CannedAccessControlList acl) {
+
+ assert clientOptions != null;
+ assert acl != null;
+
+ acquireClient(clientOptions).setObjectAcl(bucketName, key, acl);
+
+ }
+
+ public static URL generatePresignedUrl(final ClientOptions clientOptions, final String bucketName, final String key, final Date expiration) {
+
+ assert clientOptions != null;
+ assert !isBlank(bucketName);
+ assert !isBlank(key);
+
+ return acquireClient(clientOptions).generatePresignedUrl(bucketName, key, expiration, HttpMethod.GET);
+
+ }
+
+ // Note that whenever S3Object is returned, client code needs to close the internal stream to avoid resource leak.
+ public static S3Object getObject(final ClientOptions clientOptions, final String bucketName, final String key) {
+
+ assert clientOptions != null;
+ assert !isBlank(bucketName);
+ assert !isBlank(key);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Get S3 object %1$s in " + "bucket %2$s", key, bucketName));
+ }
+
+ return acquireClient(clientOptions).getObject(bucketName, key);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public static File getFile(final ClientOptions clientOptions, final String bucketName, final String key, final File targetDirectory,
+ final FileNamingStrategy namingStrategy) {
+
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+ assert isNotBlank(key);
+ assert targetDirectory != null && targetDirectory.isDirectory();
+ assert namingStrategy != null;
+
+ final AmazonS3 connection = acquireClient(clientOptions);
+
+ File tempFile = null;
+ try {
+
+ tempFile = createTempFile(join("-", targetDirectory.getName(), currentTimeMillis(), "part"), "tmp", targetDirectory);
+ tempFile.deleteOnExit();
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Downloading object %1$s from bucket %2$s to temp file %3$s", key, bucketName, tempFile.getName()));
+ }
+
+ try {
+ connection.getObject(new GetObjectRequest(bucketName, key), tempFile);
+ } catch (AmazonClientException ex) {
+ // hack to handle different ETAG format generated from RiakCS for multi-part uploaded object
+ String msg = ex.getMessage();
+ if (!msg.contains("verify integrity")) {
+ throw ex;
+ }
+ }
+
+ final File targetFile = new File(targetDirectory, namingStrategy.determineFileName(key));
+ tempFile.renameTo(targetFile);
+
+ return targetFile;
+
+ } catch (FileNotFoundException e) {
+
+ throw new CloudRuntimeException(format("Failed open file %1$s in order to get object %2$s from bucket %3$s.", targetDirectory.getAbsoluteFile(), bucketName,
+ key), e);
+
+ } catch (IOException e) {
+
+ throw new CloudRuntimeException(format("Unable to allocate temporary file in directory %1$s to download %2$s:%3$s from S3",
+ targetDirectory.getAbsolutePath(), bucketName, key), e);
+
+ } finally {
+
+ if (tempFile != null) {
+ tempFile.delete();
+ }
+
+ }
+
+ }
+
+ public static List<File> getDirectory(final ClientOptions clientOptions, final String bucketName, final String sourcePath, final File targetDirectory,
+ final FileNamingStrategy namingStrategy) {
+
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+ assert isNotBlank(sourcePath);
+ assert targetDirectory != null;
+
+ final AmazonS3 connection = acquireClient(clientOptions);
+
+ // List the objects in the source directory on S3
+ final List<S3ObjectSummary> objectSummaries = listDirectory(bucketName, sourcePath, connection);
+ final List<File> files = new ArrayList<File>();
+
+ for (final S3ObjectSummary objectSummary : objectSummaries) {
+
+ files.add(getFile(clientOptions, bucketName, objectSummary.getKey(), targetDirectory, namingStrategy));
+
+ }
+
+ return unmodifiableList(files);
+
+ }
+
+ public static List<S3ObjectSummary> getDirectory(final ClientOptions clientOptions, final String bucketName, final String sourcePath) {
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+ assert isNotBlank(sourcePath);
+
+ final AmazonS3 connection = acquireClient(clientOptions);
+
+ // List the objects in the source directory on S3
+ return listDirectory(bucketName, sourcePath, connection);
+ }
+
+ private static List<S3ObjectSummary> listDirectory(final String bucketName, final String directory, final AmazonS3 client) {
+
+ List<S3ObjectSummary> objects = new ArrayList<S3ObjectSummary>();
+ ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName).withPrefix(directory + SEPARATOR);
+
+ ObjectListing ol = client.listObjects(listObjectsRequest);
+ if(ol.isTruncated()) {
+ do {
+ objects.addAll(ol.getObjectSummaries());
+ listObjectsRequest.setMarker(ol.getNextMarker());
+ ol = client.listObjects(listObjectsRequest);
+ } while (ol.isTruncated());
+ }
+ else {
+ objects.addAll(ol.getObjectSummaries());
+ }
+
+ if (objects.isEmpty()) {
+ return emptyList();
+ }
+
+ return unmodifiableList(objects);
+ }
+
+ public static void putDirectory(final ClientOptions clientOptions, final String bucketName, final File directory, final FilenameFilter fileNameFilter,
+ final ObjectNamingStrategy namingStrategy) {
+
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+ assert directory != null && directory.isDirectory();
+ assert fileNameFilter != null;
+ assert namingStrategy != null;
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Putting directory %1$s in S3 bucket %2$s.", directory.getAbsolutePath(), bucketName));
+ }
+
+ // Determine the list of files to be sent using the passed filter ...
+ final File[] files = directory.listFiles(fileNameFilter);
+
+ if (LOGGER.isTraceEnabled()) {
+ LOGGER.trace(format("Putting files (%1$s) in S3 bucket %2$s.", ArrayUtils.toString(files, "no files found"), bucketName));
+ }
+
+ // Skip spinning up an S3 connection when no files will be sent ...
+ if (isEmpty(files)) {
+ return;
+ }
+
+ final AmazonS3 client = acquireClient(clientOptions);
+
+ // Send the files to S3 using the passed ObjectNaming strategy to
+ // determine the key ...
+ for (final File file : files) {
+ final String key = namingStrategy.determineKey(file);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(format("Putting file %1$s into bucket %2$s with key %3$s.", file.getAbsolutePath(), bucketName, key));
+ }
+ client.putObject(bucketName, key, file);
+ }
+
+ }
+
+ public static void deleteObject(final ClientOptions clientOptions, final String bucketName, final String key) {
+
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+ assert isNotBlank(key);
+
+ final AmazonS3 client = acquireClient(clientOptions);
+
+ client.deleteObject(bucketName, key);
+
+ }
+
+ public static void deleteDirectory(final ClientOptions clientOptions, final String bucketName, final String directoryName) {
+
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+ assert isNotBlank(directoryName);
+
+ final AmazonS3 client = acquireClient(clientOptions);
+
+ final List<S3ObjectSummary> objects = listDirectory(bucketName, directoryName, client);
+
+ for (final S3ObjectSummary object : objects) {
+
+ client.deleteObject(bucketName, object.getKey());
+
+ }
+
+ client.deleteObject(bucketName, directoryName);
+
+ }
+
+ public static boolean canConnect(final ClientOptions clientOptions) {
+
+ try {
+
+ acquireClient(clientOptions);
+ return true;
+
+ } catch (AmazonClientException e) {
+
+ LOGGER.warn("Ignored Exception while checking connection options", e);
+ return false;
+
+ }
+
+ }
+
+ public static boolean doesBucketExist(final ClientOptions clientOptions, final String bucketName) {
+
+ assert clientOptions != null;
+ assert !isBlank(bucketName);
+
+ try {
+
+ final List<Bucket> buckets = acquireClient(clientOptions).listBuckets();
+
+ for (Bucket bucket : buckets) {
+ if (bucket.getName().equals(bucketName)) {
+ return true;
+ }
+ }
+
+ return false;
+
+ } catch (AmazonClientException e) {
+
+ LOGGER.warn("Ignored Exception while checking bucket existence", e);
+ return false;
+
+ }
+
+ }
+
+ public static boolean canReadWriteBucket(final ClientOptions clientOptions, final String bucketName) {
+
+ assert clientOptions != null;
+ assert isNotBlank(bucketName);
+
+ try {
+
+ final AmazonS3 client = acquireClient(clientOptions);
+
+ final String fileContent = "testing put and delete";
+ final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes());
+ final String key = UUID.randomUUID().toString() + ".txt";
+
+ final ObjectMetadata metadata = new ObjectMetadata();
+ metadata.setContentLength(fileContent.length());
+
+ client.putObject(bucketName, key, inputStream, metadata);
+ client.deleteObject(bucketName, key);
+
+ return true;
+
+ } catch (AmazonClientException e) {
+
+ return false;
+
+ }
+
+ }
+
+ public static List<String> checkClientOptions(ClientOptions clientOptions) {
+
+ assert clientOptions != null;
+
+ List<String> errorMessages = new ArrayList<String>();
+
+ errorMessages.addAll(checkRequiredField("access key", clientOptions.getAccessKey()));
+ errorMessages.addAll(checkRequiredField("secret key", clientOptions.getSecretKey()));
+
+ errorMessages.addAll(checkOptionalField("connection timeout", clientOptions.getConnectionTimeout()));
+ errorMessages.addAll(checkOptionalField("socket timeout", clientOptions.getSocketTimeout()));
+ errorMessages.addAll(checkOptionalField("max error retries", clientOptions.getMaxErrorRetry()));
+ errorMessages.addAll(checkOptionalField("connection ttl", clientOptions.getConnectionTtl()));
+
+ return unmodifiableList(errorMessages);
+
+ }
+
+ public static List<String> checkBucketName(final String bucketLabel, final String bucket) {
+
+ assert isNotBlank(bucketLabel);
+ assert isNotBlank(bucket);
+
+ final List<String> errorMessages = new ArrayList<String>();
+
+ if (bucket.length() < MIN_BUCKET_NAME_LENGTH) {
+ errorMessages.add(format("The length of %1$s " + "for the %2$s must have a length of at least %3$s " + "characters", bucket, bucketLabel,
+ MIN_BUCKET_NAME_LENGTH));
+ }
+
+ if (bucket.length() > MAX_BUCKET_NAME_LENGTH) {
+ errorMessages.add(format("The length of %1$s " + "for the %2$s must not have a length of at greater" + " than %3$s characters", bucket, bucketLabel,
+ MAX_BUCKET_NAME_LENGTH));
+ }
+
+ return unmodifiableList(errorMessages);
+
+ }
+
+ private static List<String> checkOptionalField(final String fieldName, final Integer fieldValue) {
+ if (fieldValue != null && fieldValue < 0) {
+ return singletonList(format("The value of %1$s must " + "be greater than zero.", fieldName));
+ }
+ return emptyList();
+ }
+
+ private static List<String> checkRequiredField(String fieldName, String fieldValue) {
+ if (isBlank(fieldValue)) {
+ return singletonList(format("A %1$s must be specified.", fieldName));
+ }
+ return emptyList();
+ }
+
+ public interface ClientOptions {
+
+ String getAccessKey();
+
+ String getSecretKey();
+
+ String getEndPoint();
+
+ Boolean isHttps();
+
+ Integer getConnectionTimeout();
+
+ Integer getMaxErrorRetry();
+
+ Integer getSocketTimeout();
+
+ Boolean getUseTCPKeepAlive();
+
+ Integer getConnectionTtl();
+ }
+
+ public interface ObjectNamingStrategy {
+
+ String determineKey(File file);
+
+ }
+
+ public interface FileNamingStrategy {
+
+ String determineFileName(String key);
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/SerialVersionUID.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/SerialVersionUID.java b/utils/src/main/java/com/cloud/utils/SerialVersionUID.java
new file mode 100644
index 0000000..e4ea217
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/SerialVersionUID.java
@@ -0,0 +1,69 @@
+//
+// 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 com.cloud.utils;
+
+/**
+ * purposes. This is purely on an honor system though. You should always
+ **/
+public interface SerialVersionUID {
+ public static final long Base = 0x564D4F70 << 32; // 100 brownie points if you guess what this is and tell me.
+
+ public static final long UUID = Base | 0x1;
+ public static final long CloudRuntimeException = Base | 0x2;
+ public static final long CloudStartupServlet = Base | 0x3;
+ public static final long CloudServiceImpl = Base | 0x4;
+ public static final long AccountLimitException = Base | 0x5;
+ public static final long InsufficientVirtualNetworkCapacityException = Base | 0x7;
+ public static final long NetworkUnavailableException = Base | 0x8;
+ public static final long Ip = Base | 0x9;
+ public static final long UnsupportedVersionException = Base | 0xb;
+ public static final long DataCenterIpAddressPK = Base | 0xc;
+ public static final long UnableToExecuteException = Base | 0xd;
+ public static final long ExecutionException = Base | 0xe;
+ public static final long VnetKey = Base | 0xf;
+ public static final long InsufficientServerCapacityException = Base | 0x10;
+ public static final long InsufficientAddressCapacityException = Base | 0x11;
+ public static final long ManagementServerException = Base | 0x12;
+ public static final long HAStateException = Base | 0x13;
+ public static final long InsufficientStorageCapacityException = Base | 0x14;
+ public static final long InsufficientCapacityException = Base | 0x15;
+ public static final long ConcurrentOperationException = Base | 0x16;
+ public static final long AgentUnavailableException = Base | 0x17;
+ public static final long OperationTimedoutException = Base | 0x18;
+ public static final long StorageUnavailableException = Base | 0x19;
+ public static final long InfficientVirtualNetworkCapacityException = Base | 0x1a;
+ public static final long DiscoveryException = Base | 0x1b;
+ public static final long ConflictingNetworkSettingException = Base | 0x1c;
+ public static final long CloudAuthenticationException = Base | 0x1d;
+ public static final long AsyncCommandQueued = Base | 0x1e;
+ public static final long ResourceUnavailableException = Base | 0x1f;
+ public static final long ConnectionException = Base | 0x20;
+ public static final long PermissionDeniedException = Base | 0x21;
+ public static final long sshException = Base | 0x22;
+ public static final long HttpCallException = Base | 0x23;
+ public static final long VirtualMachineMigrationException = Base | 0x24;
+ public static final long DiscoveredWithErrorException = Base | 0x25;
+ public static final long NoTransitionException = Base | 0x26;
+ public static final long CloudExecutionException = Base | 0x27;
+ public static final long CallFailedException = Base | 0x28;
+ public static final long UnableDeleteHostException = Base | 0x29;
+ public static final long AffinityConflictException = Base | 0x2a;
+ public static final long JobCancellationException = Base | 0x2b;
+}
[24/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/ExceptionUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/ExceptionUtil.java b/utils/src/com/cloud/utils/exception/ExceptionUtil.java
deleted file mode 100644
index 351d2ab..0000000
--- a/utils/src/com/cloud/utils/exception/ExceptionUtil.java
+++ /dev/null
@@ -1,54 +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 com.cloud.utils.exception;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-public class ExceptionUtil {
- public static String toString(Throwable th) {
- return toString(th, true);
- }
-
- public static String toString(Throwable th, boolean printStack) {
- final StringWriter writer = new StringWriter();
- writer.append("Exception: " + th.getClass().getName() + "\n");
- writer.append("Message: ");
- writer.append(th.getMessage()).append("\n");
-
- if (printStack) {
- writer.append("Stack: ");
- th.printStackTrace(new PrintWriter(writer));
- }
- return writer.toString();
- }
-
- @SuppressWarnings("unchecked")
- public static <T extends Throwable> void rethrow(Throwable t, Class<T> clz) throws T {
- if (clz.isAssignableFrom(t.getClass()))
- throw (T)t;
- }
-
- public static <T extends Throwable> void rethrowRuntime(Throwable t) {
- rethrow(t, RuntimeException.class);
- rethrow(t, Error.class);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/ExecutionException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/ExecutionException.java b/utils/src/com/cloud/utils/exception/ExecutionException.java
deleted file mode 100644
index 7b3bc61..0000000
--- a/utils/src/com/cloud/utils/exception/ExecutionException.java
+++ /dev/null
@@ -1,49 +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 com.cloud.utils.exception;
-
-import com.cloud.utils.SerialVersionUID;
-
-/**
- * a public method.
- *
- */
-public class ExecutionException extends Exception {
- private static final long serialVersionUID = SerialVersionUID.ExecutionException;
-
- protected int csErrorCode;
-
- public ExecutionException(String msg, Throwable cause) {
- super(msg, cause);
- setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
- }
-
- public ExecutionException(String msg) {
- super(msg);
- }
-
- public void setCSErrorCode(int cserrcode) {
- this.csErrorCode = cserrcode;
- }
-
- public int getCSErrorCode() {
- return this.csErrorCode;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java b/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java
deleted file mode 100644
index 55c273b..0000000
--- a/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java
+++ /dev/null
@@ -1,35 +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 com.cloud.utils.exception;
-
-import com.cloud.utils.SerialVersionUID;
-
-public class HypervisorVersionChangedException extends CloudRuntimeException {
-
- private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException;
-
- public HypervisorVersionChangedException(String message) {
- super(message);
- }
-
- protected HypervisorVersionChangedException() {
- super();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/ChangeEvent.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/ChangeEvent.java b/utils/src/com/cloud/utils/fsm/ChangeEvent.java
deleted file mode 100644
index 15f4f6e..0000000
--- a/utils/src/com/cloud/utils/fsm/ChangeEvent.java
+++ /dev/null
@@ -1,24 +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 com.cloud.utils.fsm;
-
-public class ChangeEvent {
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/FiniteState.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/FiniteState.java b/utils/src/com/cloud/utils/fsm/FiniteState.java
deleted file mode 100644
index e6f2cd0..0000000
--- a/utils/src/com/cloud/utils/fsm/FiniteState.java
+++ /dev/null
@@ -1,58 +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 com.cloud.utils.fsm;
-
-import java.util.List;
-import java.util.Set;
-
-/**
- *
- * @param <S> State
- * @param <E> Event
- */
-public interface FiniteState<S, E> {
- /**
- * @return the state machine being used.
- */
- StateMachine<S, E> getStateMachine();
-
- /**
- * get next state based on the event.
- * @param event
- * @return next State
- */
- S getNextState(E event);
-
- /**
- * Get the states that could have traveled to the current state
- * via this event.
- * @param event
- * @return array of states
- */
- List<S> getFromStates(E event);
-
- /**
- * Get the possible events that can happen from the current state.
- * @return array of events.
- */
- Set<E> getPossibleEvents();
-
- String getDescription();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/FiniteState2.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/FiniteState2.java b/utils/src/com/cloud/utils/fsm/FiniteState2.java
deleted file mode 100644
index 14b9a5e..0000000
--- a/utils/src/com/cloud/utils/fsm/FiniteState2.java
+++ /dev/null
@@ -1,34 +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 com.cloud.utils.fsm;
-
-import java.util.Set;
-
-public interface FiniteState2<T, E> {
-
- StateMachine2<T, ? extends ChangeEvent, ? extends StateObject<?>> getStateMachine();
-
- T getNextState(ChangeEvent e) throws NoTransitionException;
-
- T getFromStates(ChangeEvent e);
-
- Set<ChangeEvent> getPossibleEvents();
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/FiniteStateObject.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/FiniteStateObject.java b/utils/src/com/cloud/utils/fsm/FiniteStateObject.java
deleted file mode 100644
index a57e3b4..0000000
--- a/utils/src/com/cloud/utils/fsm/FiniteStateObject.java
+++ /dev/null
@@ -1,25 +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 com.cloud.utils.fsm;
-
-public interface FiniteStateObject<S, E> {
-
- void setState(S state);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/NoTransitionException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/NoTransitionException.java b/utils/src/com/cloud/utils/fsm/NoTransitionException.java
deleted file mode 100644
index 241e456..0000000
--- a/utils/src/com/cloud/utils/fsm/NoTransitionException.java
+++ /dev/null
@@ -1,36 +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 com.cloud.utils.fsm;
-
-import com.cloud.utils.SerialVersionUID;
-
-/**
- * Thrown by the state machine when there is no transition from one state
- * to another.
- *
- */
-public class NoTransitionException extends Exception {
-
- private static final long serialVersionUID = SerialVersionUID.NoTransitionException;
-
- public NoTransitionException(String msg) {
- super(msg);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/State.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/State.java b/utils/src/com/cloud/utils/fsm/State.java
deleted file mode 100644
index 0af0e61..0000000
--- a/utils/src/com/cloud/utils/fsm/State.java
+++ /dev/null
@@ -1,27 +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 com.cloud.utils.fsm;
-
-/**
- * State represents one state for that object
- */
-public interface State<T> {
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/StateDao.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/StateDao.java b/utils/src/com/cloud/utils/fsm/StateDao.java
deleted file mode 100644
index 43ce25c..0000000
--- a/utils/src/com/cloud/utils/fsm/StateDao.java
+++ /dev/null
@@ -1,25 +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 com.cloud.utils.fsm;
-
-public interface StateDao<S, E, V> {
- boolean updateState(S currentState, E event, S nextState, V vo, Object data);
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/StateListener.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/StateListener.java b/utils/src/com/cloud/utils/fsm/StateListener.java
deleted file mode 100644
index 96e8be9..0000000
--- a/utils/src/com/cloud/utils/fsm/StateListener.java
+++ /dev/null
@@ -1,43 +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 com.cloud.utils.fsm;
-
-public interface StateListener<S, E, V> {
- /**
- * Event is triggered before state machine transition finished.
- * If you want to get the state of vm before state machine changed, you need to listen on this event
- * @param oldState VM's old state
- * @param event that triggered this VM state change
- * @param newState VM's new state
- * @param vo the VM instance
- * @param opaque host id
- * @return
- */
- public boolean preStateTransitionEvent(S oldState, E event, S newState, V vo, boolean status, Object opaque);
-
- /**
- * Event is triggered after state machine transition finished
- * @param transition The Transition fo the Event
- * @param vo the VM instance
- * @param status the state transition is allowed or not
- * @return
- */
- public boolean postStateTransitionEvent(StateMachine2.Transition<S, E> transition, V vo, boolean status, Object opaque);
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/StateMachine.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/StateMachine.java b/utils/src/com/cloud/utils/fsm/StateMachine.java
deleted file mode 100644
index d6d5b4d..0000000
--- a/utils/src/com/cloud/utils/fsm/StateMachine.java
+++ /dev/null
@@ -1,147 +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 com.cloud.utils.fsm;
-
-import java.util.ArrayList;
-import java.util.Formatter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Specifically, it implements the Moore machine.
- * so someone else can add/modify states easily without regression.
- * business logic anyways.
- *
- * @param <S> state
- * @param <E> event
- */
-public class StateMachine<S, E> {
- private final HashMap<S, StateEntry> _states = new HashMap<S, StateEntry>();
- private final StateEntry _initialStateEntry;
-
- public StateMachine() {
- _initialStateEntry = new StateEntry(null);
- }
-
- public void addTransition(S currentState, E event, S toState) {
- StateEntry entry = null;
- if (currentState == null) {
- entry = _initialStateEntry;
- } else {
- entry = _states.get(currentState);
- if (entry == null) {
- entry = new StateEntry(currentState);
- _states.put(currentState, entry);
- }
- }
-
- entry.addTransition(event, toState);
-
- entry = _states.get(toState);
- if (entry == null) {
- entry = new StateEntry(toState);
- _states.put(toState, entry);
- }
- entry.addFromTransition(event, currentState);
- }
-
- public Set<E> getPossibleEvents(S s) {
- StateEntry entry = _states.get(s);
- return entry.nextStates.keySet();
- }
-
- public S getNextState(S s, E e) {
- StateEntry entry = null;
- if (s == null) {
- entry = _initialStateEntry;
- } else {
- entry = _states.get(s);
- assert entry != null : "Cannot retrieve transitions for state " + s.toString();
- }
-
- return entry.nextStates.get(e);
- }
-
- public List<S> getFromStates(S s, E e) {
- StateEntry entry = _states.get(s);
- if (entry == null) {
- return new ArrayList<S>();
- }
-
- return entry.prevStates.get(e);
- }
-
- @Override
- public String toString() {
- StringBuilder str = new StringBuilder(1024);
- _initialStateEntry.buildString(str);
- for (StateEntry entry : _states.values()) {
- entry.buildString(str);
- }
- return str.toString();
- }
-
- private class StateEntry {
- public S state;
- public HashMap<E, S> nextStates;
- public HashMap<E, List<S>> prevStates;
-
- public StateEntry(S state) {
- this.state = state;
- nextStates = new HashMap<E, S>();
- prevStates = new HashMap<E, List<S>>();
- }
-
- public void addTransition(E e, S s) {
- assert !nextStates.containsKey(e) : "State " + getStateStr() + " already contains a transition to state " + nextStates.get(e).toString() + " via event " +
- e.toString() + ". Please revisit the rule you're adding to state " + s.toString();
- nextStates.put(e, s);
- }
-
- public void addFromTransition(E e, S s) {
- List<S> l = prevStates.get(e);
- if (l == null) {
- l = new ArrayList<S>();
- prevStates.put(e, l);
- }
-
- assert !l.contains(s) : "Already contains the from transition " + e.toString() + " from state " + s.toString() + " to " + getStateStr();
- l.add(s);
- }
-
- protected String getStateStr() {
- return state == null ? "Initial" : state.toString();
- }
-
- public void buildString(StringBuilder str) {
- str.append("State: ").append(getStateStr()).append("\n");
- for (Map.Entry<E, S> nextState : nextStates.entrySet()) {
- str.append(" --> Event: ");
- Formatter format = new Formatter();
- str.append(format.format("%-30s", nextState.getKey().toString()));
- str.append("----> State: ");
- str.append(nextState.getValue().toString());
- str.append("\n");
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/StateMachine2.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/StateMachine2.java b/utils/src/com/cloud/utils/fsm/StateMachine2.java
deleted file mode 100644
index 431d961..0000000
--- a/utils/src/com/cloud/utils/fsm/StateMachine2.java
+++ /dev/null
@@ -1,261 +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 com.cloud.utils.fsm;
-
-import java.util.ArrayList;
-import java.util.Formatter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Specifically, it implements the Moore machine.
- * so someone else can add/modify states easily without regression.
- * business logic anyways.
- *
- * @param <S> state
- * @param <E> event
- */
-public class StateMachine2<S, E, V extends StateObject<S>> {
- private final HashMap<S, StateEntry> _states = new HashMap<S, StateEntry>();
- private final StateEntry _initialStateEntry;
-
- private List<StateListener<S, E, V>> _listeners = new ArrayList<StateListener<S, E, V>>();
-
- public StateMachine2() {
- _initialStateEntry = new StateEntry(null);
-
- }
-
- public void addTransition(S currentState, E event, S toState) {
- addTransition(new Transition<S, E>(currentState, event, toState, null));
- }
-
-
- public void addTransition(Transition<S, E> transition) {
- S currentState = transition.getCurrentState();
- E event = transition.getEvent();
- S toState = transition.getToState();
- StateEntry entry = null;
- if (currentState == null) {
- entry = _initialStateEntry;
- } else {
- entry = _states.get(currentState);
- if (entry == null) {
- entry = new StateEntry(currentState);
- _states.put(currentState, entry);
- }
- }
-
- entry.addTransition(event, toState, transition);
-
- entry = _states.get(toState);
- if (entry == null) {
- entry = new StateEntry(toState);
- _states.put(toState, entry);
- }
- entry.addFromTransition(event, currentState);
- }
-
- public Set<E> getPossibleEvents(S s) {
- StateEntry entry = _states.get(s);
- return entry.nextStates.keySet();
- }
-
- public S getNextState(S s, E e) throws NoTransitionException {
- return getTransition(s, e).getToState();
- }
-
- public Transition<S, E> getTransition(S s, E e) throws NoTransitionException {
- StateEntry entry = null;
- if (s == null) {
- entry = _initialStateEntry;
- } else {
- entry = _states.get(s);
- assert entry != null : "Cannot retrieve transitions for state " + s;
- }
-
- Transition<S, E> transition = entry.nextStates.get(e);
- if (transition == null) {
- throw new NoTransitionException("Unable to transition to a new state from " + s + " via " + e);
- }
- return transition;
- }
-
- public List<S> getFromStates(S s, E e) {
- StateEntry entry = _states.get(s);
- if (entry == null) {
- return new ArrayList<S>();
- }
-
- return entry.prevStates.get(e);
- }
-
- public boolean transitTo(V vo, E e, Object opaque, StateDao<S, E, V> dao) throws NoTransitionException {
- S currentState = vo.getState();
- S nextState = getNextState(currentState, e);
- Transition<S, E> transition = getTransition(currentState, e);
-
- boolean transitionStatus = true;
- if (nextState == null) {
- transitionStatus = false;
- }
-
- for (StateListener<S, E, V> listener : _listeners) {
- listener.preStateTransitionEvent(currentState, e, nextState, vo, transitionStatus, opaque);
- }
-
- transitionStatus = dao.updateState(currentState, e, nextState, vo, opaque);
- if (!transitionStatus) {
- return false;
- }
-
- for (StateListener<S, E, V> listener : _listeners) {
- listener.postStateTransitionEvent(transition, vo, transitionStatus, opaque);
- }
-
- return true;
- }
-
- public boolean registerListener(StateListener<S, E, V> listener) {
- synchronized (_listeners) {
- return _listeners.add(listener);
- }
- }
-
- @Override
- public String toString() {
- StringBuilder str = new StringBuilder(1024);
- _initialStateEntry.buildString(str);
- for (StateEntry entry : _states.values()) {
- entry.buildString(str);
- }
- return str.toString();
- }
-
- public static class Transition<S, E> {
-
- private S currentState;
-
- private E event;
-
- private S toState;
-
- private List<Impact> impacts;
-
- public static enum Impact {
- USAGE
- }
-
- public Transition(S currentState, E event, S toState, List<Impact> impacts) {
- this.currentState = currentState;
- this.event = event;
- this.toState = toState;
- this.impacts = impacts;
- }
-
- public S getCurrentState() {
- return currentState;
- }
-
- public E getEvent() {
- return event;
- }
-
- public S getToState() {
- return toState;
- }
-
- public boolean isImpacted(Impact impact) {
- if (impacts == null || impacts.isEmpty()) {
- return false;
- }
- return impacts.contains(impact);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Transition that = (Transition) o;
-
- if (currentState != null ? !currentState.equals(that.currentState) : that.currentState != null) return false;
- if (event != null ? !event.equals(that.event) : that.event != null) return false;
- if (toState != null ? !toState.equals(that.toState) : that.toState != null) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = currentState != null ? currentState.hashCode() : 0;
- result = 31 * result + (event != null ? event.hashCode() : 0);
- result = 31 * result + (toState != null ? toState.hashCode() : 0);
- return result;
- }
- }
-
- private class StateEntry {
- public S state;
- public HashMap<E, Transition<S, E>> nextStates;
- public HashMap<E, List<S>> prevStates;
-
- public StateEntry(S state) {
- this.state = state;
- prevStates = new HashMap<E, List<S>>();
- nextStates = new HashMap<E, Transition<S, E>>();
- }
-
- public void addTransition(E e, S s, Transition<S, E> transition) {
- assert !nextStates.containsKey(e) : "State " + getStateStr() + " already contains a transition to state " + nextStates.get(e).toString() + " via event " +
- e.toString() + ". Please revisit the rule you're adding to state " + s.toString();
- nextStates.put(e, transition);
- }
-
- public void addFromTransition(E e, S s) {
- List<S> l = prevStates.get(e);
- if (l == null) {
- l = new ArrayList<S>();
- prevStates.put(e, l);
- }
-
- assert !l.contains(s) : "Already contains the from transition " + e.toString() + " from state " + s.toString() + " to " + getStateStr();
- l.add(s);
- }
-
- protected String getStateStr() {
- return state == null ? "Initial" : state.toString();
- }
-
- public void buildString(StringBuilder str) {
- str.append("State: ").append(getStateStr()).append("\n");
- for (Map.Entry<E, Transition<S, E>> nextState : nextStates.entrySet()) {
- str.append(" --> Event: ");
- Formatter format = new Formatter();
- str.append(format.format("%-30s", nextState.getKey().toString()));
- str.append("----> State: ");
- str.append(nextState.getValue().toString());
- str.append("\n");
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/fsm/StateObject.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/StateObject.java b/utils/src/com/cloud/utils/fsm/StateObject.java
deleted file mode 100644
index 85dd441..0000000
--- a/utils/src/com/cloud/utils/fsm/StateObject.java
+++ /dev/null
@@ -1,27 +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 com.cloud.utils.fsm;
-
-public interface StateObject<S> {
- /**
- * @return finite state.
- */
- S getState();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java b/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
deleted file mode 100644
index b102dc4..0000000
--- a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
+++ /dev/null
@@ -1,84 +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 com.cloud.utils.log;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-import org.apache.log4j.spi.ThrowableRenderer;
-
-/**
- * This renderer removes all the Cglib generated methods from the call
- *
- * Unfortunately, I had to copy out the EnhancedThrowableRenderer from
- * the apach libraries because EnhancedThrowableRenderer is a final class.
- * simply override doRender. Not sure what the developers are thinking there
- * making it final.
- *
- * <throwableRenderer class="com.cloud.utils.log.CglibThrowableRenderer"/>
- * into log4j.xml.
- *
- */
-public class CglibThrowableRenderer implements ThrowableRenderer {
- /**
- * Construct new instance.
- */
- public CglibThrowableRenderer() {
- super();
- }
-
- @Override
- public String[] doRender(final Throwable th) {
- try {
- ArrayList<String> lines = new ArrayList<String>();
- Throwable throwable = th;
- lines.add(throwable.toString());
- int start = 0;
- do {
- StackTraceElement[] elements = throwable.getStackTrace();
- for (int i = 0; i < elements.length - start; i++) {
- StackTraceElement element = elements[i];
- String filename = element.getFileName();
- String method = element.getMethodName();
- if ((filename != null && filename.equals("<generated>")) || (method != null && method.equals("invokeSuper"))) {
- continue;
- }
- lines.add("\tat " + element.toString());
- }
- if (start != 0) {
- lines.add("\t... " + start + " more");
- }
- throwable = throwable.getCause();
- if (throwable != null) {
- lines.add("Caused by: " + throwable.toString());
- start = elements.length - 1;
- }
- } while (throwable != null);
- return lines.toArray(new String[lines.size()]);
- } catch (Exception ex) {
- PrintWriter pw = new PrintWriter(System.err);
- ex.printStackTrace(pw);
- pw = new PrintWriter(System.out);
- ex.printStackTrace(pw);
- ex.printStackTrace();
- return null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/mgmt/JmxUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/mgmt/JmxUtil.java b/utils/src/com/cloud/utils/mgmt/JmxUtil.java
deleted file mode 100644
index 49076f7..0000000
--- a/utils/src/com/cloud/utils/mgmt/JmxUtil.java
+++ /dev/null
@@ -1,90 +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 com.cloud.utils.mgmt;
-
-import java.lang.management.ManagementFactory;
-import java.util.ArrayList;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-
-public class JmxUtil {
- public static ObjectName registerMBean(ManagementBean mbean) throws MalformedObjectNameException, InstanceAlreadyExistsException, MBeanRegistrationException,
- NotCompliantMBeanException {
-
- return registerMBean(mbean.getName(), null, mbean);
- }
-
- public static ObjectName registerMBean(String objTypeName, String objInstanceName, Object mbean) throws MalformedObjectNameException, InstanceAlreadyExistsException,
- MBeanRegistrationException, NotCompliantMBeanException {
-
- String name = "com.cloud:type=" + objTypeName;
- if (objInstanceName != null && !objInstanceName.isEmpty())
- name += ", name=" + objInstanceName;
- ObjectName objectName = new ObjectName(name);
-
- ArrayList<MBeanServer> server = MBeanServerFactory.findMBeanServer(null);
- if (server.size() > 0) {
- MBeanServer mBeanServer = server.get(0);
- if (!mBeanServer.isRegistered(objectName))
- mBeanServer.registerMBean(mbean, objectName);
- return objectName;
- } else {
- MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
- if (!mBeanServer.isRegistered(objectName))
- mBeanServer.registerMBean(mbean, objectName);
- return objectName;
- }
- }
-
- public static void unregisterMBean(String objTypeName, String objInstanceName) throws MalformedObjectNameException, MBeanRegistrationException,
- InstanceNotFoundException {
-
- ObjectName name = composeMBeanName(objTypeName, objInstanceName);
- unregisterMBean(name);
- }
-
- public static void unregisterMBean(ObjectName name) throws MalformedObjectNameException, MBeanRegistrationException, InstanceNotFoundException {
-
- ArrayList<MBeanServer> server = MBeanServerFactory.findMBeanServer(null);
- if (server.size() > 0) {
- MBeanServer mBeanServer = server.get(0);
- mBeanServer.unregisterMBean(name);
- } else {
- MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
- mBeanServer.unregisterMBean(name);
- }
- }
-
- private static ObjectName composeMBeanName(String objTypeName, String objInstanceName) throws MalformedObjectNameException {
-
- String name = "com.cloud:type=" + objTypeName;
- if (objInstanceName != null && !objInstanceName.isEmpty())
- name += ", name=" + objInstanceName;
-
- return new ObjectName(name);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/mgmt/ManagementBean.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/mgmt/ManagementBean.java b/utils/src/com/cloud/utils/mgmt/ManagementBean.java
deleted file mode 100644
index 387052e..0000000
--- a/utils/src/com/cloud/utils/mgmt/ManagementBean.java
+++ /dev/null
@@ -1,27 +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 com.cloud.utils.mgmt;
-
-/**
- * we ever need common use methods here.
- */
-public interface ManagementBean {
- String getName();
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/mgmt/PropertyMapDynamicBean.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/mgmt/PropertyMapDynamicBean.java b/utils/src/com/cloud/utils/mgmt/PropertyMapDynamicBean.java
deleted file mode 100644
index d1689eb..0000000
--- a/utils/src/com/cloud/utils/mgmt/PropertyMapDynamicBean.java
+++ /dev/null
@@ -1,120 +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 com.cloud.utils.mgmt;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.AttributeNotFoundException;
-import javax.management.DynamicMBean;
-import javax.management.InvalidAttributeValueException;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanException;
-import javax.management.MBeanInfo;
-import javax.management.ReflectionException;
-
-public class PropertyMapDynamicBean implements DynamicMBean {
-
- private Map<String, Object> _propMap = new HashMap<String, Object>();
-
- public PropertyMapDynamicBean() {
- }
-
- public PropertyMapDynamicBean(Map<String, Object> propMap) {
- _propMap = propMap;
- }
-
- @Override
- public synchronized Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException {
- if (_propMap != null) {
- return _propMap.get(name);
- }
-
- throw new AttributeNotFoundException("No such property " + name);
- }
-
- @Override
- public synchronized AttributeList getAttributes(String[] names) {
- AttributeList list = new AttributeList();
- for (String name : names) {
- Object value = _propMap.get(name);
- if (value != null)
- list.add(new Attribute(name, value));
- }
- return list;
- }
-
- @Override
- public synchronized MBeanInfo getMBeanInfo() {
- SortedSet<String> names = new TreeSet<String>();
-
- for (String name : _propMap.keySet())
- names.add(name);
-
- MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[names.size()];
- Iterator<String> it = names.iterator();
- for (int i = 0; i < attrs.length; i++) {
- String name = it.next();
- attrs[i] = new MBeanAttributeInfo(name, "java.lang.String", name, true, // isReadable
- true, // isWritable
- false); // isIs
- }
-
- return new MBeanInfo(this.getClass().getName(), "Dynamic MBean", attrs, null, null, null);
- }
-
- @Override
- public synchronized Object invoke(String name, Object[] args, String[] sig) throws MBeanException, ReflectionException {
- throw new ReflectionException(new NoSuchMethodException(name));
- }
-
- @Override
- public synchronized void setAttribute(Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
- String name = attr.getName();
- if (name != null)
- _propMap.put(name, attr.getValue());
- }
-
- @Override
- public synchronized AttributeList setAttributes(AttributeList list) {
- Attribute[] attrs = list.toArray(new Attribute[0]);
- AttributeList retList = new AttributeList();
- for (Attribute attr : attrs) {
- String name = attr.getName();
- Object value = attr.getValue();
- _propMap.put(name, value);
- retList.add(new Attribute(name, value));
- }
- return retList;
- }
-
- public synchronized void addProp(String name, Object value) {
- _propMap.put(name, value);
- }
-
- public synchronized Object getProp(String name) {
- return _propMap.get(name);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/net/Ip.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/Ip.java b/utils/src/com/cloud/utils/net/Ip.java
deleted file mode 100644
index 09312bc..0000000
--- a/utils/src/com/cloud/utils/net/Ip.java
+++ /dev/null
@@ -1,98 +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 com.cloud.utils.net;
-
-import java.io.Serializable;
-
-import com.cloud.utils.NumbersUtil;
-import com.cloud.utils.SerialVersionUID;
-
-/**
- * Simple Ip implementation class that works with both ip4 and ip6.
- *
- */
-public class Ip implements Serializable, Comparable<Ip> {
-
- private static final long serialVersionUID = SerialVersionUID.Ip;
-
- long ip;
-
- public Ip(long ip) {
- this.ip = ip;
- }
-
- public Ip(String ip) {
- this.ip = NetUtils.ip2Long(ip);
- }
-
- protected Ip() {
- }
-
- public String addr() {
- return toString();
- }
-
- public long longValue() {
- return ip;
- }
-
- @Override
- public String toString() {
- return NetUtils.long2Ip(ip);
- }
-
- public boolean isIp4() {
- return ip <= 2L * Integer.MAX_VALUE + 1;
- }
-
- public boolean isIp6() {
- return ip > Integer.MAX_VALUE;
- }
-
- @Override
- public int hashCode() {
- return NumbersUtil.hash(ip);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof Ip) {
- return ip == ((Ip)obj).ip;
- }
- return false;
- }
-
- public boolean isSameAddressAs(Object obj) {
- if (this.equals(obj)) {
- return true;
- } else if (obj instanceof String) {
- return ip == NetUtils.ip2Long((String)obj);
- } else if (obj instanceof Long) {
- return ip == (Long)obj;
- } else {
- return false;
- }
- }
-
- @Override
- public int compareTo(Ip that) {
- return (int)(this.ip - that.ip);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/net/Ip4Address.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/Ip4Address.java b/utils/src/com/cloud/utils/net/Ip4Address.java
deleted file mode 100644
index 0bd814d..0000000
--- a/utils/src/com/cloud/utils/net/Ip4Address.java
+++ /dev/null
@@ -1,80 +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 com.cloud.utils.net;
-
-public class Ip4Address {
- String _addr;
- String _mac;
- static final String s_empty_mac = "00:00:00:00:00:00";
-
- public Ip4Address(String addr, String mac) {
- _addr = addr;
- _mac = mac;
- }
-
- public Ip4Address(long addr, long mac) {
- _addr = NetUtils.long2Ip(addr);
- _mac = NetUtils.long2Mac(mac);
- }
-
- public Ip4Address(String addr) {
- this(addr, s_empty_mac);
- }
-
- public Ip4Address(long addr) {
- this(NetUtils.long2Ip(addr), s_empty_mac);
- }
-
- public String ip4() {
- return _addr;
- }
-
- public String mac() {
- return _mac;
- }
-
- public long toLong() {
- return NetUtils.ip2Long(_addr);
- }
-
- @Override
- public boolean equals(Object that) {
-
- if (that instanceof Ip4Address) {
- Ip4Address ip4 = (Ip4Address)that;
- return _addr.equals(ip4._addr) && (_mac == ip4._mac || _mac.equals(ip4._mac));
- } else {
- return false;
- }
- }
-
- public boolean isSameAddressAs(Object other) {
- if (other instanceof String) { // Assume that is an ip4 address in String form
- return _addr.equals(other);
- } else {
- return equals(other);
- }
- }
-
- @Override
- public int hashCode(){
- return _mac.hashCode()*_addr.hashCode();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/net/MacAddress.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/MacAddress.java b/utils/src/com/cloud/utils/net/MacAddress.java
deleted file mode 100644
index b9118cf..0000000
--- a/utils/src/com/cloud/utils/net/MacAddress.java
+++ /dev/null
@@ -1,367 +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 com.cloud.utils.net;
-
-import static com.cloud.utils.AutoCloseableUtil.closeAutoCloseable;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Formatter;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.NumbersUtil;
-
-/**
- * copied from the public domain utility from John Burkard.
- * @author <a href="mailto:jb@eaio.com">Johann Burkard</a>
- * @version 2.1.3
- **/
-public class MacAddress {
- private static final Logger s_logger = Logger.getLogger(MacAddress.class);
- private long _addr = 0;
-
- protected MacAddress() {
- }
-
- public MacAddress(long addr) {
- _addr = addr;
- }
-
- public long toLong() {
- return _addr;
- }
-
- public byte[] toByteArray() {
- byte[] bytes = new byte[6];
- bytes[0] = (byte)((_addr >> 40) & 0xff);
- bytes[1] = (byte)((_addr >> 32) & 0xff);
- bytes[2] = (byte)((_addr >> 24) & 0xff);
- bytes[3] = (byte)((_addr >> 16) & 0xff);
- bytes[4] = (byte)((_addr >> 8) & 0xff);
- bytes[5] = (byte)((_addr >> 0) & 0xff);
- return bytes;
- }
-
- public String toString(String separator) {
- StringBuilder buff = new StringBuilder();
- Formatter formatter = new Formatter(buff);
- formatter.format("%02x%s%02x%s%02x%s%02x%s%02x%s%02x", _addr >> 40 & 0xff, separator, _addr >> 32 & 0xff, separator, _addr >> 24 & 0xff, separator,
- _addr >> 16 & 0xff, separator, _addr >> 8 & 0xff, separator, _addr & 0xff);
- return buff.toString();
-
- /*
-
- String str = Long.toHexString(_addr);
-
- for (int i = str.length() - 1; i >= 0; i--) {
- buff.append(str.charAt(i));
- if (separator != null && (str.length() - i) % 2 == 0) {
- buff.append(separator);
- }
- }
- return buff.reverse().toString();
- */
- }
-
- @Override
- public String toString() {
- return toString(":");
- }
-
- private static MacAddress s_address;
- static {
- String macAddress = null;
-
- Process p = null;
- BufferedReader in = null;
-
- try {
- String osname = System.getProperty("os.name");
-
- if (osname.startsWith("Windows")) {
- p = Runtime.getRuntime().exec(new String[] {"ipconfig", "/all"}, null);
- } else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) {
- // Solaris code must appear before the generic code
- String hostName = MacAddress.getFirstLineOfCommand(new String[] {"uname", "-n"});
- if (hostName != null) {
- p = Runtime.getRuntime().exec(new String[] {"/usr/sbin/arp", hostName}, null);
- }
- } else if (new File("/usr/sbin/lanscan").exists()) {
- p = Runtime.getRuntime().exec(new String[] {"/usr/sbin/lanscan"}, null);
- } else if (new File("/sbin/ifconfig").exists()) {
- p = Runtime.getRuntime().exec(new String[] {"/sbin/ifconfig", "-a"}, null);
- }
-
- if (p != null) {
- in = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
- String l = null;
- while ((l = in.readLine()) != null) {
- macAddress = MacAddress.parse(l);
- if (macAddress != null) {
- short parsedShortMacAddress = MacAddress.parseShort(macAddress);
- if (parsedShortMacAddress != 0xff && parsedShortMacAddress != 0x00)
- break;
- }
- macAddress = null;
- }
- }
-
- } catch (SecurityException ex) {
- s_logger.info("[ignored] security exception in static initializer of MacAddress", ex);
- } catch (IOException ex) {
- s_logger.info("[ignored] io exception in static initializer of MacAddress");
- } finally {
- if (p != null) {
- closeAutoCloseable(in, "closing init process input stream");
- closeAutoCloseable(p.getErrorStream(), "closing init process error output stream");
- closeAutoCloseable(p.getOutputStream(), "closing init process std output stream");
- p.destroy();
- }
- }
-
- long clockSeqAndNode = 0;
-
- if (macAddress != null) {
- if (macAddress.indexOf(':') != -1) {
- clockSeqAndNode |= MacAddress.parseLong(macAddress);
- } else if (macAddress.startsWith("0x")) {
- clockSeqAndNode |= MacAddress.parseLong(macAddress.substring(2));
- }
- } else {
- try {
- byte[] local = InetAddress.getLocalHost().getAddress();
- clockSeqAndNode |= (local[0] << 24) & 0xFF000000L;
- clockSeqAndNode |= (local[1] << 16) & 0xFF0000;
- clockSeqAndNode |= (local[2] << 8) & 0xFF00;
- clockSeqAndNode |= local[3] & 0xFF;
- } catch (UnknownHostException ex) {
- clockSeqAndNode |= (long)(Math.random() * 0x7FFFFFFF);
- }
- }
-
- s_address = new MacAddress(clockSeqAndNode);
- }
-
- public static MacAddress getMacAddress() {
- return s_address;
- }
-
- private static String getFirstLineOfCommand(String[] commands) throws IOException {
-
- Process p = null;
- BufferedReader reader = null;
-
- try {
- p = Runtime.getRuntime().exec(commands);
- reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
-
- return reader.readLine();
- } finally {
- if (p != null) {
- closeAutoCloseable(reader, "closing process input stream");
- closeAutoCloseable(p.getErrorStream(), "closing process error output stream");
- closeAutoCloseable(p.getOutputStream(), "closing process std output stream");
- p.destroy();
- }
- }
-
- }
-
- /**
- * The MAC address parser attempts to find the following patterns:
- * <ul>
- * <li>.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}</li>
- * <li>.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}</li>
- * </ul>
- *
- * This is copied from the author below. The author encouraged copying
- * it.
- *
- */
- static String parse(String in) {
-
- // lanscan
-
- int hexStart = in.indexOf("0x");
- if (hexStart != -1) {
- int hexEnd = in.indexOf(' ', hexStart);
- if (hexEnd != -1) {
- return in.substring(hexStart, hexEnd);
- }
- }
-
- int octets = 0;
- int lastIndex, old, end;
-
- if (in.indexOf('-') > -1) {
- in = in.replace('-', ':');
- }
-
- lastIndex = in.lastIndexOf(':');
-
- if (lastIndex > in.length() - 2)
- return null;
-
- end = Math.min(in.length(), lastIndex + 3);
-
- ++octets;
- old = lastIndex;
- while (octets != 5 && lastIndex != -1 && lastIndex > 1) {
- lastIndex = in.lastIndexOf(':', --lastIndex);
- if (old - lastIndex == 3 || old - lastIndex == 2) {
- ++octets;
- old = lastIndex;
- }
- }
-
- if (octets == 5 && lastIndex > 1) {
- return in.substring(lastIndex - 2, end).trim();
- }
- return null;
- }
-
- public static void main(String[] args) {
- MacAddress addr = MacAddress.getMacAddress();
- System.out.println("addr in integer is " + addr.toLong());
- System.out.println("addr in bytes is " + NumbersUtil.bytesToString(addr.toByteArray(), 0, addr.toByteArray().length));
- System.out.println("addr in char is " + addr.toString(":"));
- }
-
- /**
- * Parses a <code>long</code> from a hex encoded number. This method will skip
- * all characters that are not 0-9 and a-f (the String is lower cased first).
- * Returns 0 if the String does not contain any interesting characters.
- *
- * @param s the String to extract a <code>long</code> from, may not be <code>null</code>
- * @return a <code>long</code>
- * @throws NullPointerException if the String is <code>null</code>
- */
- public static long parseLong(String s) throws NullPointerException {
- s = s.toLowerCase();
- long out = 0;
- byte shifts = 0;
- char c;
- for (int i = 0; i < s.length() && shifts < 16; i++) {
- c = s.charAt(i);
- if ((c > 47) && (c < 58)) {
- out <<= 4;
- ++shifts;
- out |= c - 48;
- } else if ((c > 96) && (c < 103)) {
- ++shifts;
- out <<= 4;
- out |= c - 87;
- }
- }
- return out;
- }
-
- /**
- * Parses an <code>int</code> from a hex encoded number. This method will skip
- * all characters that are not 0-9 and a-f (the String is lower cased first).
- * Returns 0 if the String does not contain any interesting characters.
- *
- * @param s the String to extract an <code>int</code> from, may not be <code>null</code>
- * @return an <code>int</code>
- * @throws NullPointerException if the String is <code>null</code>
- */
- public static int parseInt(String s) throws NullPointerException {
- s = s.toLowerCase();
- int out = 0;
- byte shifts = 0;
- char c;
- for (int i = 0; i < s.length() && shifts < 8; i++) {
- c = s.charAt(i);
- if ((c > 47) && (c < 58)) {
- out <<= 4;
- ++shifts;
- out |= c - 48;
- } else if ((c > 96) && (c < 103)) {
- ++shifts;
- out <<= 4;
- out |= c - 87;
- }
- }
- return out;
- }
-
- /**
- * Parses a <code>short</code> from a hex encoded number. This method will skip
- * all characters that are not 0-9 and a-f (the String is lower cased first).
- * Returns 0 if the String does not contain any interesting characters.
- *
- * @param s the String to extract a <code>short</code> from, may not be <code>null</code>
- * @return a <code>short</code>
- * @throws NullPointerException if the String is <code>null</code>
- */
- public static short parseShort(String s) throws NullPointerException {
- s = s.toLowerCase();
- short out = 0;
- byte shifts = 0;
- char c;
- for (int i = 0; i < s.length() && shifts < 4; i++) {
- c = s.charAt(i);
- if ((c > 47) && (c < 58)) {
- out <<= 4;
- ++shifts;
- out |= c - 48;
- } else if ((c > 96) && (c < 103)) {
- ++shifts;
- out <<= 4;
- out |= c - 87;
- }
- }
- return out;
- }
-
- /**
- * Parses a <code>byte</code> from a hex encoded number. This method will skip
- * all characters that are not 0-9 and a-f (the String is lower cased first).
- * Returns 0 if the String does not contain any interesting characters.
- *
- * @param s the String to extract a <code>byte</code> from, may not be <code>null</code>
- * @return a <code>byte</code>
- * @throws NullPointerException if the String is <code>null</code>
- */
- public static byte parseByte(String s) throws NullPointerException {
- s = s.toLowerCase();
- byte out = 0;
- byte shifts = 0;
- char c;
- for (int i = 0; i < s.length() && shifts < 2; i++) {
- c = s.charAt(i);
- if ((c > 47) && (c < 58)) {
- out <<= 4;
- ++shifts;
- out |= c - 48;
- } else if ((c > 96) && (c < 103)) {
- ++shifts;
- out <<= 4;
- out |= c - 87;
- }
- }
- return out;
- }
-}
[47/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Refactor NSX api implementation (NiciraNvpApi)
- Make internal method private
- Remove unused methods
- Refactor type deserialization adapter classes out
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c6602ee1
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c6602ee1
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c6602ee1
Branch: refs/heads/deploy-from-snapshot
Commit: c6602ee151968d266d22553e21f47bbc24de1199
Parents: 18e6b9b
Author: Miguel Ferreira <mi...@me.com>
Authored: Sat Aug 22 16:12:12 2015 +0200
Committer: Miguel Ferreira <mi...@me.com>
Committed: Tue Aug 25 17:36:16 2015 +0200
----------------------------------------------------------------------
.../cloud/network/nicira/NatRuleAdapter.java | 49 +++++++++++++++
.../com/cloud/network/nicira/NiciraNvpApi.java | 63 ++++----------------
.../network/nicira/RoutingConfigAdapter.java | 52 ++++++++++++++++
.../network/nicira/NatRuleAdapterTest.java | 60 +++++++++++++++++++
.../com/cloud/network/nicira/NatRuleTest.java | 2 +-
.../nicira/RoutingConfigAdapterTest.java | 57 ++++++++++++++++++
6 files changed, 229 insertions(+), 54 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6602ee1/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java
new file mode 100644
index 0000000..7ea2f5b
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java
@@ -0,0 +1,49 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.lang.reflect.Type;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+
+public class NatRuleAdapter implements JsonDeserializer<NatRule> {
+
+ @Override
+ public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
+ final JsonObject jsonObject = jsonElement.getAsJsonObject();
+
+ if (!jsonObject.has("type")) {
+ throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object");
+ }
+
+ final String natRuleType = jsonObject.get("type").getAsString();
+ if ("SourceNatRule".equals(natRuleType)) {
+ return context.deserialize(jsonElement, SourceNatRule.class);
+ } else if ("DestinationNatRule".equals(natRuleType)) {
+ return context.deserialize(jsonElement, DestinationNatRule.class);
+ }
+
+ throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\"");
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6602ee1/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
index 06446a7..39262b6 100644
--- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java
@@ -32,9 +32,6 @@ import com.cloud.utils.rest.RESTServiceConnector;
import com.cloud.utils.rest.RESTValidationStrategy;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
@SuppressWarnings("rawtypes")
@@ -50,7 +47,7 @@ public class NiciraNvpApi {
private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter";
private static final String LOGIN_URL = "/ws.v1/login";
- protected RESTServiceConnector restConnector;
+ private final RESTServiceConnector restConnector;
protected final static Map<Class, String> prefixMap;
@@ -111,7 +108,7 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- protected <T> T create(final T entity) throws NiciraNvpApiException {
+ private <T> T create(final T entity) throws NiciraNvpApiException {
final String uri = prefixMap.get(entity.getClass());
return createWithUri(entity, uri);
}
@@ -123,7 +120,7 @@ public class NiciraNvpApi {
* @return
* @throws NiciraNvpApiException
*/
- protected <T> T createWithUri(final T entity, final String uri) throws NiciraNvpApiException {
+ private <T> T createWithUri(final T entity, final String uri) throws NiciraNvpApiException {
T createdEntity;
try {
createdEntity = restConnector.executeCreateObject(entity, new TypeToken<T>() {
@@ -138,24 +135,15 @@ public class NiciraNvpApi {
/**
* GET list of items
*
- * @return
- * @throws NiciraNvpApiException
- */
- protected <T> NiciraNvpList<T> find(final Class<T> clazz) throws NiciraNvpApiException {
- return find(null, clazz);
- }
-
- /**
- * GET list of items
- *
* @param uuid
+ *
* @return
* @throws NiciraNvpApiException
*/
- public <T> NiciraNvpList<T> find(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
+ private <T> List<T> find(final Optional<String> uuid, final Class<T> clazz) throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz);
Map<String, String> params = defaultListParams;
- if (uuid != null) {
+ if (uuid.isPresent()) {
params = new HashMap<String, String>(defaultListParams);
params.put("uuid", uuid);
}
@@ -181,7 +169,7 @@ public class NiciraNvpApi {
* @param uuid
* @throws NiciraNvpApiException
*/
- public <T> void update(final T item, final String uuid) throws NiciraNvpApiException {
+ private <T> void update(final T item, final String uuid) throws NiciraNvpApiException {
final String uri = prefixMap.get(item.getClass()) + "/" + uuid;
updateWithUri(item, uri);
}
@@ -193,7 +181,7 @@ public class NiciraNvpApi {
* @param uuid
* @throws NiciraNvpApiException
*/
- public <T> void updateWithUri(final T item, final String uri) throws NiciraNvpApiException {
+ private <T> void updateWithUri(final T item, final String uri) throws NiciraNvpApiException {
try {
restConnector.executeUpdateObject(item, uri, Collections.<String, String> emptyMap());
} catch (final CloudstackRESTException e) {
@@ -207,7 +195,7 @@ public class NiciraNvpApi {
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
- public <T> void delete(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
+ private <T> void delete(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz) + "/" + uuid;
deleteWithUri(uri);
}
@@ -218,7 +206,7 @@ public class NiciraNvpApi {
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
- public void deleteWithUri(final String uri) throws NiciraNvpApiException {
+ private void deleteWithUri(final String uri) throws NiciraNvpApiException {
try {
restConnector.executeDeleteObject(uri);
} catch (final CloudstackRESTException e) {
@@ -588,48 +576,17 @@ public class NiciraNvpApi {
}
}
- public static class NatRuleAdapter implements JsonDeserializer<NatRule> {
- @Override
- public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
- final JsonObject jsonObject = jsonElement.getAsJsonObject();
- if (!jsonObject.has("type")) {
- throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object");
- }
- final String natRuleType = jsonObject.get("type").getAsString();
- if ("SourceNatRule".equals(natRuleType)) {
- return context.deserialize(jsonElement, SourceNatRule.class);
- } else if ("DestinationNatRule".equals(natRuleType)) {
- return context.deserialize(jsonElement, DestinationNatRule.class);
- }
- throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\"");
- }
}
- public static class RoutingConfigAdapter implements JsonDeserializer<RoutingConfig> {
- private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig";
- private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig";
- @Override
- public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
- final JsonObject jsonObject = jsonElement.getAsJsonObject();
- if (!jsonObject.has("type")) {
- throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object");
- }
- final String routingConfigType = jsonObject.get("type").getAsString();
- if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) {
- return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class);
- } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) {
- return context.deserialize(jsonElement, RoutingTableRoutingConfig.class);
- }
- throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\"");
}
}
}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6602ee1/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java
new file mode 100644
index 0000000..ad94f63
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java
@@ -0,0 +1,52 @@
+//
+// 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 com.cloud.network.nicira;
+
+import java.lang.reflect.Type;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+
+public class RoutingConfigAdapter implements JsonDeserializer<RoutingConfig> {
+
+ private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig";
+ private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig";
+
+ @Override
+ public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
+ final JsonObject jsonObject = jsonElement.getAsJsonObject();
+
+ if (!jsonObject.has("type")) {
+ throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object");
+ }
+
+ final String routingConfigType = jsonObject.get("type").getAsString();
+ if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) {
+ return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class);
+ } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) {
+ return context.deserialize(jsonElement, RoutingTableRoutingConfig.class);
+ }
+
+ throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\"");
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6602ee1/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java
new file mode 100644
index 0000000..199a6fe
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java
@@ -0,0 +1,60 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.instanceOf;
+
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+
+public class NatRuleAdapterTest {
+ private final Gson gson = new GsonBuilder()
+ .registerTypeAdapter(NatRule.class, new NatRuleAdapter())
+ .create();
+
+ @Test(expected = JsonParseException.class)
+ public void testNatRuleAdapterNoType() {
+ gson.fromJson("{}", NatRule.class);
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testNatRuleAdapterWrongType() {
+ gson.fromJson("{type : \"WrongType\"}", NatRule.class);
+ }
+
+ @Test()
+ public void testNatRuleAdapterWithSourceNatRule() {
+ final SourceNatRule sourceNatRule = (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class);
+
+ assertThat(sourceNatRule, instanceOf(SourceNatRule.class));
+ }
+
+ @Test()
+ public void testNatRuleAdapterWithDestinationNatRule() {
+ final DestinationNatRule destinationNatRule = (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class);
+
+ assertThat(destinationNatRule, instanceOf(DestinationNatRule.class));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6602ee1/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
index d4c6596..e4072bd 100644
--- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java
@@ -32,7 +32,7 @@ public class NatRuleTest {
@Test
public void testNatRuleEncoding() {
final Gson gson =
- new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter())
+ new GsonBuilder().registerTypeAdapter(NatRule.class, new NatRuleAdapter())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6602ee1/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java
new file mode 100644
index 0000000..44269b2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java
@@ -0,0 +1,57 @@
+//
+// 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 com.cloud.network.nicira;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.notNullValue;
+
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+
+public class RoutingConfigAdapterTest {
+ private final Gson gson = new GsonBuilder()
+ .registerTypeAdapter(RoutingConfig.class, new RoutingConfigAdapter())
+ .create();
+
+ @Test(expected = JsonParseException.class)
+ public void testRoutingConfigAdapterNoType() {
+ gson.fromJson("{}", RoutingConfig.class);
+ }
+
+ @Test(expected = JsonParseException.class)
+ public void testRoutingConfigAdapterWrongType() {
+ gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class);
+ }
+
+ @Test()
+ public void testRoutingConfigAdapter() throws Exception {
+ final String jsonString = "{type : \"SingleDefaultRouteImplicitRoutingConfig\"}";
+
+ final SingleDefaultRouteImplicitRoutingConfig object = gson.fromJson(jsonString, SingleDefaultRouteImplicitRoutingConfig.class);
+
+ assertThat(object, notNullValue());
+ assertThat(object, instanceOf(SingleDefaultRouteImplicitRoutingConfig.class));
+ }
+
+}
[36/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java
new file mode 100644
index 0000000..431e855
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java
@@ -0,0 +1,99 @@
+//
+// 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 com.cloud.network;
+
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.apache.cloudstack.api.InternalIdentity;
+
+@Entity
+@Table(name = "external_nicira_nvp_devices")
+public class NiciraNvpDeviceVO implements InternalIdentity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private long id;
+
+ @Column(name = "uuid")
+ private String uuid;
+
+ @Column(name = "host_id")
+ private long hostId;
+
+ @Column(name = "physical_network_id")
+ private long physicalNetworkId;
+
+ @Column(name = "provider_name")
+ private String providerName;
+
+ @Column(name = "device_name")
+ private String deviceName;
+
+ public NiciraNvpDeviceVO() {
+ uuid = UUID.randomUUID().toString();
+ }
+
+ public NiciraNvpDeviceVO(final long hostId, final long physicalNetworkId, final String providerName, final String deviceName) {
+ super();
+ this.hostId = hostId;
+ this.physicalNetworkId = physicalNetworkId;
+ this.providerName = providerName;
+ this.deviceName = deviceName;
+ uuid = UUID.randomUUID().toString();
+ }
+
+ @Override
+ public long getId() {
+ return id;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public long getPhysicalNetworkId() {
+ return physicalNetworkId;
+ }
+
+ public long getHostId() {
+ return hostId;
+ }
+
+ public String getProviderName() {
+ return providerName;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java
new file mode 100644
index 0000000..9b13780
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java
@@ -0,0 +1,87 @@
+//
+// 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 com.cloud.network;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.apache.cloudstack.api.InternalIdentity;
+
+@Entity
+@Table(name = "nicira_nvp_nic_map")
+public class NiciraNvpNicMappingVO implements InternalIdentity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private long id;
+
+ @Column(name = "logicalswitch")
+ private String logicalSwitchUuid;
+
+ @Column(name = "logicalswitchport")
+ private String logicalSwitchPortUuid;
+
+ @Column(name = "nic")
+ private String nicUuid;
+
+ public NiciraNvpNicMappingVO() {
+ }
+
+ public NiciraNvpNicMappingVO(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final String nicUuid) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ this.logicalSwitchPortUuid = logicalSwitchPortUuid;
+ this.nicUuid = nicUuid;
+ }
+
+ public String getLogicalSwitchUuid() {
+ return logicalSwitchUuid;
+ }
+
+ public void setLogicalSwitchUuid(final String logicalSwitchUuid) {
+ this.logicalSwitchUuid = logicalSwitchUuid;
+ }
+
+ public String getLogicalSwitchPortUuid() {
+ return logicalSwitchPortUuid;
+ }
+
+ public void setLogicalSwitchPortUuid(final String logicalSwitchPortUuid) {
+ this.logicalSwitchPortUuid = logicalSwitchPortUuid;
+ }
+
+ public String getNicUuid() {
+ return nicUuid;
+ }
+
+ public void setNicUuid(String nicUuid) {
+ this.nicUuid = nicUuid;
+ }
+
+ @Override
+ public long getId() {
+ return id;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java
new file mode 100644
index 0000000..9fae3cd
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java
@@ -0,0 +1,85 @@
+//
+// 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 com.cloud.network;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.apache.cloudstack.api.InternalIdentity;
+
+@Entity
+@Table(name = "nicira_nvp_router_map")
+public class NiciraNvpRouterMappingVO implements InternalIdentity {
+ //FIXME the ddl for this table should be in one of the upgrade scripts
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private long id;
+
+ @Column(name = "logicalrouter_uuid")
+ private String logicalRouterUuid;
+
+ @Column(name = "network_id")
+ private long networkId;
+
+ public NiciraNvpRouterMappingVO() {
+ }
+
+ public NiciraNvpRouterMappingVO(final String logicalRouterUuid, final long networkId) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ this.networkId = networkId;
+ }
+
+ public NiciraNvpRouterMappingVO(final long id, final String logicalRouterUuid, final long networkId) {
+ this.id = id;
+ this.logicalRouterUuid = logicalRouterUuid;
+ this.networkId = networkId;
+ }
+
+ @Override
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final long id) {
+ this.id = id;
+ }
+
+ public String getLogicalRouterUuid() {
+ return logicalRouterUuid;
+ }
+
+ public void setLogicalRouterUuid(final String logicalRouterUuid) {
+ this.logicalRouterUuid = logicalRouterUuid;
+ }
+
+ public long getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(final long networkId) {
+ this.networkId = networkId;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java
new file mode 100644
index 0000000..f2a9754
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java
@@ -0,0 +1,35 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.dao;
+
+import java.util.List;
+
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface NiciraNvpDao extends GenericDao<NiciraNvpDeviceVO, Long> {
+ /**
+ * list all the nicira nvp devices added in to this physical network
+ * @param physicalNetworkId physical Network Id
+ * @return list of NiciraNvpDeviceVO for this physical network.
+ */
+ List<NiciraNvpDeviceVO> listByPhysicalNetwork(long physicalNetworkId);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java
new file mode 100644
index 0000000..3144c81
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java
@@ -0,0 +1,53 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+
+@Component
+@Local(value = NiciraNvpDao.class)
+public class NiciraNvpDaoImpl extends GenericDaoBase<NiciraNvpDeviceVO, Long> implements NiciraNvpDao {
+
+ protected final SearchBuilder<NiciraNvpDeviceVO> physicalNetworkIdSearch;
+
+ public NiciraNvpDaoImpl() {
+ physicalNetworkIdSearch = createSearchBuilder();
+ physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ);
+ physicalNetworkIdSearch.done();
+ }
+
+ @Override
+ public List<NiciraNvpDeviceVO> listByPhysicalNetwork(final long physicalNetworkId) {
+ SearchCriteria<NiciraNvpDeviceVO> sc = physicalNetworkIdSearch.create();
+ sc.setParameters("physicalNetworkId", physicalNetworkId);
+ return search(sc, null);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java
new file mode 100644
index 0000000..ff81b759
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java
@@ -0,0 +1,32 @@
+//
+// 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 com.cloud.network.dao;
+
+import com.cloud.network.NiciraNvpNicMappingVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface NiciraNvpNicMappingDao extends GenericDao<NiciraNvpNicMappingVO, Long> {
+
+ /** find the mapping for a nic
+ * @param nicUuid the Uuid of a nic attached to a logical switch port
+ * @return NiciraNvpNicMapping for this nic uuid or null if it does not exist
+ */
+ public NiciraNvpNicMappingVO findByNicUuid(String nicUuid);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java
new file mode 100644
index 0000000..603855c
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java
@@ -0,0 +1,51 @@
+//
+// 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 com.cloud.network.dao;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.network.NiciraNvpNicMappingVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+
+@Component
+@Local(value = NiciraNvpNicMappingDao.class)
+public class NiciraNvpNicMappingDaoImpl extends GenericDaoBase<NiciraNvpNicMappingVO, Long> implements NiciraNvpNicMappingDao {
+
+ protected final SearchBuilder<NiciraNvpNicMappingVO> nicSearch;
+
+ public NiciraNvpNicMappingDaoImpl() {
+ nicSearch = createSearchBuilder();
+ nicSearch.and("nicUuid", nicSearch.entity().getNicUuid(), Op.EQ);
+ nicSearch.done();
+ }
+
+ @Override
+ public NiciraNvpNicMappingVO findByNicUuid(final String nicUuid) {
+ SearchCriteria<NiciraNvpNicMappingVO> sc = nicSearch.create();
+ sc.setParameters("nicUuid", nicUuid);
+ return findOneBy(sc);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java
new file mode 100644
index 0000000..b64fb90
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java
@@ -0,0 +1,28 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.dao;
+
+import com.cloud.network.NiciraNvpRouterMappingVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface NiciraNvpRouterMappingDao extends GenericDao<NiciraNvpRouterMappingVO, Long> {
+
+ public NiciraNvpRouterMappingVO findByNetworkId(long id);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java
new file mode 100644
index 0000000..67d3658
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java
@@ -0,0 +1,51 @@
+//
+// 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 com.cloud.network.dao;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.network.NiciraNvpRouterMappingVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+
+@Component
+@Local(value = NiciraNvpRouterMappingDao.class)
+public class NiciraNvpRouterMappingDaoImpl extends GenericDaoBase<NiciraNvpRouterMappingVO, Long> implements NiciraNvpRouterMappingDao {
+
+ protected final SearchBuilder<NiciraNvpRouterMappingVO> networkSearch;
+
+ public NiciraNvpRouterMappingDaoImpl() {
+ networkSearch = createSearchBuilder();
+ networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ);
+ networkSearch.done();
+ }
+
+ @Override
+ public NiciraNvpRouterMappingVO findByNetworkId(final long id) {
+ SearchCriteria<NiciraNvpRouterMappingVO> sc = networkSearch.create();
+ sc.setParameters("network_id", id);
+ return findOneBy(sc);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java
new file mode 100644
index 0000000..0243e2d
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java
@@ -0,0 +1,849 @@
+//
+// 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 com.cloud.network.element;
+
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
+import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.CreateLogicalRouterAnswer;
+import com.cloud.agent.api.CreateLogicalRouterCommand;
+import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
+import com.cloud.agent.api.DeleteLogicalRouterAnswer;
+import com.cloud.agent.api.DeleteLogicalRouterCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
+import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
+import com.cloud.agent.api.FindLogicalSwitchPortCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.StartupNiciraNvpCommand;
+import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
+import com.cloud.agent.api.to.PortForwardingRuleTO;
+import com.cloud.agent.api.to.StaticNatRuleTO;
+import com.cloud.api.ApiDBUtils;
+import com.cloud.api.commands.AddNiciraNvpDeviceCmd;
+import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;
+import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;
+import com.cloud.api.commands.ListNiciraNvpDevicesCmd;
+import com.cloud.api.response.NiciraNvpDeviceResponse;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.dc.Vlan;
+import com.cloud.dc.dao.VlanDao;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.host.DetailVO;
+import com.cloud.host.Host;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.host.dao.HostDetailsDao;
+import com.cloud.network.IpAddress;
+import com.cloud.network.IpAddressManager;
+import com.cloud.network.Network;
+import com.cloud.network.Network.Capability;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.Networks;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.network.NiciraNvpNicMappingVO;
+import com.cloud.network.NiciraNvpRouterMappingVO;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.PublicIpAddress;
+import com.cloud.network.addr.PublicIp;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.NiciraNvpDao;
+import com.cloud.network.dao.NiciraNvpNicMappingDao;
+import com.cloud.network.dao.NiciraNvpRouterMappingDao;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.network.rules.StaticNat;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.resource.ResourceManager;
+import com.cloud.resource.ResourceState;
+import com.cloud.resource.ResourceStateAdapter;
+import com.cloud.resource.ServerResource;
+import com.cloud.resource.UnableDeleteHostException;
+import com.cloud.user.Account;
+import com.cloud.utils.component.AdapterBase;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionStatus;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.NetUtils;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.NicVO;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachineProfile;
+import com.cloud.vm.dao.NicDao;
+
+@Component
+@Local(value = {NetworkElement.class, ConnectivityProvider.class, SourceNatServiceProvider.class, StaticNatServiceProvider.class, PortForwardingServiceProvider.class,
+ IpDeployer.class})
+public class NiciraNvpElement extends AdapterBase implements ConnectivityProvider, SourceNatServiceProvider, PortForwardingServiceProvider, StaticNatServiceProvider,
+NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
+
+ private static final int MAX_PORT = 65535;
+ private static final int MIN_PORT = 0;
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpElement.class);
+
+ private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
+
+ @Inject
+ protected NicDao nicDao;
+ @Inject
+ protected ResourceManager resourceMgr;
+ @Inject
+ protected PhysicalNetworkDao physicalNetworkDao;
+ @Inject
+ protected PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao;
+ @Inject
+ protected NiciraNvpDao niciraNvpDao;
+ @Inject
+ protected HostDetailsDao hostDetailsDao;
+ @Inject
+ protected HostDao hostDao;
+ @Inject
+ protected AgentManager agentMgr;
+ @Inject
+ protected NiciraNvpNicMappingDao niciraNvpNicMappingDao;
+ @Inject
+ protected NiciraNvpRouterMappingDao niciraNvpRouterMappingDao;
+ @Inject
+ protected NetworkDao networkDao;
+ @Inject
+ protected NetworkOrchestrationService networkManager;
+ @Inject
+ protected NetworkModel networkModel;
+ @Inject
+ protected ConfigurationManager configMgr;
+ @Inject
+ protected NetworkServiceMapDao ntwkSrvcDao;
+ @Inject
+ protected VlanDao vlanDao;
+ @Inject
+ protected IpAddressManager ipAddrMgr;
+
+ @Override
+ public Map<Service, Map<Capability, String>> getCapabilities() {
+ return capabilities;
+ }
+
+ @Override
+ public Provider getProvider() {
+ return Provider.NiciraNvp;
+ }
+
+ protected boolean canHandle(Network network, Service service) {
+ s_logger.debug("Checking if NiciraNvpElement can handle service " + service.getName() + " on network " + network.getDisplayText());
+ if (network.getBroadcastDomainType() != BroadcastDomainType.Lswitch) {
+ return false;
+ }
+
+ if (!networkModel.isProviderForNetwork(getProvider(), network.getId())) {
+ s_logger.debug("NiciraNvpElement is not a provider for network " + network.getDisplayText());
+ return false;
+ }
+
+ if (!ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, Network.Provider.NiciraNvp)) {
+ s_logger.debug("NiciraNvpElement can't provide the " + service.getName() + " service on network " + network.getDisplayText());
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+ super.configure(name, params);
+ resourceMgr.registerResourceStateAdapter(name, this);
+ return true;
+ }
+
+ @Override
+ public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
+ ResourceUnavailableException, InsufficientCapacityException {
+ s_logger.debug("entering NiciraNvpElement implement function for network " + network.getDisplayText() + " (state " + network.getState() + ")");
+
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ if (network.getBroadcastUri() == null) {
+ s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
+ return false;
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+ hostDao.loadDetails(niciraNvpHost);
+
+ Account owner = context.getAccount();
+
+ /*
+ * TODO Shouldn't we lock the network as we might need to do
+ * multiple operations that should be done only once.
+ */
+
+ // Implement SourceNat immediately as we have al the info already
+ if (networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.NiciraNvp)) {
+ s_logger.debug("Apparently we are supposed to provide SourceNat on this network");
+
+ PublicIp sourceNatIp = ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network);
+ String publicCidr = sourceNatIp.getAddress().addr() + "/" + NetUtils.getCidrSize(sourceNatIp.getVlanNetmask());
+ String internalCidr = network.getGateway() + "/" + network.getCidr().split("/")[1];
+ // assuming a vlan:
+ String vtag = sourceNatIp.getVlanTag();
+ BroadcastDomainType tiep = null;
+ try {
+ tiep = BroadcastDomainType.getTypeOf(vtag);
+ } catch (URISyntaxException use) {
+ throw new CloudRuntimeException("vlantag for sourceNatIp is not valid: " + vtag, use);
+ }
+ if (tiep == BroadcastDomainType.Vlan) {
+ vtag = BroadcastDomainType.Vlan.getValueFrom(BroadcastDomainType.fromString(vtag));
+ } else if (!(tiep == BroadcastDomainType.UnDecided || tiep == BroadcastDomainType.Native)) {
+ throw new CloudRuntimeException("only vlans are supported for sourceNatIp, at this moment: " + vtag);
+ }
+ long vlanid = (Vlan.UNTAGGED.equals(vtag)) ? 0 : Long.parseLong(vtag);
+
+ CreateLogicalRouterCommand cmd =
+ new CreateLogicalRouterCommand(niciraNvpHost.getDetail("l3gatewayserviceuuid"), vlanid, BroadcastDomainType.getValue(network.getBroadcastUri()),
+ "router-" + network.getDisplayText(), publicCidr, sourceNatIp.getGateway(), internalCidr, context.getDomain().getName() + "-" +
+ context.getAccount().getAccountName());
+ CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+ if (answer.getResult() == false) {
+ s_logger.error("Failed to create Logical Router for network " + network.getDisplayText());
+ return false;
+ }
+
+ // Store the uuid so we can easily find it during cleanup
+ NiciraNvpRouterMappingVO routermapping = new NiciraNvpRouterMappingVO(answer.getLogicalRouterUuid(), network.getId());
+ niciraNvpRouterMappingDao.persist(routermapping);
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
+ throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ if (network.getBroadcastUri() == null) {
+ s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
+ return false;
+ }
+
+ NicVO nicVO = nicDao.findById(nic.getId());
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+
+ NiciraNvpNicMappingVO existingNicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid());
+ if (existingNicMap != null) {
+ FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchUuid(), existingNicMap.getLogicalSwitchPortUuid());
+ FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), findCmd);
+
+ if (answer.getResult()) {
+ s_logger.warn("Existing Logical Switchport found for nic " + nic.getName() + " with uuid " + existingNicMap.getLogicalSwitchPortUuid());
+ UpdateLogicalSwitchPortCommand cmd =
+ new UpdateLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchPortUuid(), BroadcastDomainType.getValue(network.getBroadcastUri()),
+ nicVO.getUuid(), context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName());
+ agentMgr.easySend(niciraNvpHost.getId(), cmd);
+ return true;
+ } else {
+ s_logger.error("Stale entry found for nic " + nic.getName() + " with logical switchport uuid " + existingNicMap.getLogicalSwitchPortUuid());
+ niciraNvpNicMappingDao.remove(existingNicMap.getId());
+ }
+ }
+
+ CreateLogicalSwitchPortCommand cmd =
+ new CreateLogicalSwitchPortCommand(BroadcastDomainType.getValue(network.getBroadcastUri()), nicVO.getUuid(), context.getDomain().getName() + "-" +
+ context.getAccount().getAccountName(), nic.getName());
+ CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("CreateLogicalSwitchPortCommand failed");
+ return false;
+ }
+
+ NiciraNvpNicMappingVO nicMap =
+ new NiciraNvpNicMappingVO(BroadcastDomainType.getValue(network.getBroadcastUri()), answer.getLogicalSwitchPortUuid(), nicVO.getUuid());
+ niciraNvpNicMappingDao.persist(nicMap);
+
+ return true;
+ }
+
+ @Override
+ public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException,
+ ResourceUnavailableException {
+
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ if (network.getBroadcastUri() == null) {
+ s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
+ return false;
+ }
+
+ NicVO nicVO = nicDao.findById(nic.getId());
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+
+ NiciraNvpNicMappingVO nicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid());
+ if (nicMap == null) {
+ s_logger.error("No mapping for nic " + nic.getName());
+ return false;
+ }
+
+ DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand(nicMap.getLogicalSwitchUuid(), nicMap.getLogicalSwitchPortUuid());
+ DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("DeleteLogicalSwitchPortCommand failed");
+ return false;
+ }
+
+ niciraNvpNicMappingDao.remove(nicMap.getId());
+
+ return true;
+ }
+
+ @Override
+ public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+
+ if (networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.NiciraNvp)) {
+ s_logger.debug("Apparently we were providing SourceNat on this network");
+
+ // Deleting the LogicalRouter will also take care of all provisioned
+ // nat rules.
+ NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
+ if (routermapping == null) {
+ s_logger.warn("No logical router uuid found for network " + network.getDisplayText());
+ // This might be cause by a failed deployment, so don't make shutdown fail as well.
+ return true;
+ }
+
+ DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid());
+ DeleteLogicalRouterAnswer answer = (DeleteLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+ if (answer.getResult() == false) {
+ s_logger.error("Failed to delete LogicalRouter for network " + network.getDisplayText());
+ return false;
+ }
+
+ niciraNvpRouterMappingDao.remove(routermapping.getId());
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean isReady(PhysicalNetworkServiceProvider provider) {
+ return true;
+ }
+
+ @Override
+ public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
+ ResourceUnavailableException {
+ // Nothing to do here.
+ return true;
+ }
+
+ @Override
+ public boolean canEnableIndividualServices() {
+ return true;
+ }
+
+ @Override
+ public boolean verifyServicesCombination(Set<Service> services) {
+ // This element can only function in a Nicra Nvp based
+ // SDN network, so Connectivity needs to be present here
+ if (!services.contains(Service.Connectivity)) {
+ s_logger.warn("Unable to provide services without Connectivity service enabled for this element");
+ return false;
+ }
+ if ((services.contains(Service.PortForwarding) || services.contains(Service.StaticNat)) && !services.contains(Service.SourceNat)) {
+ s_logger.warn("Unable to provide StaticNat and/or PortForwarding without the SourceNat service");
+ return false;
+ }
+ return true;
+ }
+
+ private static Map<Service, Map<Capability, String>> setCapabilities() {
+ Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
+
+ // L2 Support : SDN provisioning
+ capabilities.put(Service.Connectivity, null);
+
+ // L3 Support : Generic?
+ capabilities.put(Service.Gateway, null);
+
+ // L3 Support : SourceNat
+ Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>();
+ sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "peraccount");
+ sourceNatCapabilities.put(Capability.RedundantRouter, "false");
+ capabilities.put(Service.SourceNat, sourceNatCapabilities);
+
+ // L3 Support : Port Forwarding
+ capabilities.put(Service.PortForwarding, null);
+
+ // L3 support : StaticNat
+ capabilities.put(Service.StaticNat, null);
+
+ return capabilities;
+ }
+
+ @Override
+ public List<Class<?>> getCommands() {
+ List<Class<?>> cmdList = new ArrayList<Class<?>>();
+ cmdList.add(AddNiciraNvpDeviceCmd.class);
+ cmdList.add(DeleteNiciraNvpDeviceCmd.class);
+ cmdList.add(ListNiciraNvpDeviceNetworksCmd.class);
+ cmdList.add(ListNiciraNvpDevicesCmd.class);
+ return cmdList;
+ }
+
+ @Override
+ @DB
+ public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) {
+ ServerResource resource = new NiciraNvpResource();
+ final String deviceName = Network.Provider.NiciraNvp.getName();
+ NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
+ if (networkDevice == null) {
+ throw new CloudRuntimeException("No network device found for " + deviceName);
+ }
+ final Long physicalNetworkId = cmd.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
+ }
+ long zoneId = physicalNetwork.getDataCenterId();
+
+ final PhysicalNetworkServiceProviderVO ntwkSvcProvider =
+ physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
+ if (ntwkSvcProvider == null) {
+ throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " +
+ physicalNetworkId + "to add this device");
+ } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
+ throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " +
+ physicalNetworkId + "to add this device");
+ }
+
+ if (niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) {
+ throw new CloudRuntimeException("A NiciraNvp device is already configured on this physical network");
+ }
+
+ Map<String, String> params = new HashMap<String, String>();
+ params.put("guid", UUID.randomUUID().toString());
+ params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
+ params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
+ params.put("name", "Nicira Controller - " + cmd.getHost());
+ params.put("ip", cmd.getHost());
+ params.put("adminuser", cmd.getUsername());
+ params.put("adminpass", cmd.getPassword());
+ params.put("transportzoneuuid", cmd.getTransportzoneUuid());
+ // FIXME What to do with multiple isolation types
+ params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase());
+ if (cmd.getL3GatewayServiceUuid() != null) {
+ params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid());
+ }
+
+ Map<String, Object> hostdetails = new HashMap<String, Object>();
+ hostdetails.putAll(params);
+
+ try {
+ resource.configure(cmd.getHost(), hostdetails);
+
+ final Host host = resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
+ if (host != null) {
+ return Transaction.execute(new TransactionCallback<NiciraNvpDeviceVO>() {
+ @Override
+ public NiciraNvpDeviceVO doInTransaction(TransactionStatus status) {
+ NiciraNvpDeviceVO niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
+ niciraNvpDao.persist(niciraNvpDevice);
+
+ DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice.getId()));
+ hostDetailsDao.persist(detail);
+
+ return niciraNvpDevice;
+ }
+ });
+ } else {
+ throw new CloudRuntimeException("Failed to add Nicira Nvp Device due to internal error.");
+ }
+ } catch (ConfigurationException e) {
+ throw new CloudRuntimeException(e.getMessage());
+ }
+ }
+
+ @Override
+ public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(NiciraNvpDeviceVO niciraNvpDeviceVO) {
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDeviceVO.getHostId());
+ hostDao.loadDetails(niciraNvpHost);
+
+ NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse();
+ response.setDeviceName(niciraNvpDeviceVO.getDeviceName());
+ PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(niciraNvpDeviceVO.getPhysicalNetworkId());
+ if (pnw != null) {
+ response.setPhysicalNetworkId(pnw.getUuid());
+ }
+ response.setId(niciraNvpDeviceVO.getUuid());
+ response.setProviderName(niciraNvpDeviceVO.getProviderName());
+ response.setHostName(niciraNvpHost.getDetail("ip"));
+ response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid"));
+ response.setL3GatewayServiceUuid(niciraNvpHost.getDetail("l3gatewayserviceuuid"));
+ response.setObjectName("niciranvpdevice");
+ return response;
+ }
+
+ @Override
+ public boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd) {
+ Long niciraDeviceId = cmd.getNiciraNvpDeviceId();
+ NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraDeviceId);
+ if (niciraNvpDevice == null) {
+ throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId);
+ }
+
+ // Find the physical network we work for
+ Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork != null) {
+ // Lets see if there are networks that use us
+ // Find the nicira networks on this physical network
+ List<NetworkVO> networkList = networkDao.listByPhysicalNetwork(physicalNetworkId);
+ if (networkList != null) {
+ // Networks with broadcast type lswitch are ours
+ for (NetworkVO network : networkList) {
+ if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
+ if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) {
+ throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack.");
+ }
+ }
+ }
+ }
+ }
+
+ HostVO niciraHost = hostDao.findById(niciraNvpDevice.getHostId());
+ Long hostId = niciraHost.getId();
+
+ niciraHost.setResourceState(ResourceState.Maintenance);
+ hostDao.update(hostId, niciraHost);
+ resourceMgr.deleteHost(hostId, false, false);
+
+ niciraNvpDao.remove(niciraDeviceId);
+ return true;
+ }
+
+ @Override
+ public List<NiciraNvpDeviceVO> listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd) {
+ Long physicalNetworkId = cmd.getPhysicalNetworkId();
+ Long niciraNvpDeviceId = cmd.getNiciraNvpDeviceId();
+ List<NiciraNvpDeviceVO> responseList = new ArrayList<NiciraNvpDeviceVO>();
+
+ if (physicalNetworkId == null && niciraNvpDeviceId == null) {
+ throw new InvalidParameterValueException("Either physical network Id or nicira device Id must be specified");
+ }
+
+ if (niciraNvpDeviceId != null) {
+ NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraNvpDeviceId);
+ if (niciraNvpDevice == null) {
+ throw new InvalidParameterValueException("Could not find Nicira Nvp device with id: " + niciraNvpDevice);
+ }
+ responseList.add(niciraNvpDevice);
+ } else {
+ PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId);
+ }
+ responseList = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
+ }
+
+ return responseList;
+ }
+
+ @Override
+ public List<? extends Network> listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd) {
+ Long niciraDeviceId = cmd.getNiciraNvpDeviceId();
+ NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraDeviceId);
+ if (niciraNvpDevice == null) {
+ throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId);
+ }
+
+ // Find the physical network we work for
+ Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ // No such physical network, so no provisioned networks
+ return Collections.emptyList();
+ }
+
+ // Find the nicira networks on this physical network
+ List<NetworkVO> networkList = networkDao.listByPhysicalNetwork(physicalNetworkId);
+ if (networkList == null) {
+ return Collections.emptyList();
+ }
+
+ // Networks with broadcast type lswitch are ours
+ List<NetworkVO> responseList = new ArrayList<NetworkVO>();
+ for (NetworkVO network : networkList) {
+ if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
+ responseList.add(network);
+ }
+ }
+
+ return responseList;
+ }
+
+ @Override
+ public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details, List<String> hostTags) {
+ if (!(startup[0] instanceof StartupNiciraNvpCommand)) {
+ return null;
+ }
+ host.setType(Host.Type.L2Networking);
+ return host;
+ }
+
+ @Override
+ public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
+ if (!(host.getType() == Host.Type.L2Networking)) {
+ return null;
+ }
+ return new DeleteHostAnswer(true);
+ }
+
+ /**
+ * From interface SourceNatServiceProvider
+ */
+ @Override
+ public IpDeployer getIpDeployer(Network network) {
+ return this;
+ }
+
+ /**
+ * From interface IpDeployer
+ *
+ * @param network
+ * @param ipAddress
+ * @param services
+ * @return
+ * @throws ResourceUnavailableException
+ */
+ @Override
+ public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> services) throws ResourceUnavailableException {
+ if (services.contains(Service.SourceNat)) {
+ // Only if we need to provide SourceNat we need to configure the logical router
+ // SourceNat is required for StaticNat and PortForwarding
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+ hostDao.loadDetails(niciraNvpHost);
+
+ NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
+ if (routermapping == null) {
+ s_logger.error("No logical router uuid found for network " + network.getDisplayText());
+ return false;
+ }
+
+ List<String> cidrs = new ArrayList<String>();
+ for (PublicIpAddress ip : ipAddress) {
+ if (ip.getState() == IpAddress.State.Releasing) {
+ // If we are releasing we don't need to push this ip to
+ // the Logical Router
+ continue;
+ }
+ cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask()));
+ }
+ ConfigurePublicIpsOnLogicalRouterCommand cmd =
+ new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs);
+ ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+ //FIXME answer can be null if the host is down
+ return answer.getResult();
+ } else {
+ s_logger.debug("No need to provision ip addresses as we are not providing L3 services.");
+ }
+
+ return true;
+ }
+
+ /**
+ * From interface StaticNatServiceProvider
+ */
+ @Override
+ public boolean applyStaticNats(Network network, List<? extends StaticNat> rules) throws ResourceUnavailableException {
+ if (!canHandle(network, Service.StaticNat)) {
+ return false;
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+
+ NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
+ if (routermapping == null) {
+ s_logger.error("No logical router uuid found for network " + network.getDisplayText());
+ return false;
+ }
+
+ List<StaticNatRuleTO> staticNatRules = new ArrayList<StaticNatRuleTO>();
+ for (StaticNat rule : rules) {
+ IpAddress sourceIp = networkModel.getIp(rule.getSourceIpAddressId());
+ // Force the nat rule into the StaticNatRuleTO, no use making a new TO object
+ // we only need the source and destination ip. Unfortunately no mention if a rule
+ // is new.
+ StaticNatRuleTO ruleTO =
+ new StaticNatRuleTO(1, sourceIp.getAddress().addr(), MIN_PORT, MAX_PORT, rule.getDestIpAddress(), MIN_PORT, MAX_PORT, "any", rule.isForRevoke(), false);
+ staticNatRules.add(ruleTO);
+ }
+
+ ConfigureStaticNatRulesOnLogicalRouterCommand cmd = new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules);
+ ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+
+ return answer.getResult();
+ }
+
+ /**
+ * From interface PortForwardingServiceProvider
+ */
+ @Override
+ public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException {
+ if (!canHandle(network, Service.PortForwarding)) {
+ return false;
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+
+ NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
+ if (routermapping == null) {
+ s_logger.error("No logical router uuid found for network " + network.getDisplayText());
+ return false;
+ }
+
+ List<PortForwardingRuleTO> portForwardingRules = new ArrayList<PortForwardingRuleTO>();
+ for (PortForwardingRule rule : rules) {
+ IpAddress sourceIp = networkModel.getIp(rule.getSourceIpAddressId());
+ Vlan vlan = vlanDao.findById(sourceIp.getVlanId());
+ PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr());
+ portForwardingRules.add(ruleTO);
+ }
+
+ ConfigurePortForwardingRulesOnLogicalRouterCommand cmd =
+ new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules);
+ ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+
+ return answer.getResult();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java
new file mode 100644
index 0000000..dae1a0f
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java
@@ -0,0 +1,45 @@
+//
+// 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 com.cloud.network.element;
+
+import java.util.List;
+
+import com.cloud.api.commands.AddNiciraNvpDeviceCmd;
+import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;
+import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;
+import com.cloud.api.commands.ListNiciraNvpDevicesCmd;
+import com.cloud.api.response.NiciraNvpDeviceResponse;
+import com.cloud.network.Network;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.utils.component.PluggableService;
+
+public interface NiciraNvpElementService extends PluggableService {
+
+ public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd);
+
+ public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(NiciraNvpDeviceVO niciraDeviceVO);
+
+ boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd);
+
+ List<? extends Network> listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd);
+
+ List<NiciraNvpDeviceVO> listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
new file mode 100644
index 0000000..640d8a5
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java
@@ -0,0 +1,256 @@
+//
+// 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 com.cloud.network.guru;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.CreateLogicalSwitchAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchCommand;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.host.dao.HostDetailsDao;
+import com.cloud.network.Network;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network.Service;
+import com.cloud.network.Network.State;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.NetworkProfile;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.NiciraNvpDeviceVO;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetwork.IsolationMethod;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.NiciraNvpDao;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
+import com.cloud.resource.ResourceManager;
+import com.cloud.user.Account;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachineProfile;
+
+@Local(value = NetworkGuru.class)
+public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
+ private static final int MAX_NAME_LENGTH = 40;
+
+ private static final Logger s_logger = Logger.getLogger(NiciraNvpGuestNetworkGuru.class);
+
+ @Inject
+ protected NetworkModel networkModel;
+ @Inject
+ protected NetworkDao networkDao;
+ @Inject
+ protected DataCenterDao zoneDao;
+ @Inject
+ protected PhysicalNetworkDao physicalNetworkDao;
+ @Inject
+ protected AccountDao accountDao;
+ @Inject
+ protected NiciraNvpDao niciraNvpDao;
+ @Inject
+ protected HostDao hostDao;
+ @Inject
+ protected ResourceManager resourceMgr;
+ @Inject
+ protected AgentManager agentMgr;
+ @Inject
+ protected HostDetailsDao hostDetailsDao;
+ @Inject
+ protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao;
+
+ public NiciraNvpGuestNetworkGuru() {
+ super();
+ _isolationMethods = new IsolationMethod[] {IsolationMethod.STT, IsolationMethod.VXLAN};
+ }
+
+ @Override
+ protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
+ // This guru handles only Guest Isolated network that supports Source nat service
+ if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated &&
+ isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) {
+ return true;
+ } else {
+ s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced);
+ return false;
+ }
+ }
+
+ @Override
+ public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final Account owner) {
+ // Check of the isolation type of the related physical network is supported
+ PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId());
+ DataCenter dc = _dcDao.findById(plan.getDataCenterId());
+ if (!canHandle(offering, dc.getNetworkType(), physnet)) {
+ s_logger.debug("Refusing to design this network");
+ return null;
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + physnet.getName());
+ return null;
+ }
+ s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId());
+
+ s_logger.debug("Physical isolation type is supported, asking GuestNetworkGuru to design this network");
+ NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner);
+ if (networkObject == null) {
+ return null;
+ }
+ // Override the broadcast domain type
+ networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch);
+
+ return networkObject;
+ }
+
+ @Override
+ public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context)
+ throws InsufficientVirtualNetworkCapacityException {
+ assert (network.getState() == State.Implementing) : "Why are we implementing " + network;
+
+ long dcId = dest.getDataCenter().getId();
+
+ //get physical network id
+ Long physicalNetworkId = network.getPhysicalNetworkId();
+
+ // physical network id can be null in Guest Network in Basic zone, so locate the physical network
+ if (physicalNetworkId == null) {
+ physicalNetworkId = networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType());
+ }
+
+ NetworkVO implemented =
+ new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated,
+ network.getDataCenterId(), physicalNetworkId, offering.getRedundantRouter());
+
+ if (network.getGateway() != null) {
+ implemented.setGateway(network.getGateway());
+ }
+
+ if (network.getCidr() != null) {
+ implemented.setCidr(network.getCidr());
+ }
+
+ // Name is either the given name or the uuid
+ String name = network.getName();
+ if (name == null || name.isEmpty()) {
+ name = ((NetworkVO)network).getUuid();
+ }
+ if (name.length() > MAX_NAME_LENGTH) {
+ name = name.substring(0, MAX_NAME_LENGTH - 1); // max length 40
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + physicalNetworkId);
+ return null;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+ hostDao.loadDetails(niciraNvpHost);
+ String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid");
+ String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype");
+
+ CreateLogicalSwitchCommand cmd =
+ new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-" + context.getAccount().getAccountName());
+ CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("CreateLogicalSwitchCommand failed");
+ return null;
+ }
+
+ try {
+ implemented.setBroadcastUri(new URI("lswitch", answer.getLogicalSwitchUuid(), null));
+ implemented.setBroadcastDomainType(BroadcastDomainType.Lswitch);
+ s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString());
+ } catch (URISyntaxException e) {
+ s_logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e);
+ return null;
+ }
+
+ return implemented;
+ }
+
+ @Override
+ public void reserve(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context)
+ throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
+ // TODO Auto-generated method stub
+ super.reserve(nic, network, vm, dest, context);
+ }
+
+ @Override
+ public boolean release(final NicProfile nic, final VirtualMachineProfile vm, final String reservationId) {
+ // TODO Auto-generated method stub
+ return super.release(nic, vm, reservationId);
+ }
+
+ @Override
+ public void shutdown(final NetworkProfile profile, final NetworkOffering offering) {
+ NetworkVO networkObject = networkDao.findById(profile.getId());
+ if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch || networkObject.getBroadcastUri() == null) {
+ s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText());
+ return;
+ }
+
+ List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId());
+ return;
+ }
+ NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
+ HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
+
+ DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
+ DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("DeleteLogicalSwitchCommand failed");
+ }
+
+ super.shutdown(profile, offering);
+ }
+
+ @Override
+ public boolean trash(final Network network, final NetworkOffering offering) {
+ return super.trash(network, offering);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java
new file mode 100644
index 0000000..b5291dc
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.nicira;
+
+import java.util.List;
+
+public abstract class AccessConfiguration<T extends AccessRule> extends BaseNiciraNamedEntity {
+
+ protected List<T> logicalPortEgressRules;
+ protected List<T> logicalPortIngressRules;
+
+ public List<T> getLogicalPortEgressRules() {
+ return logicalPortEgressRules;
+ }
+
+ public void setLogicalPortEgressRules(final List<T> logicalPortEgressRules) {
+ this.logicalPortEgressRules = logicalPortEgressRules;
+ }
+
+ public List<T> getLogicalPortIngressRules() {
+ return logicalPortIngressRules;
+ }
+
+ public void setLogicalPortIngressRules(final List<T> logicalPortIngressRules) {
+ this.logicalPortIngressRules = logicalPortIngressRules;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java
new file mode 100644
index 0000000..e614db6
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.network.nicira;
+
+import java.io.Serializable;
+
+import org.apache.commons.lang.builder.ReflectionToStringBuilder;
+import org.apache.commons.lang.builder.ToStringStyle;
+
+@SuppressWarnings("serial")
+public abstract class AccessRule implements Serializable {
+
+ public static final String ETHERTYPE_IPV4 = "IPv4";
+ public static final String ETHERTYPE_IPV6 = "IPv6";
+
+ protected String ethertype = ETHERTYPE_IPV4;
+
+ protected int protocol;
+
+
+ public String getEthertype() {
+ return ethertype;
+ }
+
+ public void setEthertype(String ethertype) {
+ this.ethertype = ethertype;
+ }
+
+ public int getProtocol() {
+ return protocol;
+ }
+
+ public void setProtocol(int protocol) {
+ this.protocol = protocol;
+ }
+
+ @Override
+ public String toString() {
+ return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java
new file mode 100644
index 0000000..870124e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java
@@ -0,0 +1,23 @@
+//
+// 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 com.cloud.network.nicira;
+
+public class Acl extends AccessConfiguration<AclRule> {
+}
[27/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/UriUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/UriUtils.java b/utils/src/com/cloud/utils/UriUtils.java
deleted file mode 100644
index 631c629..0000000
--- a/utils/src/com/cloud/utils/UriUtils.java
+++ /dev/null
@@ -1,394 +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 com.cloud.utils;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URLEncoder;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.StringTokenizer;
-
-import javax.net.ssl.HttpsURLConnection;
-
-import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
-import org.apache.commons.httpclient.UsernamePasswordCredentials;
-import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.HeadMethod;
-import org.apache.commons.httpclient.util.URIUtil;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.utils.URIBuilder;
-import org.apache.http.client.utils.URLEncodedUtils;
-
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.crypt.DBEncryptionUtil;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class UriUtils {
-
- public static final Logger s_logger = Logger.getLogger(UriUtils.class.getName());
-
- public static String formNfsUri(String host, String path) {
- try {
- URI uri = new URI("nfs", host, path, null);
- return uri.toString();
- } catch (URISyntaxException e) {
- throw new CloudRuntimeException("Unable to form nfs URI: " + host + " - " + path);
- }
- }
-
- public static String formIscsiUri(String host, String iqn, Integer lun) {
- try {
- String path = iqn;
- if (lun != null) {
- path += "/" + lun.toString();
- }
- URI uri = new URI("iscsi", host, path, null);
- return uri.toString();
- } catch (URISyntaxException e) {
- throw new CloudRuntimeException("Unable to form iscsi URI: " + host + " - " + iqn + " - " + lun);
- }
- }
-
- public static String formFileUri(String path) {
- File file = new File(path);
-
- return file.toURI().toString();
- }
-
- // a simple URI component helper (Note: it does not deal with URI paramemeter area)
- public static String encodeURIComponent(String url) {
- int schemeTail = url.indexOf("://");
-
- int pathStart = 0;
- if (schemeTail > 0)
- pathStart = url.indexOf('/', schemeTail + 3);
- else
- pathStart = url.indexOf('/');
-
- if (pathStart > 0) {
- String[] tokens = url.substring(pathStart + 1).split("/");
- StringBuilder sb = new StringBuilder(url.substring(0, pathStart));
- for (String token : tokens) {
- sb.append("/").append(URLEncoder.encode(token));
- }
-
- return sb.toString();
- }
-
- // no need to do URL component encoding
- return url;
- }
-
- public static String getCifsUriParametersProblems(URI uri) {
- if (!UriUtils.hostAndPathPresent(uri)) {
- String errMsg = "cifs URI missing host and/or path. Make sure it's of the format cifs://hostname/path";
- s_logger.warn(errMsg);
- return errMsg;
- }
- return null;
- }
-
- public static boolean hostAndPathPresent(URI uri) {
- return !(uri.getHost() == null || uri.getHost().trim().isEmpty() || uri.getPath() == null || uri.getPath().trim().isEmpty());
- }
-
- public static boolean cifsCredentialsPresent(URI uri) {
- List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
- boolean foundUser = false;
- boolean foundPswd = false;
- for (NameValuePair nvp : args) {
- String name = nvp.getName();
- if (name.equals("user")) {
- foundUser = true;
- s_logger.debug("foundUser is" + foundUser);
- } else if (name.equals("password")) {
- foundPswd = true;
- s_logger.debug("foundPswd is" + foundPswd);
- }
- }
- return (foundUser && foundPswd);
- }
-
- public static String getUpdateUri(String url, boolean encrypt) {
- String updatedPath = null;
- try {
- String query = URIUtil.getQuery(url);
- URIBuilder builder = new URIBuilder(url);
- builder.removeQuery();
-
- StringBuilder updatedQuery = new StringBuilder();
- List<NameValuePair> queryParams = getUserDetails(query);
- ListIterator<NameValuePair> iterator = queryParams.listIterator();
- while (iterator.hasNext()) {
- NameValuePair param = iterator.next();
- String value = null;
- if ("password".equalsIgnoreCase(param.getName()) &&
- param.getValue() != null) {
- value = encrypt ? DBEncryptionUtil.encrypt(param.getValue()) : DBEncryptionUtil.decrypt(param.getValue());
- } else {
- value = param.getValue();
- }
-
- if (updatedQuery.length() == 0) {
- updatedQuery.append(param.getName()).append('=')
- .append(value);
- } else {
- updatedQuery.append('&').append(param.getName())
- .append('=').append(value);
- }
- }
-
- String schemeAndHost = "";
- URI newUri = builder.build();
- if (newUri.getScheme() != null) {
- schemeAndHost = newUri.getScheme() + "://" + newUri.getHost();
- }
-
- updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery;
- } catch (URISyntaxException e) {
- throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage());
- }
-
- return updatedPath;
- }
-
- private static List<NameValuePair> getUserDetails(String query) {
- List<NameValuePair> details = new ArrayList<NameValuePair>();
- if (query != null && !query.isEmpty()) {
- StringTokenizer allParams = new StringTokenizer(query, "&");
- while (allParams.hasMoreTokens()) {
- String param = allParams.nextToken();
- details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")),
- param.substring(param.indexOf("=") + 1)));
- }
- }
-
- return details;
- }
-
- // Get the size of a file from URL response header.
- public static Long getRemoteSize(String url) {
- Long remoteSize = (long)0;
- HttpURLConnection httpConn = null;
- HttpsURLConnection httpsConn = null;
- try {
- URI uri = new URI(url);
- if (uri.getScheme().equalsIgnoreCase("http")) {
- httpConn = (HttpURLConnection)uri.toURL().openConnection();
- if (httpConn != null) {
- httpConn.setConnectTimeout(2000);
- httpConn.setReadTimeout(5000);
- String contentLength = httpConn.getHeaderField("content-length");
- if (contentLength != null) {
- remoteSize = Long.parseLong(contentLength);
- }
- httpConn.disconnect();
- }
- } else if (uri.getScheme().equalsIgnoreCase("https")) {
- httpsConn = (HttpsURLConnection)uri.toURL().openConnection();
- if (httpsConn != null) {
- String contentLength = httpsConn.getHeaderField("content-length");
- if (contentLength != null) {
- remoteSize = Long.parseLong(contentLength);
- }
- httpsConn.disconnect();
- }
- }
- } catch (URISyntaxException e) {
- throw new IllegalArgumentException("Invalid URL " + url);
- } catch (IOException e) {
- throw new IllegalArgumentException("Unable to establish connection with URL " + url);
- }
- return remoteSize;
- }
-
- public static Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
- return validateUrl(null, url);
- }
-
- public static Pair<String, Integer> validateUrl(String format, String url) throws IllegalArgumentException {
- try {
- URI uri = new URI(url);
- if ((uri.getScheme() == null) ||
- (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) {
- throw new IllegalArgumentException("Unsupported scheme for url: " + url);
- }
- int port = uri.getPort();
- if (!(port == 80 || port == 8080 || port == 443 || port == -1)) {
- throw new IllegalArgumentException("Only ports 80, 8080 and 443 are allowed");
- }
-
- if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
- port = 443;
- } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
- port = 80;
- }
-
- String host = uri.getHost();
- try {
- InetAddress hostAddr = InetAddress.getByName(host);
- if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) {
- throw new IllegalArgumentException("Illegal host specified in url");
- }
- if (hostAddr instanceof Inet6Address) {
- throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
- }
- } catch (UnknownHostException uhe) {
- throw new IllegalArgumentException("Unable to resolve " + host);
- }
-
- // verify format
- if (format != null) {
- String uripath = uri.getPath();
- checkFormat(format, uripath);
- }
- return new Pair<String, Integer>(host, port);
- } catch (URISyntaxException use) {
- throw new IllegalArgumentException("Invalid URL: " + url);
- }
- }
-
- // use http HEAD method to validate url
- public static void checkUrlExistence(String url) {
- if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) {
- HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
- HeadMethod httphead = new HeadMethod(url);
- try {
- if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) {
- throw new IllegalArgumentException("Invalid URL: " + url);
- }
- } catch (HttpException hte) {
- throw new IllegalArgumentException("Cannot reach URL: " + url);
- } catch (IOException ioe) {
- throw new IllegalArgumentException("Cannot reach URL: " + url);
- }
- }
- }
-
- // verify if a URI path is compliance with the file format given
- private static void checkFormat(String format, String uripath) {
- if ((!uripath.toLowerCase().endsWith("vhd")) && (!uripath.toLowerCase().endsWith("vhd.zip")) && (!uripath.toLowerCase().endsWith("vhd.bz2")) &&
- (!uripath.toLowerCase().endsWith("vhdx")) && (!uripath.toLowerCase().endsWith("vhdx.gz")) &&
- (!uripath.toLowerCase().endsWith("vhdx.bz2")) && (!uripath.toLowerCase().endsWith("vhdx.zip")) &&
- (!uripath.toLowerCase().endsWith("vhd.gz")) && (!uripath.toLowerCase().endsWith("qcow2")) && (!uripath.toLowerCase().endsWith("qcow2.zip")) &&
- (!uripath.toLowerCase().endsWith("qcow2.bz2")) && (!uripath.toLowerCase().endsWith("qcow2.gz")) && (!uripath.toLowerCase().endsWith("ova")) &&
- (!uripath.toLowerCase().endsWith("ova.zip")) && (!uripath.toLowerCase().endsWith("ova.bz2")) && (!uripath.toLowerCase().endsWith("ova.gz")) &&
- (!uripath.toLowerCase().endsWith("tar")) && (!uripath.toLowerCase().endsWith("tar.zip")) && (!uripath.toLowerCase().endsWith("tar.bz2")) &&
- (!uripath.toLowerCase().endsWith("tar.gz")) && (!uripath.toLowerCase().endsWith("vmdk")) && (!uripath.toLowerCase().endsWith("vmdk.gz")) &&
- (!uripath.toLowerCase().endsWith("vmdk.zip")) && (!uripath.toLowerCase().endsWith("vmdk.bz2")) && (!uripath.toLowerCase().endsWith("img")) &&
- (!uripath.toLowerCase().endsWith("img.gz")) && (!uripath.toLowerCase().endsWith("img.zip")) && (!uripath.toLowerCase().endsWith("img.bz2")) &&
- (!uripath.toLowerCase().endsWith("raw")) && (!uripath.toLowerCase().endsWith("raw.gz")) && (!uripath.toLowerCase().endsWith("raw.bz2")) &&
- (!uripath.toLowerCase().endsWith("raw.zip")) && (!uripath.toLowerCase().endsWith("iso")) && (!uripath.toLowerCase().endsWith("iso.zip"))
- && (!uripath.toLowerCase().endsWith("iso.bz2")) && (!uripath.toLowerCase().endsWith("iso.gz"))) {
- throw new IllegalArgumentException("Please specify a valid " + format.toLowerCase());
- }
-
- if ((format.equalsIgnoreCase("vhd")
- && (!uripath.toLowerCase().endsWith("vhd")
- && !uripath.toLowerCase().endsWith("vhd.zip")
- && !uripath.toLowerCase().endsWith("vhd.bz2")
- && !uripath.toLowerCase().endsWith("vhd.gz")))
- || (format.equalsIgnoreCase("vhdx")
- && (!uripath.toLowerCase().endsWith("vhdx")
- && !uripath.toLowerCase().endsWith("vhdx.zip")
- && !uripath.toLowerCase().endsWith("vhdx.bz2")
- && !uripath.toLowerCase().endsWith("vhdx.gz")))
- || (format.equalsIgnoreCase("qcow2")
- && (!uripath.toLowerCase().endsWith("qcow2")
- && !uripath.toLowerCase().endsWith("qcow2.zip")
- && !uripath.toLowerCase().endsWith("qcow2.bz2")
- && !uripath.toLowerCase().endsWith("qcow2.gz")))
- || (format.equalsIgnoreCase("ova")
- && (!uripath.toLowerCase().endsWith("ova")
- && !uripath.toLowerCase().endsWith("ova.zip")
- && !uripath.toLowerCase().endsWith("ova.bz2")
- && !uripath.toLowerCase().endsWith("ova.gz")))
- || (format.equalsIgnoreCase("tar")
- && (!uripath.toLowerCase().endsWith("tar")
- && !uripath.toLowerCase().endsWith("tar.zip")
- && !uripath.toLowerCase().endsWith("tar.bz2")
- && !uripath.toLowerCase().endsWith("tar.gz")))
- || (format.equalsIgnoreCase("raw")
- && (!uripath.toLowerCase().endsWith("img")
- && !uripath.toLowerCase().endsWith("img.zip")
- && !uripath.toLowerCase().endsWith("img.bz2")
- && !uripath.toLowerCase().endsWith("img.gz")
- && !uripath.toLowerCase().endsWith("raw")
- && !uripath.toLowerCase().endsWith("raw.bz2")
- && !uripath.toLowerCase().endsWith("raw.zip")
- && !uripath.toLowerCase().endsWith("raw.gz")))
- || (format.equalsIgnoreCase("vmdk")
- && (!uripath.toLowerCase().endsWith("vmdk")
- && !uripath.toLowerCase().endsWith("vmdk.zip")
- && !uripath.toLowerCase().endsWith("vmdk.bz2")
- && !uripath.toLowerCase().endsWith("vmdk.gz")))
- || (format.equalsIgnoreCase("iso")
- && (!uripath.toLowerCase().endsWith("iso")
- && !uripath.toLowerCase().endsWith("iso.zip")
- && !uripath.toLowerCase().endsWith("iso.bz2")
- && !uripath.toLowerCase().endsWith("iso.gz")))) {
- throw new IllegalArgumentException("Please specify a valid URL. URL:" + uripath + " is an invalid for the format " + format.toLowerCase());
- }
-
- }
-
- public static InputStream getInputStreamFromUrl(String url, String user, String password) {
-
- try {
- Pair<String, Integer> hostAndPort = validateUrl(url);
- HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
- if ((user != null) && (password != null)) {
- httpclient.getParams().setAuthenticationPreemptive(true);
- Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
- httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
- s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
- }
- // Execute the method.
- GetMethod method = new GetMethod(url);
- int statusCode = httpclient.executeMethod(method);
-
- if (statusCode != HttpStatus.SC_OK) {
- s_logger.error("Failed to read from URL: " + url);
- return null;
- }
-
- return method.getResponseBodyAsStream();
- } catch (Exception ex) {
- s_logger.error("Failed to read from URL: " + url);
- return null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/UsernamePasswordValidator.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/UsernamePasswordValidator.java b/utils/src/com/cloud/utils/UsernamePasswordValidator.java
deleted file mode 100644
index f11186c..0000000
--- a/utils/src/com/cloud/utils/UsernamePasswordValidator.java
+++ /dev/null
@@ -1,49 +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 com.cloud.utils;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class UsernamePasswordValidator {
- private Pattern usernamePattern;
- private Pattern passwordPattern;
- private Matcher matcher;
-
- private static final String USERNAME_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$";
- private static final String PASSWORD_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$";
-
- public UsernamePasswordValidator() {
- usernamePattern = Pattern.compile(USERNAME_PATTERN);
- passwordPattern = Pattern.compile(PASSWORD_PATTERN);
-
- }
-
- public boolean validateUsername(final String username) {
- matcher = usernamePattern.matcher(username);
- return matcher.matches();
- }
-
- public boolean validatePassword(final String password) {
- matcher = passwordPattern.matcher(password);
- return matcher.matches();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/UuidUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/UuidUtils.java b/utils/src/com/cloud/utils/UuidUtils.java
deleted file mode 100644
index 9c4a756..0000000
--- a/utils/src/com/cloud/utils/UuidUtils.java
+++ /dev/null
@@ -1,34 +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 com.cloud.utils;
-
-import org.apache.xerces.impl.xpath.regex.RegularExpression;
-
-public class UuidUtils {
-
- public final static String first(String uuid) {
- return uuid.substring(0, uuid.indexOf('-'));
- }
-
- public static boolean validateUUID(String uuid) {
- RegularExpression regex = new RegularExpression("[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}");
- return regex.matches(uuid);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java b/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java
deleted file mode 100644
index b8f3f00..0000000
--- a/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java
+++ /dev/null
@@ -1,38 +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 com.cloud.utils.backoff;
-
-import com.cloud.utils.component.Adapter;
-
-/**
- * BackoffAlgorithm implements multiple BackoffAlgorithm.
- */
-public interface BackoffAlgorithm extends Adapter {
-
- /**
- */
- void waitBeforeRetry();
-
- /**
- * no longer need to backoff. reset to beginning.
- */
- void reset();
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java b/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java
deleted file mode 100644
index 14eae16..0000000
--- a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java
+++ /dev/null
@@ -1,102 +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 com.cloud.utils.backoff.impl;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.ejb.Local;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.cloud.utils.NumbersUtil;
-import com.cloud.utils.backoff.BackoffAlgorithm;
-import com.cloud.utils.component.AdapterBase;
-
-/**
- * An implementation of BackoffAlgorithm that waits for some seconds.
- * After the time the client can try to perform the operation again.
- *
- * @config
- * {@table
- * || Param Name | Description | Values | Default ||
- * || seconds | seconds to sleep | integer | 5 ||
- * }
- **/
-@Local(value = {BackoffAlgorithm.class})
-public class ConstantTimeBackoff extends AdapterBase implements BackoffAlgorithm, ConstantTimeBackoffMBean {
- long _time;
- private final Map<String, Thread> _asleep = new ConcurrentHashMap<String, Thread>();
- private final static Log LOG = LogFactory.getLog(ConstantTimeBackoff.class);
-
- @Override
- public void waitBeforeRetry() {
- Thread current = Thread.currentThread();
- try {
- _asleep.put(current.getName(), current);
- Thread.sleep(_time);
- } catch (InterruptedException e) {
- // JMX or other threads may interrupt this thread, but let's log it
- // anyway, no exception to log as this is not an error
- LOG.info("Thread " + current.getName() + " interrupted while waiting for retry");
- } finally {
- _asleep.remove(current.getName());
- }
- return;
- }
-
- @Override
- public void reset() {
- }
-
- @Override
- public boolean configure(String name, Map<String, Object> params) {
- _time = NumbersUtil.parseLong((String)params.get("seconds"), 5) * 1000;
- return true;
- }
-
- @Override
- public Collection<String> getWaiters() {
- return _asleep.keySet();
- }
-
- @Override
- public boolean wakeup(String threadName) {
- Thread th = _asleep.get(threadName);
- if (th != null) {
- th.interrupt();
- return true;
- }
-
- return false;
- }
-
- @Override
- public long getTimeToWait() {
- return _time;
- }
-
- @Override
- public void setTimeToWait(long seconds) {
- _time = seconds * 1000;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java b/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java
deleted file mode 100644
index 4dc9f9c..0000000
--- a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java
+++ /dev/null
@@ -1,35 +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 com.cloud.utils.backoff.impl;
-
-import java.util.Collection;
-
-import com.cloud.utils.mgmt.ManagementBean;
-
-public interface ConstantTimeBackoffMBean extends ManagementBean {
- public long getTimeToWait();
-
- public void setTimeToWait(long seconds);
-
- Collection<String> getWaiters();
-
- boolean wakeup(String threadName);
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
deleted file mode 100644
index a6d905d..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
+++ /dev/null
@@ -1,355 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-
-import org.apache.log4j.Logger;
-
-import com.trilead.ssh2.Connection;
-import com.trilead.ssh2.Session;
-
-import com.cloud.utils.Pair;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.ssh.SSHCmdHelper;
-
-public class NetconfHelper {
- private static final Logger s_logger = Logger.getLogger(NetconfHelper.class);
-
- private static final String SSH_NETCONF_TERMINATOR = "]]>]]>";
-
- private Connection _connection;
-
- private Session _session;
-
- public NetconfHelper(String ip, String username, String password) throws CloudRuntimeException {
- _connection = SSHCmdHelper.acquireAuthorizedConnection(ip, username, password);
- if (_connection == null) {
- throw new CloudRuntimeException("Error opening ssh connection.");
- }
-
- try {
- _session = _connection.openSession();
- _session.startSubSystem("xmlagent");
- exchangeHello();
- } catch (final Exception e) {
- disconnect();
- s_logger.error("Failed to connect to device SSH server: " + e.getMessage());
- throw new CloudRuntimeException("Failed to connect to SSH server: " + _connection.getHostname());
- }
- }
-
- public void disconnect() {
- if (_session != null) {
- _session.close();
- }
- SSHCmdHelper.releaseSshConnection(_connection);
- }
-
- public void queryStatus() throws CloudRuntimeException {
- // This command is used to query the server status.
- String status =
- "<?xml version=\"1.0\"?>" + "<nc:rpc message-id=\"1\" xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0" + "\"xmlns=\"http://www.cisco.com/nxos:1.0:xml\">" +
- " <nc:get>" + " <nc:filter type=\"subtree\">" + " <show>" + " <xml>" + " <server>" + " <status/>" +
- " </server>" + " </xml>" + " </show>" + " </nc:filter>" + " </nc:get>" + "</nc:rpc>" + SSH_NETCONF_TERMINATOR;
- send(status);
- // parse the rpc reply.
- parseOkReply(receive());
- }
-
- public void addPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName)
- throws CloudRuntimeException {
- String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid, vdc, espName);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for adding port profile.");
- }
- }
-
- public void addPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) throws CloudRuntimeException {
- String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for adding port profile.");
- }
- }
-
- public void updatePortProfile(String name, SwitchPortMode mode, List<Pair<VsmCommand.OperationType, String>> params) throws CloudRuntimeException {
- String command = VsmCommand.getUpdatePortProfile(name, mode, params);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for updating port profile.");
- }
- }
-
- public void deletePortProfile(String name) throws CloudRuntimeException {
- String command = VsmCommand.getDeletePortProfile(name);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for deleting port profile.");
- }
- }
-
- public void addPolicyMap(String name, int averageRate, int maxRate, int burstRate) throws CloudRuntimeException {
- String command = VsmCommand.getAddPolicyMap(name, averageRate, maxRate, burstRate);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for adding/updating policy map.");
- }
- }
-
- public void deletePolicyMap(String name) throws CloudRuntimeException {
- String command = VsmCommand.getDeletePolicyMap(name);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for deleting policy map.");
- }
- }
-
- public void updatePolicyMap(String name, int averageRate, int maxRate, int burstRate) throws CloudRuntimeException {
- // Add and update of policy map work in the exact same way.
- addPolicyMap(name, averageRate, maxRate, burstRate);
- }
-
- public void attachServicePolicy(String policyMap, String portProfile) throws CloudRuntimeException {
- String command = VsmCommand.getServicePolicy(policyMap, portProfile, true);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for adding policy map.");
- }
- }
-
- public void detachServicePolicy(String policyMap, String portProfile) throws CloudRuntimeException {
- String command = VsmCommand.getServicePolicy(policyMap, portProfile, false);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for removing policy map.");
- }
- }
-
- public void addVServiceNode(String vlanId, String ipAddr) throws CloudRuntimeException {
- String command = VsmCommand.getVServiceNode(vlanId, ipAddr);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- parseOkReply(sendAndReceive(command));
- } else {
- throw new CloudRuntimeException("Error generating rpc request for adding vservice node for vlan " + vlanId);
- }
- }
-
- public PortProfile getPortProfileByName(String name) throws CloudRuntimeException {
- String command = VsmCommand.getPortProfile(name);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- String received = sendAndReceive(command);
- VsmPortProfileResponse response = new VsmPortProfileResponse(received.trim());
- if (!response.isResponseOk()) {
- throw new CloudRuntimeException(response.toString());
- } else {
- return response.getPortProfile();
- }
- } else {
- throw new CloudRuntimeException("Error generating rpc request for getting port profile.");
- }
- }
-
- public PolicyMap getPolicyMapByName(String name) throws CloudRuntimeException {
- String command = VsmCommand.getPolicyMap(name);
- if (command != null) {
- command = command.concat(SSH_NETCONF_TERMINATOR);
- String received = sendAndReceive(command);
- VsmPolicyMapResponse response = new VsmPolicyMapResponse(received.trim());
- if (!response.isResponseOk()) {
- throw new CloudRuntimeException(response.toString());
- } else {
- return response.getPolicyMap();
- }
- } else {
- throw new CloudRuntimeException("Error generating rpc request for getting policy map.");
- }
- }
-
- private void exchangeHello() {
- String ack = receive();
- String hello = VsmCommand.getHello() + SSH_NETCONF_TERMINATOR;
- send(hello);
- }
-
- private String sendAndReceive(String command) {
- String received;
- synchronized (NetconfHelper.class) {
- send(command);
- received = receive();
- }
- return received;
- }
-
- private void send(String message) {
- try {
- OutputStream outputStream = _session.getStdin();
- outputStream.write(message.getBytes());
- outputStream.flush();
- } catch (Exception e) {
- s_logger.error("Failed to send message: " + e.getMessage());
- throw new CloudRuntimeException("Failed to send message: " + e.getMessage());
- }
- }
-
- private String receive() {
- String response = new String("");
- InputStream inputStream = _session.getStdout();
-
- try {
- Delimiter delimiter = new Delimiter();
- byte[] buffer = new byte[1024];
- int count = 0;
-
- // Read the input stream till we find the end sequence ']]>]]>'.
- while (true) {
- int data = inputStream.read();
- if (data != -1) {
- byte[] dataStream = delimiter.parse(data);
- if (delimiter.endReached()) {
- response += new String(buffer, 0, count);
- break;
- }
-
- if (dataStream != null) {
- for (int i = 0; i < dataStream.length; i++) {
- buffer[count] = dataStream[i];
- count++;
- if (count == 1024) {
- response += new String(buffer, 0, count);
- count = 0;
- }
- }
- }
- } else {
- break;
- }
- }
- } catch (final Exception e) {
- throw new CloudRuntimeException("Error occured while reading from the stream: " + e.getMessage());
- }
-
- return response;
- }
-
- private void parseOkReply(String reply) throws CloudRuntimeException {
- VsmOkResponse response = new VsmOkResponse(reply.trim());
- if (!response.isResponseOk()) {
- throw new CloudRuntimeException(response.toString());
- }
- }
-
- private static class Delimiter {
- private boolean _endReached = false;
-
- // Used to accumulate response read while searching for end of response.
- private byte[] _gatherResponse = new byte[6];
-
- // Index into number of bytes read.
- private int _offset = 0;
-
- // True if ']]>]]>' detected.
- boolean endReached() {
- return _endReached;
- }
-
- // Parses the input stream and checks if end sequence is reached.
- byte[] parse(int input) throws RuntimeException {
- boolean collect = false;
- byte[] streamRead = null;
-
- // Check if end sequence matched.
- switch (_offset) {
- case 0:
- if (input == ']') {
- collect = true;
- }
- break;
- case 1:
- if (input == ']') {
- collect = true;
- }
- break;
- case 2:
- if (input == '>') {
- collect = true;
- }
- break;
- case 3:
- if (input == ']') {
- collect = true;
- }
- break;
- case 4:
- if (input == ']') {
- collect = true;
- }
- break;
- case 5:
- if (input == '>') {
- collect = true;
- _endReached = true;
- }
- break;
- default:
- throw new RuntimeException("Invalid index value: " + _offset);
- }
-
- if (collect) {
- _gatherResponse[_offset++] = (byte)input;
- } else {
- // End sequence not yet reached. Return the stream of bytes collected so far.
- streamRead = new byte[_offset + 1];
- for (int index = 0; index < _offset; ++index) {
- streamRead[index] = _gatherResponse[index];
- }
-
- streamRead[_offset] = (byte)input;
- _offset = 0;
- }
-
- return streamRead;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java
deleted file mode 100644
index 01605d7..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java
+++ /dev/null
@@ -1,34 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-public class PolicyMap {
- public String policyMapName;
- public int committedRate;
- public int burstRate;
- public int peakRate;
-
- PolicyMap() {
- policyMapName = null;
- committedRate = 0;
- burstRate = 0;
- peakRate = 0;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java
deleted file mode 100644
index 53d9728..0000000
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java
+++ /dev/null
@@ -1,48 +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 com.cloud.utils.cisco.n1kv.vsm;
-
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
-import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
-
-public class PortProfile {
- public PortProfileType type;
- public SwitchPortMode mode;
- public BindingType binding;
- public String profileName;
- public String inputPolicyMap;
- public String outputPolicyMap;
- public String vlan;
- public boolean status;
- public int maxPorts;
-
- PortProfile() {
- profileName = null;
- inputPolicyMap = null;
- outputPolicyMap = null;
- vlan = null;
- status = false;
- maxPorts = 32;
- type = PortProfileType.none;
- mode = SwitchPortMode.none;
- binding = BindingType.none;
- }
-}
[03/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
Merge pull request #734 from remibergsma/git-pr-errormsg
Git PR merge script improvementsProcessed feedback from @bhaisaab and (a colleague of) @karuturi
- make the help message better (I also updated Confluence)
- make sure we can use it on other repo's as well (Documentation and such)
Tested it and works fine for me.
* pr/734:
fixed hardcoded merge message location
fix bug where the countdown would be on multiple lines
make it work with any Apache repository mirrored on GitHub
Improve error/help message in case of missing git remote
Signed-off-by: Remi Bergsma <gi...@remi.nl>
Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/a527d272
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/a527d272
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/a527d272
Branch: refs/heads/deploy-from-snapshot
Commit: a527d27299379aefefb96aeb30c2dd4423877b1f
Parents: 82df5b1 1e6df1b
Author: Remi Bergsma <gi...@remi.nl>
Authored: Mon Aug 24 22:15:36 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Mon Aug 24 22:15:36 2015 +0200
----------------------------------------------------------------------
tools/git/git-pr | 27 ++++++++++++++++++++-------
1 file changed, 20 insertions(+), 7 deletions(-)
----------------------------------------------------------------------
[15/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/net/NetUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/net/NetUtils.java b/utils/src/main/java/com/cloud/utils/net/NetUtils.java
new file mode 100644
index 0000000..883129b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/net/NetUtils.java
@@ -0,0 +1,1550 @@
+//
+// 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 com.cloud.utils.net;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.InterfaceAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Formatter;
+import java.util.List;
+import java.util.Random;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang.SystemUtils;
+import org.apache.commons.net.util.SubnetUtils;
+import org.apache.commons.validator.routines.InetAddressValidator;
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.IteratorUtil;
+import com.cloud.utils.Pair;
+import com.cloud.utils.script.Script;
+import com.googlecode.ipv6.IPv6Address;
+import com.googlecode.ipv6.IPv6AddressRange;
+import com.googlecode.ipv6.IPv6Network;
+
+public class NetUtils {
+ protected final static Logger s_logger = Logger.getLogger(NetUtils.class);
+
+ private static final int MAX_CIDR = 32;
+ private static final int RFC_3021_31_BIT_CIDR = 31;
+
+ public final static String HTTP_PORT = "80";
+ public final static String HTTPS_PORT = "443";
+ public final static int VPN_PORT = 500;
+ public final static int VPN_NATT_PORT = 4500;
+ public final static int VPN_L2TP_PORT = 1701;
+ public final static int HAPROXY_STATS_PORT = 8081;
+
+ public final static String UDP_PROTO = "udp";
+ public final static String TCP_PROTO = "tcp";
+ public final static String ANY_PROTO = "any";
+ public final static String ICMP_PROTO = "icmp";
+ public final static String ALL_PROTO = "all";
+ public final static String HTTP_PROTO = "http";
+ public final static String SSL_PROTO = "ssl";
+
+ public final static String ALL_CIDRS = "0.0.0.0/0";
+ public final static int PORT_RANGE_MIN = 0;
+ public final static int PORT_RANGE_MAX = 65535;
+
+ public final static int DEFAULT_AUTOSCALE_VM_DESTROY_TIME = 2 * 60; // Grace period before Vm is destroyed
+ public final static int DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME = 30;
+ public final static int DEFAULT_AUTOSCALE_POLICY_QUIET_TIME = 5 * 60;
+ private final static Random s_rand = new Random(System.currentTimeMillis());
+
+ public static long createSequenceBasedMacAddress(final long macAddress) {
+ return macAddress | 0x060000000000l | (long)s_rand.nextInt(32768) << 25 & 0x00fffe000000l;
+ }
+
+ public static String getHostName() {
+ try {
+ final InetAddress localAddr = InetAddress.getLocalHost();
+ if (localAddr != null) {
+ return localAddr.getHostName();
+ }
+ } catch (final UnknownHostException e) {
+ s_logger.warn("UnknownHostException when trying to get host name. ", e);
+ }
+ return "localhost";
+ }
+
+ public static InetAddress getLocalInetAddress() {
+ try {
+ return InetAddress.getLocalHost();
+ } catch (final UnknownHostException e) {
+ s_logger.warn("UnknownHostException in getLocalInetAddress().", e);
+ return null;
+ }
+ }
+
+ public static String resolveToIp(final String host) {
+ try {
+ final InetAddress addr = InetAddress.getByName(host);
+ return ipFromInetAddress(addr);
+ } catch (final UnknownHostException e) {
+ s_logger.warn("Unable to resolve " + host + " to IP due to UnknownHostException");
+ return null;
+ }
+ }
+
+ public static InetAddress[] getAllLocalInetAddresses() {
+ final List<InetAddress> addrList = new ArrayList<InetAddress>();
+ try {
+ for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
+ if (ifc.isUp() && !ifc.isVirtual()) {
+ for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
+ addrList.add(addr);
+ }
+ }
+ }
+ } catch (final SocketException e) {
+ s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
+ }
+
+ final InetAddress[] addrs = new InetAddress[addrList.size()];
+ if (addrList.size() > 0) {
+ System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
+ }
+ return addrs;
+ }
+
+ public static String[] getLocalCidrs() {
+ final String defaultHostIp = getDefaultHostIp();
+
+ final List<String> cidrList = new ArrayList<String>();
+ try {
+ for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
+ if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
+ for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
+ final InetAddress addr = address.getAddress();
+ final int prefixLength = address.getNetworkPrefixLength();
+ if (prefixLength < MAX_CIDR && prefixLength > 0) {
+ final String ip = ipFromInetAddress(addr);
+ if (ip.equalsIgnoreCase(defaultHostIp)) {
+ cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
+ }
+ }
+ }
+ }
+ }
+ } catch (final SocketException e) {
+ s_logger.warn("UnknownHostException in getLocalCidrs().", e);
+ }
+
+ return cidrList.toArray(new String[0]);
+ }
+
+ public static String getDefaultHostIp() {
+ if (SystemUtils.IS_OS_WINDOWS) {
+ final Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*");
+ try {
+ final Process result = Runtime.getRuntime().exec("route print -4");
+ final BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
+
+ String line = output.readLine();
+ while (line != null) {
+ final Matcher matcher = pattern.matcher(line);
+ if (matcher.find()) {
+ return matcher.group(2);
+ }
+ line = output.readLine();
+ }
+ } catch (final IOException e) {
+ s_logger.debug("Caught IOException", e);
+ }
+ return null;
+ } else {
+ NetworkInterface nic = null;
+ final String pubNic = getDefaultEthDevice();
+
+ if (pubNic == null) {
+ return null;
+ }
+
+ try {
+ nic = NetworkInterface.getByName(pubNic);
+ } catch (final SocketException e) {
+ return null;
+ }
+
+ String[] info = null;
+ try {
+ info = NetUtils.getNetworkParams(nic);
+ } catch (final NullPointerException ignored) {
+ s_logger.debug("Caught NullPointerException when trying to getDefaultHostIp");
+ }
+ if (info != null) {
+ return info[0];
+ }
+ return null;
+ }
+ }
+
+ public static String getDefaultEthDevice() {
+ if (SystemUtils.IS_OS_MAC) {
+ final String defDev = Script.runSimpleBashScript("/sbin/route -n get default 2> /dev/null | grep interface | awk '{print $2}'");
+ return defDev;
+ }
+ final String defaultRoute = Script.runSimpleBashScript("/sbin/route | grep default");
+
+ if (defaultRoute == null) {
+ return null;
+ }
+
+ final String[] defaultRouteList = defaultRoute.split("\\s+");
+
+ if (defaultRouteList.length != 8) {
+ return null;
+ }
+
+ return defaultRouteList[7];
+ }
+
+ public static InetAddress getFirstNonLoopbackLocalInetAddress() {
+ final InetAddress[] addrs = getAllLocalInetAddresses();
+ if (addrs != null) {
+ for (final InetAddress addr : addrs) {
+ if (s_logger.isInfoEnabled()) {
+ s_logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);
+ }
+
+ if (!addr.isLoopbackAddress()) {
+ return addr;
+ }
+ }
+ }
+
+ s_logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length);
+ return null;
+ }
+
+ public static InetAddress[] getInterfaceInetAddresses(final String ifName) {
+ final List<InetAddress> addrList = new ArrayList<InetAddress>();
+ try {
+ for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
+ if (ifc.isUp() && !ifc.isVirtual() && ifc.getName().equals(ifName)) {
+ for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
+ addrList.add(addr);
+ }
+ }
+ }
+ } catch (final SocketException e) {
+ s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
+ }
+
+ final InetAddress[] addrs = new InetAddress[addrList.size()];
+ if (addrList.size() > 0) {
+ System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
+ }
+ return addrs;
+ }
+
+ public static String getLocalIPString() {
+ final InetAddress addr = getLocalInetAddress();
+ if (addr != null) {
+ return ipFromInetAddress(addr);
+ }
+
+ return "127.0.0.1";
+ }
+
+ public static String ipFromInetAddress(final InetAddress addr) {
+ assert addr != null;
+
+ final byte[] ipBytes = addr.getAddress();
+ final StringBuffer sb = new StringBuffer();
+ sb.append(ipBytes[0] & 0xff).append(".");
+ sb.append(ipBytes[1] & 0xff).append(".");
+ sb.append(ipBytes[2] & 0xff).append(".");
+ sb.append(ipBytes[3] & 0xff);
+
+ return sb.toString();
+ }
+
+ public static boolean isLocalAddress(final InetAddress addr) {
+ final InetAddress[] addrs = getAllLocalInetAddresses();
+
+ if (addrs != null) {
+ for (final InetAddress self : addrs) {
+ if (self.equals(addr)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isLocalAddress(final String strAddress) {
+
+ InetAddress addr;
+ try {
+ addr = InetAddress.getByName(strAddress);
+ return isLocalAddress(addr);
+ } catch (final UnknownHostException e) {
+ }
+ return false;
+ }
+
+ public static String getMacAddress(final InetAddress address) {
+ final StringBuffer sb = new StringBuffer();
+ final Formatter formatter = new Formatter(sb);
+ try {
+ final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
+ final byte[] mac = ni.getHardwareAddress();
+
+ for (int i = 0; i < mac.length; i++) {
+ formatter.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : "");
+ }
+ } catch (final SocketException e) {
+ s_logger.error("SocketException when trying to retrieve MAC address", e);
+ } finally {
+ formatter.close();
+ }
+ return sb.toString();
+ }
+
+ public static long getMacAddressAsLong(final InetAddress address) {
+ long macAddressAsLong = 0;
+ try {
+ final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
+ final byte[] mac = ni.getHardwareAddress();
+
+ for (int i = 0; i < mac.length; i++) {
+ macAddressAsLong |= (long)(mac[i] & 0xff) << (mac.length - i - 1) * 8;
+ }
+
+ } catch (final SocketException e) {
+ s_logger.error("SocketException when trying to retrieve MAC address", e);
+ }
+
+ return macAddressAsLong;
+ }
+
+ /**
+ * This method will fail in case we have a 31 Bit prefix network
+ * See RFC 3021.
+ *
+ * In order to avoid calling this method, please check the <code>NetUtils.is31PrefixCidr(cidr)</code> first.
+ */
+ public static boolean ipRangesOverlap(final String startIp1, final String endIp1, final String startIp2, final String endIp2) {
+ final long startIp1Long = ip2Long(startIp1);
+ long endIp1Long = startIp1Long;
+ if (endIp1 != null) {
+ endIp1Long = ip2Long(endIp1);
+ }
+ final long startIp2Long = ip2Long(startIp2);
+ long endIp2Long = startIp2Long;
+ if (endIp2 != null) {
+ endIp2Long = ip2Long(endIp2);
+ }
+
+ if (startIp1Long == startIp2Long || startIp1Long == endIp2Long || endIp1Long == startIp2Long || endIp1Long == endIp2Long) {
+ return true;
+ } else if (startIp1Long > startIp2Long && startIp1Long < endIp2Long) {
+ return true;
+ } else if (endIp1Long > startIp2Long && endIp1Long < endIp2Long) {
+ return true;
+ } else if (startIp2Long > startIp1Long && startIp2Long < endIp1Long) {
+ return true;
+ } else if (endIp2Long > startIp1Long && endIp2Long < endIp1Long) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public static long ip2Long(final String ip) {
+ final String[] tokens = ip.split("[.]");
+ assert tokens.length == 4;
+ long result = 0;
+ for (int i = 0; i < tokens.length; i++) {
+ try {
+ result = result << 8 | Integer.parseInt(tokens[i]);
+ } catch (final NumberFormatException e) {
+ throw new RuntimeException("Incorrect number", e);
+ }
+ }
+
+ return result;
+ }
+
+ public static String long2Ip(final long ip) {
+ final StringBuilder result = new StringBuilder(15);
+ result.append(ip >> 24 & 0xff).append(".");
+ result.append(ip >> 16 & 0xff).append(".");
+ result.append(ip >> 8 & 0xff).append(".");
+ result.append(ip & 0xff);
+
+ return result.toString();
+ }
+
+ public static long mac2Long(final String macAddress) {
+ final String[] tokens = macAddress.split(":");
+ assert tokens.length == 6;
+ long result = 0;
+ for (int i = 0; i < tokens.length; i++) {
+ result = result << 8;
+ result |= Integer.parseInt(tokens[i], 16);
+ }
+ return result;
+ }
+
+ public static String[] getNicParams(final String nicName) {
+ try {
+ final NetworkInterface nic = NetworkInterface.getByName(nicName);
+ return getNetworkParams(nic);
+ } catch (final SocketException e) {
+ return null;
+ }
+ }
+
+ public static String[] getNetworkParams(final NetworkInterface nic) {
+ final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
+ if (addrs == null || addrs.size() == 0) {
+ return null;
+ }
+ InterfaceAddress addr = null;
+ for (final InterfaceAddress iaddr : addrs) {
+ final InetAddress inet = iaddr.getAddress();
+ if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
+ addr = iaddr;
+ break;
+ }
+ }
+ if (addr == null) {
+ return null;
+ }
+ final String[] result = new String[3];
+ result[0] = addr.getAddress().getHostAddress();
+ try {
+ final byte[] mac = nic.getHardwareAddress();
+ result[1] = byte2Mac(mac);
+ } catch (final SocketException e) {
+ s_logger.debug("Caught exception when trying to get the mac address ", e);
+ }
+
+ result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
+ return result;
+ }
+
+ public static String prefix2Netmask(final short prefix) {
+ long addr = 0;
+ for (int i = 0; i < prefix; i++) {
+ addr = addr | 1 << 31 - i;
+ }
+
+ return long2Ip(addr);
+ }
+
+ public static String byte2Mac(final byte[] m) {
+ final StringBuilder result = new StringBuilder(17);
+ final Formatter formatter = new Formatter(result);
+ formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
+ formatter.close();
+ return result.toString();
+ }
+
+ public static String long2Mac(final long macAddress) {
+ final StringBuilder result = new StringBuilder(17);
+ try (Formatter formatter = new Formatter(result)) {
+ formatter.format("%02x:%02x:%02x:%02x:%02x:%02x",
+ macAddress >> 40 & 0xff, macAddress >> 32 & 0xff,
+ macAddress >> 24 & 0xff, macAddress >> 16 & 0xff,
+ macAddress >> 8 & 0xff, macAddress & 0xff);
+ }
+ return result.toString();
+ }
+
+ public static boolean isValidPrivateIp(final String ipAddress, final String guestIPAddress) {
+
+ final InetAddress privIp = parseIpAddress(ipAddress);
+ if (privIp == null) {
+ return false;
+ }
+ if (!privIp.isSiteLocalAddress()) {
+ return false;
+ }
+
+ String firstGuestOctet = "10";
+ if (guestIPAddress != null && !guestIPAddress.isEmpty()) {
+ final String[] guestIPList = guestIPAddress.split("\\.");
+ firstGuestOctet = guestIPList[0];
+ }
+
+ final String[] ipList = ipAddress.split("\\.");
+ if (!ipList[0].equals(firstGuestOctet)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public static boolean isSiteLocalAddress(final String ipAddress) {
+ if (ipAddress == null) {
+ return false;
+ } else {
+ final InetAddress ip = parseIpAddress(ipAddress);
+ if(ip != null) {
+ return ip.isSiteLocalAddress();
+ }
+ return false;
+ }
+ }
+
+ public static boolean validIpRange(final String startIP, final String endIP) {
+ if (endIP == null || endIP.isEmpty()) {
+ return true;
+ }
+
+ final long startIPLong = NetUtils.ip2Long(startIP);
+ final long endIPLong = NetUtils.ip2Long(endIP);
+ return startIPLong <= endIPLong;
+ }
+
+ public static boolean isValidIp(final String ip) {
+ final InetAddressValidator validator = InetAddressValidator.getInstance();
+
+ return validator.isValidInet4Address(ip);
+ }
+
+ public static boolean is31PrefixCidr(final String cidr) {
+ final boolean isValidCird = isValidCIDR(cidr);
+ if (isValidCird){
+ final String[] cidrPair = cidr.split("\\/");
+ final String cidrSize = cidrPair[1];
+
+ final int cidrSizeNum = Integer.parseInt(cidrSize);
+ if (cidrSizeNum == RFC_3021_31_BIT_CIDR) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static boolean isValidCIDR(final String cidr) {
+ if (cidr == null || cidr.isEmpty()) {
+ return false;
+ }
+ final String[] cidrPair = cidr.split("\\/");
+ if (cidrPair.length != 2) {
+ return false;
+ }
+ final String cidrAddress = cidrPair[0];
+ final String cidrSize = cidrPair[1];
+ if (!isValidIp(cidrAddress)) {
+ return false;
+ }
+ int cidrSizeNum = -1;
+
+ try {
+ cidrSizeNum = Integer.parseInt(cidrSize);
+ } catch (final Exception e) {
+ return false;
+ }
+
+ if (cidrSizeNum < 0 || cidrSizeNum > MAX_CIDR) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public static boolean isValidNetmask(final String netmask) {
+ if (!isValidIp(netmask)) {
+ return false;
+ }
+
+ final long ip = ip2Long(netmask);
+ int count = 0;
+ boolean finished = false;
+ for (int i = 31; i >= 0; i--) {
+ if ((ip >> i & 0x1) == 0) {
+ finished = true;
+ } else {
+ if (finished) {
+ return false;
+ }
+ count += 1;
+ }
+ }
+
+ if (count == 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private static InetAddress parseIpAddress(final String address) {
+ final StringTokenizer st = new StringTokenizer(address, ".");
+ final byte[] bytes = new byte[4];
+
+ if (st.countTokens() == 4) {
+ try {
+ for (int i = 0; i < 4; i++) {
+ bytes[i] = (byte)Integer.parseInt(st.nextToken());
+ }
+ return InetAddress.getByAddress(address, bytes);
+ } catch (final NumberFormatException nfe) {
+ return null;
+ } catch (final UnknownHostException uhe) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ public static String getCidrFromGatewayAndNetmask(final String gatewayStr, final String netmaskStr) {
+ final long netmask = ip2Long(netmaskStr);
+ final long gateway = ip2Long(gatewayStr);
+ final long firstPart = gateway & netmask;
+ final long size = getCidrSize(netmaskStr);
+ return long2Ip(firstPart) + "/" + size;
+ }
+
+ public static String[] getIpRangeFromCidr(final String cidr, final long size) {
+ assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
+ final String[] result = new String[2];
+ final long ip = ip2Long(cidr);
+ final long startNetMask = ip2Long(getCidrNetmask(size));
+ final long start = (ip & startNetMask) + 1;
+ long end = start;
+
+ end = end >> MAX_CIDR - size;
+
+ end++;
+ end = (end << MAX_CIDR - size) - 2;
+
+ result[0] = long2Ip(start);
+ result[1] = long2Ip(end);
+
+ return result;
+ }
+
+ public static Set<Long> getAllIpsFromCidr(final String cidr, final long size, final Set<Long> usedIps) {
+ assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
+ final Set<Long> result = new TreeSet<Long>();
+ final long ip = ip2Long(cidr);
+ final long startNetMask = ip2Long(getCidrNetmask(size));
+ long start = (ip & startNetMask) + 1;
+ long end = start;
+
+ end = end >> MAX_CIDR - size;
+
+ end++;
+ end = (end << MAX_CIDR - size) - 2;
+ int maxIps = 255; // get 255 ips as maximum
+ while (start <= end && maxIps > 0) {
+ if (!usedIps.contains(start)) {
+ result.add(start);
+ maxIps--;
+ }
+ start++;
+ }
+
+ return result;
+ }
+
+ /**
+ * Given a cidr, this method returns an ip address within the range but
+ * is not in the avoid list.
+ *
+ * @param startIp ip that the cidr starts with
+ * @param size size of the cidr
+ * @param avoid set of ips to avoid
+ * @return ip that is within the cidr range but not in the avoid set. -1 if unable to find one.
+ */
+ public static long getRandomIpFromCidr(final String startIp, final int size, final SortedSet<Long> avoid) {
+ return getRandomIpFromCidr(ip2Long(startIp), size, avoid);
+
+ }
+
+ /**
+ * Given a cidr, this method returns an ip address within the range but
+ * is not in the avoid list.
+ * Note: the gateway address has to be specified in the avoid list
+ *
+ * @param cidr ip that the cidr starts with
+ * @param size size of the cidr
+ * @param avoid set of ips to avoid
+ * @return ip that is within the cidr range but not in the avoid set. -1 if unable to find one.
+ */
+ public static long getRandomIpFromCidr(final long cidr, final int size, final SortedSet<Long> avoid) {
+ assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
+
+ final long startNetMask = ip2Long(getCidrNetmask(size));
+ final long startIp = (cidr & startNetMask) + 1; //exclude the first ip since it isnt valid, e.g., 192.168.10.0
+ int range = 1 << MAX_CIDR - size; //e.g., /24 = 2^8 = 256
+ range = range - 1; //exclude end of the range since that is the broadcast address, e.g., 192.168.10.255
+
+ if (avoid.size() >= range) {
+ return -1;
+ }
+
+ //Reduce the range by the size of the avoid set
+ //e.g., cidr = 192.168.10.0, size = /24, avoid = 192.168.10.1, 192.168.10.20, 192.168.10.254
+ // range = 2^8 - 1 - 3 = 252
+ range = range - avoid.size();
+ final int next = s_rand.nextInt(range); //note: nextInt excludes last value
+ long ip = startIp + next;
+ for (final Long avoidable : avoid) {
+ if (ip >= avoidable) {
+ ip++;
+ } else {
+ break;
+ }
+ }
+
+ return ip;
+ }
+
+ public static String getIpRangeStartIpFromCidr(final String cidr, final long size) {
+ final long ip = ip2Long(cidr);
+ final long startNetMask = ip2Long(getCidrNetmask(size));
+ final long start = (ip & startNetMask) + 1;
+ return long2Ip(start);
+ }
+
+ public static String getIpRangeEndIpFromCidr(final String cidr, final long size) {
+ final long ip = ip2Long(cidr);
+ final long startNetMask = ip2Long(getCidrNetmask(size));
+ final long start = (ip & startNetMask) + 1;
+ long end = start;
+ end = end >> MAX_CIDR - size;
+
+ end++;
+ end = (end << MAX_CIDR - size) - 2;
+ return long2Ip(end);
+ }
+
+ public static boolean sameSubnet(final String ip1, final String ip2, final String netmask) {
+ if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
+ return true;
+ }
+ final String subnet1 = NetUtils.getSubNet(ip1, netmask);
+ final String subnet2 = NetUtils.getSubNet(ip2, netmask);
+
+ return subnet1.equals(subnet2);
+ }
+
+ public static boolean sameSubnetCIDR(final String ip1, final String ip2, final long cidrSize) {
+ if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
+ return true;
+ }
+ final String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize);
+ final String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize);
+
+ return subnet1.equals(subnet2);
+ }
+
+ public static String getSubNet(final String ip, final String netmask) {
+ final long ipAddr = ip2Long(ip);
+ final long subnet = ip2Long(netmask);
+ final long result = ipAddr & subnet;
+ return long2Ip(result);
+ }
+
+ public static String getCidrSubNet(final String ip, final long cidrSize) {
+ final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSize << MAX_CIDR - cidrSize;
+ final String netmask = NetUtils.long2Ip(numericNetmask);
+ return getSubNet(ip, netmask);
+ }
+
+ public static String ipAndNetMaskToCidr(final String ip, final String netmask) {
+ if (!isValidIp(ip)) {
+ return null;
+ }
+
+ if (!isValidNetmask(netmask)) {
+ return null;
+ }
+
+ final long ipAddr = ip2Long(ip);
+ final long subnet = ip2Long(netmask);
+ final long result = ipAddr & subnet;
+ int bits = subnet == 0 ? 0 : 1;
+ long subnet2 = subnet;
+ while ((subnet2 = subnet2 >> 1 & subnet) != 0) {
+ bits++;
+ }
+
+ return long2Ip(result) + "/" + Integer.toString(bits);
+ }
+
+ public static String[] ipAndNetMaskToRange(final String ip, final String netmask) {
+ final long ipAddr = ip2Long(ip);
+ long subnet = ip2Long(netmask);
+ final long start = (ipAddr & subnet) + 1;
+ long end = start;
+ int bits = subnet == 0 ? 0 : 1;
+ while ((subnet = subnet >> 1 & subnet) != 0) {
+ bits++;
+ }
+ end = end >> MAX_CIDR - bits;
+
+ end++;
+ end = (end << MAX_CIDR - bits) - 2;
+
+ return new String[] {long2Ip(start), long2Ip(end)};
+
+ }
+
+ public static Pair<String, Integer> getCidr(final String cidr) {
+ final String[] tokens = cidr.split("/");
+ return new Pair<String, Integer>(tokens[0], Integer.parseInt(tokens[1]));
+ }
+
+ public static enum SupersetOrSubset {
+ isSuperset, isSubset, neitherSubetNorSuperset, sameSubnet, errorInCidrFormat
+ }
+
+ public static SupersetOrSubset isNetowrkASubsetOrSupersetOfNetworkB(final String cidrA, final String cidrB) {
+ final Long[] cidrALong = cidrToLong(cidrA);
+ final Long[] cidrBLong = cidrToLong(cidrB);
+ long shift = 0;
+ if (cidrALong == null || cidrBLong == null) {
+ //implies error in the cidr format
+ return SupersetOrSubset.errorInCidrFormat;
+ }
+ if (cidrALong[1] >= cidrBLong[1]) {
+ shift = MAX_CIDR - cidrBLong[1];
+ } else {
+ shift = MAX_CIDR - cidrALong[1];
+ }
+ final long result = (cidrALong[0] >> shift) - (cidrBLong[0] >> shift);
+ if (result == 0) {
+ if (cidrALong[1] < cidrBLong[1]) {
+ //this implies cidrA is super set of cidrB
+ return SupersetOrSubset.isSuperset;
+ } else if (cidrALong[1].equals(cidrBLong[1])) {
+ //this implies both the cidrs are equal
+ return SupersetOrSubset.sameSubnet;
+ }
+ // implies cidrA is subset of cidrB
+ return SupersetOrSubset.isSubset;
+ }
+ //this implies no overlap.
+ return SupersetOrSubset.neitherSubetNorSuperset;
+ }
+
+ public static boolean isNetworkAWithinNetworkB(final String cidrA, final String cidrB) {
+ final Long[] cidrALong = cidrToLong(cidrA);
+ final Long[] cidrBLong = cidrToLong(cidrB);
+ if (cidrALong == null || cidrBLong == null) {
+ return false;
+ }
+ final long shift = MAX_CIDR - cidrBLong[1];
+ return cidrALong[0] >> shift == cidrBLong[0] >> shift;
+ }
+
+ public static Long[] cidrToLong(final String cidr) {
+ if (cidr == null || cidr.isEmpty()) {
+ return null;
+ }
+ final String[] cidrPair = cidr.split("\\/");
+ if (cidrPair.length != 2) {
+ return null;
+ }
+ final String cidrAddress = cidrPair[0];
+ final String cidrSize = cidrPair[1];
+ if (!isValidIp(cidrAddress)) {
+ return null;
+ }
+ int cidrSizeNum = -1;
+
+ try {
+ cidrSizeNum = Integer.parseInt(cidrSize);
+ } catch (final Exception e) {
+ return null;
+ }
+ final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSizeNum << MAX_CIDR - cidrSizeNum;
+ final long ipAddr = ip2Long(cidrAddress);
+ final Long[] cidrlong = {ipAddr & numericNetmask, (long)cidrSizeNum};
+ return cidrlong;
+
+ }
+
+ public static String getCidrSubNet(final String cidr) {
+ if (cidr == null || cidr.isEmpty()) {
+ return null;
+ }
+ final String[] cidrPair = cidr.split("\\/");
+ if (cidrPair.length != 2) {
+ return null;
+ }
+ final String cidrAddress = cidrPair[0];
+ final String cidrSize = cidrPair[1];
+ if (!isValidIp(cidrAddress)) {
+ return null;
+ }
+ int cidrSizeNum = -1;
+
+ try {
+ cidrSizeNum = Integer.parseInt(cidrSize);
+ } catch (final Exception e) {
+ return null;
+ }
+ final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSizeNum << MAX_CIDR - cidrSizeNum;
+ final String netmask = NetUtils.long2Ip(numericNetmask);
+ return getSubNet(cidrAddress, netmask);
+ }
+
+ public static String getCidrNetmask(final long cidrSize) {
+ final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSize << MAX_CIDR - cidrSize;
+ return long2Ip(numericNetmask);
+ }
+
+ public static String getCidrNetmask(final String cidr) {
+ final String[] cidrPair = cidr.split("\\/");
+ final long guestCidrSize = Long.parseLong(cidrPair[1]);
+ return getCidrNetmask(guestCidrSize);
+ }
+
+ public static String cidr2Netmask(final String cidr) {
+ final String[] tokens = cidr.split("\\/");
+ return getCidrNetmask(Integer.parseInt(tokens[1]));
+ }
+
+ public static long getCidrSize(final String netmask) {
+ final long ip = ip2Long(netmask);
+ int count = 0;
+ for (int i = 0; i < MAX_CIDR; i++) {
+ if ((ip >> i & 0x1) == 0) {
+ count++;
+ } else {
+ break;
+ }
+ }
+
+ return MAX_CIDR - count;
+ }
+
+ public static boolean isValidPort(final String p) {
+ try {
+ final int port = Integer.parseInt(p);
+ return !(port > 65535 || port < 1);
+ } catch (final NumberFormatException e) {
+ return false;
+ }
+ }
+
+ public static boolean isValidPort(final int p) {
+ return !(p > 65535 || p < 1);
+ }
+
+ public static boolean isValidLBPort(final String p) {
+ try {
+ final int port = Integer.parseInt(p);
+ return !(port > 65535 || port < 1);
+ } catch (final NumberFormatException e) {
+ return false;
+ }
+ }
+
+ public static boolean isValidProto(final String p) {
+ final String proto = p.toLowerCase();
+ return proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO);
+ }
+
+ public static boolean isValidSecurityGroupProto(final String p) {
+ final String proto = p.toLowerCase();
+ return proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO) || proto.equals(ALL_PROTO);
+ }
+
+ public static boolean isValidAlgorithm(final String p) {
+ final String algo = p.toLowerCase();
+ return algo.equals("roundrobin") || algo.equals("leastconn") || algo.equals("source");
+ }
+
+ public static boolean isValidAutoScaleAction(final String p) {
+ final String action = p.toLowerCase();
+ return action.equals("scaleup") || action.equals("scaledown");
+ }
+
+ public static String getLinkLocalNetMask() {
+ return "255.255.0.0";
+ }
+
+ public static String getLinkLocalGateway() {
+ return "169.254.0.1";
+ }
+
+ public static String getLinkLocalCIDR() {
+ return "169.254.0.0/16";
+ }
+
+ public static String[] getLinkLocalIPRange(final int size) {
+ if (size > 16 || size <= 0) {
+ return null;
+ }
+ /* reserve gateway */
+ final String[] range = getIpRangeFromCidr(getLinkLocalGateway(), MAX_CIDR - size);
+
+ if (range[0].equalsIgnoreCase(getLinkLocalGateway())) {
+ /* remove the gateway */
+ long ip = ip2Long(range[0]);
+ ip += 1;
+ range[0] = long2Ip(ip);
+ }
+ return range;
+ }
+
+ public static String getLinkLocalIpEnd() {
+ final String[] cidrPair = getLinkLocalCIDR().split("\\/");
+ final String cidr = cidrPair[0];
+
+ return getIpRangeEndIpFromCidr(cidr, MAX_CIDR - Long.parseLong(cidrPair[1]));
+ }
+
+ public static String portRangeToString(final int portRange[]) {
+ return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]);
+ }
+
+ public static boolean verifyDomainNameLabel(final String hostName, final boolean isHostName) {
+ // must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a
+ // case-insensitive manner),
+ // the digits '0' through '9', and the hyphen ('-').
+ // Can not start with a hyphen and digit, and must not end with a hyphen
+ // If it's a host name, don't allow to start with digit
+
+ if (hostName.length() > 63 || hostName.length() < 1) {
+ s_logger.warn("Domain name label must be between 1 and 63 characters long");
+ return false;
+ } else if (!hostName.toLowerCase().matches("[a-z0-9-]*")) {
+ s_logger.warn("Domain name label may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner)");
+ return false;
+ } else if (hostName.startsWith("-") || hostName.endsWith("-")) {
+ s_logger.warn("Domain name label can not start with a hyphen and digit, and must not end with a hyphen");
+ return false;
+ } else if (isHostName && hostName.matches("^[0-9-].*")) {
+ s_logger.warn("Host name can't start with digit");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static boolean verifyDomainName(final String domainName) {
+ // don't allow domain name length to exceed 190 chars (190 + 63 (max host name length) = 253 = max domainName length
+ if (domainName.length() < 1 || domainName.length() > 190) {
+ s_logger.trace("Domain name must be between 1 and 190 characters long");
+ return false;
+ }
+
+ if (domainName.startsWith(".") || domainName.endsWith(".")) {
+ s_logger.trace("Domain name can't start or end with .");
+ return false;
+ }
+
+ final String[] domainNameLabels = domainName.split("\\.");
+
+ for (int i = 0; i < domainNameLabels.length; i++) {
+ if (!verifyDomainNameLabel(domainNameLabels[i], false)) {
+ s_logger.warn("Domain name label " + domainNameLabels[i] + " is incorrect");
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static String getDhcpRange(final String cidr) {
+ final String[] splitResult = cidr.split("\\/");
+ final long size = Long.parseLong(splitResult[1]);
+ return NetUtils.getIpRangeStartIpFromCidr(splitResult[0], size);
+ }
+
+ // Check if 2 CIDRs have exactly same IP Range
+ public static boolean isSameIpRange(final String cidrA, final String cidrB) {
+
+ if (!NetUtils.isValidCIDR(cidrA)) {
+ s_logger.info("Invalid value of cidr " + cidrA);
+ return false;
+ }
+ if (!NetUtils.isValidCIDR(cidrB)) {
+ s_logger.info("Invalid value of cidr " + cidrB);
+ return false;
+ }
+ final String[] cidrPairFirst = cidrA.split("\\/");
+ final String[] cidrPairSecond = cidrB.split("\\/");
+
+ final Long networkSizeFirst = Long.valueOf(cidrPairFirst[1]);
+ final Long networkSizeSecond = Long.valueOf(cidrPairSecond[1]);
+ final String ipRangeFirst[] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeFirst);
+ final String ipRangeSecond[] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeSecond);
+
+ final long startIpFirst = NetUtils.ip2Long(ipRangeFirst[0]);
+ final long endIpFirst = NetUtils.ip2Long(ipRangeFirst[1]);
+ final long startIpSecond = NetUtils.ip2Long(ipRangeSecond[0]);
+ final long endIpSecond = NetUtils.ip2Long(ipRangeSecond[1]);
+ if (startIpFirst == startIpSecond && endIpFirst == endIpSecond) {
+ return true;
+ }
+ return false;
+ }
+
+ public static boolean validateGuestCidr(final String cidr) {
+ // RFC 1918 - The Internet Assigned Numbers Authority (IANA) has reserved the
+ // following three blocks of the IP address space for private internets:
+ // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
+ // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
+ // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
+
+ final String cidr1 = "10.0.0.0/8";
+ final String cidr2 = "172.16.0.0/12";
+ final String cidr3 = "192.168.0.0/16";
+
+ if (!isValidCIDR(cidr)) {
+ s_logger.warn("Cidr " + cidr + " is not valid");
+ return false;
+ }
+
+ if (isNetworkAWithinNetworkB(cidr, cidr1) || isNetworkAWithinNetworkB(cidr, cidr2) || isNetworkAWithinNetworkB(cidr, cidr3)) {
+ return true;
+ } else {
+ s_logger.warn("cidr " + cidr + " is not RFC 1918 compliant");
+ return false;
+ }
+ }
+
+ public static boolean verifyInstanceName(final String instanceName) {
+ //instance name for cloudstack vms shouldn't contain - and spaces
+ if (instanceName.contains("-") || instanceName.contains(" ") || instanceName.contains("+")) {
+ s_logger.warn("Instance name can not contain hyphen, spaces and \"+\" char");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static boolean isNetworksOverlap(final String cidrA, final String cidrB) {
+ final Long[] cidrALong = cidrToLong(cidrA);
+ final Long[] cidrBLong = cidrToLong(cidrB);
+ if (cidrALong == null || cidrBLong == null) {
+ return false;
+ }
+ final long shift = MAX_CIDR - (cidrALong[1] > cidrBLong[1] ? cidrBLong[1] : cidrALong[1]);
+ return cidrALong[0] >> shift == cidrBLong[0] >> shift;
+ }
+
+ public static boolean isValidS2SVpnPolicy(final String policys) {
+ if (policys == null || policys.isEmpty()) {
+ return false;
+ }
+ for (final String policy : policys.split(",")) {
+ if (policy.isEmpty()) {
+ return false;
+ }
+ final String cipherHash = policy.split(";")[0];
+ if (cipherHash.isEmpty()) {
+ return false;
+ }
+ final String[] list = cipherHash.split("-");
+ if (list.length != 2) {
+ return false;
+ }
+ final String cipher = list[0];
+ final String hash = list[1];
+ if (!cipher.matches("3des|aes128|aes192|aes256")) {
+ return false;
+ }
+ if (!hash.matches("md5|sha1")) {
+ return false;
+ }
+ String pfsGroup = null;
+ if (!policy.equals(cipherHash)) {
+ pfsGroup = policy.split(";")[1];
+ }
+ if (pfsGroup != null && !pfsGroup.matches("modp1024|modp1536")) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static boolean isValidCidrList(final String cidrList) {
+ for (final String guestCidr : cidrList.split(",")) {
+ if (!isValidCIDR(guestCidr)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static boolean validateGuestCidrList(final String guestCidrList) {
+ for (final String guestCidr : guestCidrList.split(",")) {
+ if (!validateGuestCidr(guestCidr)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static boolean validateIcmpType(final long icmpType) {
+ //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
+ if (!(icmpType >= 0 && icmpType <= 255)) {
+ s_logger.warn("impcType is not within 0-255 range");
+ return false;
+ }
+ return true;
+ }
+
+ public static boolean validateIcmpCode(final long icmpCode) {
+
+ //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
+ if (!(icmpCode >= 0 && icmpCode <= 15)) {
+ s_logger.warn("Icmp code should be within 0-15 range");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static boolean isValidIpv6(final String ip) {
+ try {
+ IPv6Address.fromString(ip);
+ } catch (final IllegalArgumentException ex) {
+ return false;
+ }
+ return true;
+ }
+
+ public static boolean isValidIp6Cidr(final String ip6Cidr) {
+ try {
+ IPv6Network.fromString(ip6Cidr);
+ } catch (final IllegalArgumentException ex) {
+ return false;
+ }
+ return true;
+ }
+
+ public static int getIp6CidrSize(final String ip6Cidr) {
+ IPv6Network network = null;
+ try {
+ network = IPv6Network.fromString(ip6Cidr);
+ } catch (final IllegalArgumentException ex) {
+ return 0;
+ }
+ return network.getNetmask().asPrefixLength();
+ }
+
+ // Can cover 127 bits
+ public static String getIp6FromRange(final String ip6Range) {
+ final String[] ips = ip6Range.split("-");
+ final String startIp = ips[0];
+ final IPv6Address start = IPv6Address.fromString(startIp);
+ final BigInteger gap = countIp6InRange(ip6Range);
+ BigInteger next = new BigInteger(gap.bitLength(), s_rand);
+ while (next.compareTo(gap) >= 0) {
+ next = new BigInteger(gap.bitLength(), s_rand);
+ }
+ InetAddress resultAddr = null;
+ final BigInteger startInt = convertIPv6AddressToBigInteger(start);
+ if (startInt != null) {
+ final BigInteger resultInt = startInt.add(next);
+ try {
+ resultAddr = InetAddress.getByAddress(resultInt.toByteArray());
+ } catch (final UnknownHostException e) {
+ return null;
+ }
+ }
+ if( resultAddr != null) {
+ final IPv6Address ip = IPv6Address.fromInetAddress(resultAddr);
+ return ip.toString();
+ }
+ return null;
+ }
+
+ //RFC3315, section 9.4
+ public static String getDuidLL(final String macAddress) {
+ final String duid = "00:03:00:01:" + macAddress;
+ return duid;
+ }
+
+ private static BigInteger convertIPv6AddressToBigInteger(final IPv6Address addr) {
+ InetAddress inetAddr;
+ try {
+ inetAddr = addr.toInetAddress();
+ } catch (final UnknownHostException e) {
+ return null;
+ }
+ return new BigInteger(inetAddr.getAddress());
+ }
+
+ // Can cover 127 bits
+ public static BigInteger countIp6InRange(final String ip6Range) {
+ if (ip6Range == null) {
+ return null;
+ }
+ final String[] ips = ip6Range.split("-");
+ final String startIp = ips[0];
+ String endIp = ips[0];
+ if (ips.length > 1) {
+ endIp = ips[1];
+ }
+ try {
+ final BigInteger startInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(startIp));
+ final BigInteger endInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(endIp));
+ if (endInt != null && startInt != null && startInt.compareTo(endInt) <= 0) {
+ return endInt.subtract(startInt).add(BigInteger.ONE);
+ }
+ } catch (final IllegalArgumentException ex) {
+ s_logger.error("Failed to convert a string to an IPv6 address", ex);
+ }
+ return null;
+ }
+
+ public static boolean isIp6InRange(final String ip6, final String ip6Range) {
+ if (ip6Range == null) {
+ return false;
+ }
+ final String[] ips = ip6Range.split("-");
+ final String startIp = ips[0];
+ String endIp = null;
+ if (ips.length > 1) {
+ endIp = ips[1];
+ }
+ final IPv6Address start = IPv6Address.fromString(startIp);
+ final IPv6Address end = IPv6Address.fromString(endIp);
+ final IPv6Address ip = IPv6Address.fromString(ip6);
+ if (start.compareTo(ip) <= 0 && end.compareTo(ip) >= 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public static boolean isIp6InNetwork(final String ip6, final String ip6Cidr) {
+ IPv6Network network = null;
+ try {
+ network = IPv6Network.fromString(ip6Cidr);
+ } catch (final IllegalArgumentException ex) {
+ return false;
+ }
+ final IPv6Address ip = IPv6Address.fromString(ip6);
+ return network.contains(ip);
+ }
+
+ public static boolean isIp6RangeOverlap(final String ipRange1, final String ipRange2) {
+ String[] ips = ipRange1.split("-");
+ final String startIp1 = ips[0];
+ String endIp1 = null;
+ if (ips.length > 1) {
+ endIp1 = ips[1];
+ }
+ final IPv6Address start1 = IPv6Address.fromString(startIp1);
+ final IPv6Address end1 = IPv6Address.fromString(endIp1);
+ final IPv6AddressRange range1 = IPv6AddressRange.fromFirstAndLast(start1, end1);
+ ips = ipRange2.split("-");
+ final String startIp2 = ips[0];
+ String endIp2 = null;
+ if (ips.length > 1) {
+ endIp2 = ips[1];
+ }
+ final IPv6Address start2 = IPv6Address.fromString(startIp2);
+ final IPv6Address end2 = IPv6Address.fromString(endIp2);
+ final IPv6AddressRange range2 = IPv6AddressRange.fromFirstAndLast(start2, end2);
+ return range1.overlaps(range2);
+ }
+
+ public static String getNextIp6InRange(final String currentIp, final String ipRange) {
+ final String[] ips = ipRange.split("-");
+ final String startIp = ips[0];
+ String endIp = null;
+ if (ips.length > 1) {
+ endIp = ips[1];
+ }
+ final IPv6Address start = IPv6Address.fromString(startIp);
+ final IPv6Address end = IPv6Address.fromString(endIp);
+ final IPv6Address current = IPv6Address.fromString(currentIp);
+ IPv6Address result = null;
+ if (current.equals(end)) {
+ result = start;
+ } else {
+ result = current.add(1);
+ }
+ String resultIp = null;
+ if (result != null) {
+ resultIp = result.toString();
+ }
+ return resultIp;
+ }
+
+ public static String standardizeIp6Address(final String ip6Addr) {
+ try {
+ return IPv6Address.fromString(ip6Addr).toString();
+ } catch (final IllegalArgumentException ex) {
+ throw new IllegalArgumentException("Invalid IPv6 address: " + ex.getMessage());
+ }
+ }
+
+ public static String standardizeIp6Cidr(final String ip6Cidr){
+ try {
+ return IPv6Network.fromString(ip6Cidr).toString();
+ } catch (final IllegalArgumentException ex) {
+ throw new IllegalArgumentException("Invalid IPv6 CIDR: " + ex.getMessage());
+ }
+ }
+
+ static final String VLAN_PREFIX = "vlan://";
+ static final int VLAN_PREFIX_LENGTH = VLAN_PREFIX.length();
+
+ public static boolean isValidVlan(String vlan) {
+ if (null == vlan || "".equals(vlan)) {
+ return false;
+ }
+ if (vlan.startsWith(VLAN_PREFIX)) {
+ vlan = vlan.substring(VLAN_PREFIX_LENGTH);
+ }
+ try {
+ final int vnet = Integer.parseInt(vlan);
+ if (vnet <= 0 || vnet >= 4095) { // the valid range is 1- 4094
+ return false;
+ }
+ return true;
+ } catch (final NumberFormatException e) {
+ return false;
+ }
+ }
+
+ static final String VLAN_UNTAGGED = "untagged";
+
+ public static boolean isSameIsolationId(String one, String other) {
+ // check nulls
+ // check empty strings
+ if ((one == null || one.isEmpty()) && (other == null || other.isEmpty())) {
+ return true;
+ }
+ if (one == null || other == null) {
+ return false;
+ }
+ // check 'untagged'
+ if (one.contains(VLAN_UNTAGGED) && other.contains(VLAN_UNTAGGED)) {
+ return true;
+ }
+ // if one is a number check the other as number and as 'vlan://' + number
+ if (one.startsWith(VLAN_PREFIX)) {
+ one = one.substring(VLAN_PREFIX_LENGTH);
+ }
+ if (other.startsWith(VLAN_PREFIX)) {
+ other = other.substring(VLAN_PREFIX_LENGTH);
+ }
+ // check valid uris or numbers
+ if (one.equalsIgnoreCase(other)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ // Attention maintainers: these pvlan functions should take into account code
+ // in Networks.BroadcastDomainType, where URI construction is done for other
+ // types of BroadcastDomainTypes
+ public static URI generateUriForPvlan(final String primaryVlan, final String isolatedPvlan) {
+ return URI.create("pvlan://" + primaryVlan + "-i" + isolatedPvlan);
+ }
+
+ public static String getPrimaryPvlanFromUri(final URI uri) {
+ final String[] vlans = uri.getHost().split("-");
+ if (vlans.length < 1) {
+ return null;
+ }
+ return vlans[0];
+ }
+
+ public static String getIsolatedPvlanFromUri(final URI uri) {
+ final String[] vlans = uri.getHost().split("-");
+ if (vlans.length < 2) {
+ return null;
+ }
+ for (final String vlan : vlans) {
+ if (vlan.startsWith("i")) {
+ return vlan.replace("i", " ").trim();
+ }
+ }
+ return null;
+ }
+
+ public static String generateMacOnIncrease(final String baseMac, final long l) {
+ long mac = mac2Long(baseMac);
+ if (l > 0xFFFFl) {
+ return null;
+ }
+ mac = mac + (l << 24);
+ mac = mac & 0x06FFFFFFFFFFl;
+ return long2Mac(mac);
+ }
+
+ public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) {
+ if (!isValidIp(ipAddress)) {
+ return false;
+ }
+ if (!isValidCIDR(cidr)) {
+ return false;
+ }
+
+ // check if the gatewayip is the part of the ip range being added.
+ // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links
+ // GW Netmask Stat IP End IP
+ // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1
+ // https://tools.ietf.org/html/rfc3021
+ // Added by Wilder Rodrigues
+ final SubnetUtils subnetUtils = new SubnetUtils(cidr);
+ subnetUtils.setInclusiveHostCount(true);
+
+ final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress);
+
+ return isInRange;
+ }
+
+ public static Boolean IsIpEqualToNetworkOrBroadCastIp(final String requestedIp, final String cidr, final long size) {
+ assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
+
+ final long ip = ip2Long(cidr);
+ final long startNetMask = ip2Long(getCidrNetmask(size));
+
+ final long start = ip & startNetMask;
+ long end = start;
+
+ end = end >> MAX_CIDR - size;
+
+ end++;
+ end = (end << MAX_CIDR - size) - 1;
+
+ final long reqIp = ip2Long(requestedIp);
+ if (reqIp == start || reqIp == end) {
+ return true;
+ }
+ return false;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/net/NfsUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/net/NfsUtils.java b/utils/src/main/java/com/cloud/utils/net/NfsUtils.java
new file mode 100644
index 0000000..23c1007
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/net/NfsUtils.java
@@ -0,0 +1,55 @@
+//
+// 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 com.cloud.utils.net;
+
+import java.io.File;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+public class NfsUtils {
+
+ public static String url2Mount(String urlStr) throws URISyntaxException {
+ URI url;
+ url = new URI(urlStr);
+ return url.getHost() + ":" + url.getPath();
+ }
+
+ public static String uri2Mount(URI uri) {
+ return uri.getHost() + ":" + uri.getPath();
+ }
+
+ public static String url2PathSafeString(String urlStr) {
+ String safe = urlStr.replace(File.separatorChar, '-');
+ safe = safe.replace("?", "");
+ safe = safe.replace("*", "");
+ safe = safe.replace("\\", "");
+ safe = safe.replace("/", "");
+ return safe;
+ }
+
+ public static String getHostPart(String nfsPath) {
+ String toks[] = nfsPath.split(":");
+ if (toks != null && toks.length == 2) {
+ return toks[0];
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/net/UrlUtil.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/net/UrlUtil.java b/utils/src/main/java/com/cloud/utils/net/UrlUtil.java
new file mode 100644
index 0000000..539486e
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/net/UrlUtil.java
@@ -0,0 +1,63 @@
+//
+// 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 com.cloud.utils.net;
+
+import java.net.URI;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+
+public class UrlUtil {
+ public final static Map<String, String> parseQueryParameters(String query) {
+ HashMap<String, String> values = new HashMap<String, String>();
+ parseQueryParameters(query, false, values);
+
+ return values;
+ }
+
+ public final static Map<String, String> parseQueryParameters(URL url) {
+ return parseQueryParameters(url.getQuery());
+ }
+
+ public final static Map<String, String> parseQueryParameters(URI url) {
+ return parseQueryParameters(url.getQuery());
+ }
+
+ public final static void parseQueryParameters(String query, boolean lowercaseKeys, Map<String, String> params) {
+ if (query == null) {
+ return;
+ }
+
+ if (query.startsWith("?")) {
+ query = query.substring(1);
+ }
+
+ String[] parts = query.split("&");
+ for (String part : parts) {
+ String[] tokens = part.split("=");
+
+ if (lowercaseKeys) {
+ tokens[0] = tokens[0].toLowerCase();
+ }
+
+ params.put(tokens[0], tokens[1]);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/HandlerFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/HandlerFactory.java b/utils/src/main/java/com/cloud/utils/nio/HandlerFactory.java
new file mode 100644
index 0000000..f6b9c82
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/HandlerFactory.java
@@ -0,0 +1,28 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.nio;
+
+/**
+ * WorkerFactory creates and selects workers.
+ */
+public interface HandlerFactory {
+ public Task create(Task.Type type, Link link, byte[] data);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/nio/Link.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/nio/Link.java b/utils/src/main/java/com/cloud/utils/nio/Link.java
new file mode 100644
index 0000000..6d6306a
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/nio/Link.java
@@ -0,0 +1,567 @@
+//
+// 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 com.cloud.utils.nio;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetSocketAddress;
+import java.net.SocketTimeoutException;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.SocketChannel;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.cloudstack.utils.security.SSLUtils;
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.PropertiesUtil;
+import com.cloud.utils.db.DbProperties;
+
+/**
+ */
+public class Link {
+ private static final Logger s_logger = Logger.getLogger(Link.class);
+
+ private final InetSocketAddress _addr;
+ private final NioConnection _connection;
+ private SelectionKey _key;
+ private final ConcurrentLinkedQueue<ByteBuffer[]> _writeQueue;
+ private ByteBuffer _readBuffer;
+ private ByteBuffer _plaintextBuffer;
+ private Object _attach;
+ private boolean _readHeader;
+ private boolean _gotFollowingPacket;
+
+ private SSLEngine _sslEngine;
+ public static final String keystoreFile = "/cloudmanagementserver.keystore";
+
+ public Link(InetSocketAddress addr, NioConnection connection) {
+ _addr = addr;
+ _connection = connection;
+ _readBuffer = ByteBuffer.allocate(2048);
+ _attach = null;
+ _key = null;
+ _writeQueue = new ConcurrentLinkedQueue<ByteBuffer[]>();
+ _readHeader = true;
+ _gotFollowingPacket = false;
+ }
+
+ public Link(Link link) {
+ this(link._addr, link._connection);
+ }
+
+ public Object attachment() {
+ return _attach;
+ }
+
+ public void attach(Object attach) {
+ _attach = attach;
+ }
+
+ public void setKey(SelectionKey key) {
+ synchronized (this) {
+ _key = key;
+ }
+ }
+
+ public void setSSLEngine(SSLEngine sslEngine) {
+ _sslEngine = sslEngine;
+ }
+
+ /**
+ * No user, so comment it out.
+ *
+ * Static methods for reading from a channel in case
+ * you need to add a client that doesn't require nio.
+ * @param ch channel to read from.
+ * @param bytebuffer to use.
+ * @return bytes read
+ * @throws IOException if not read to completion.
+ public static byte[] read(SocketChannel ch, ByteBuffer buff) throws IOException {
+ synchronized(buff) {
+ buff.clear();
+ buff.limit(4);
+
+ while (buff.hasRemaining()) {
+ if (ch.read(buff) == -1) {
+ throw new IOException("Connection closed with -1 on reading size.");
+ }
+ }
+
+ buff.flip();
+
+ int length = buff.getInt();
+ ByteArrayOutputStream output = new ByteArrayOutputStream(length);
+ WritableByteChannel outCh = Channels.newChannel(output);
+
+ int count = 0;
+ while (count < length) {
+ buff.clear();
+ int read = ch.read(buff);
+ if (read < 0) {
+ throw new IOException("Connection closed with -1 on reading data.");
+ }
+ count += read;
+ buff.flip();
+ outCh.write(buff);
+ }
+
+ return output.toByteArray();
+ }
+ }
+ */
+
+ private static void doWrite(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
+ SSLSession sslSession = sslEngine.getSession();
+ ByteBuffer pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ SSLEngineResult engResult;
+
+ ByteBuffer headBuf = ByteBuffer.allocate(4);
+
+ int totalLen = 0;
+ for (ByteBuffer buffer : buffers) {
+ totalLen += buffer.limit();
+ }
+
+ int processedLen = 0;
+ while (processedLen < totalLen) {
+ headBuf.clear();
+ pkgBuf.clear();
+ engResult = sslEngine.wrap(buffers, pkgBuf);
+ if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
+ engResult.getStatus() != SSLEngineResult.Status.OK) {
+ throw new IOException("SSL: SSLEngine return bad result! " + engResult);
+ }
+
+ processedLen = 0;
+ for (ByteBuffer buffer : buffers) {
+ processedLen += buffer.position();
+ }
+
+ int dataRemaining = pkgBuf.position();
+ int header = dataRemaining;
+ int headRemaining = 4;
+ pkgBuf.flip();
+ if (processedLen < totalLen) {
+ header = header | HEADER_FLAG_FOLLOWING;
+ }
+ headBuf.putInt(header);
+ headBuf.flip();
+
+ while (headRemaining > 0) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Writing Header " + headRemaining);
+ }
+ long count = ch.write(headBuf);
+ headRemaining -= count;
+ }
+ while (dataRemaining > 0) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Writing Data " + dataRemaining);
+ }
+ long count = ch.write(pkgBuf);
+ dataRemaining -= count;
+ }
+ }
+ }
+
+ /**
+ * write method to write to a socket. This method writes to completion so
+ * it doesn't follow the nio standard. We use this to make sure we write
+ * our own protocol.
+ *
+ * @param ch channel to write to.
+ * @param buffers buffers to write.
+ * @throws IOException if unable to write to completion.
+ */
+ public static void write(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
+ synchronized (ch) {
+ doWrite(ch, buffers, sslEngine);
+ }
+ }
+
+ /* SSL has limitation of 16k, we may need to split packets. 18000 is 16k + some extra SSL informations */
+ protected static final int MAX_SIZE_PER_PACKET = 18000;
+ protected static final int HEADER_FLAG_FOLLOWING = 0x10000;
+
+ public byte[] read(SocketChannel ch) throws IOException {
+ if (_readHeader) { // Start of a packet
+ if (_readBuffer.position() == 0) {
+ _readBuffer.limit(4);
+ }
+
+ if (ch.read(_readBuffer) == -1) {
+ throw new IOException("Connection closed with -1 on reading size.");
+ }
+
+ if (_readBuffer.hasRemaining()) {
+ s_logger.trace("Need to read the rest of the packet length");
+ return null;
+ }
+ _readBuffer.flip();
+ int header = _readBuffer.getInt();
+ int readSize = (short)header;
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Packet length is " + readSize);
+ }
+
+ if (readSize > MAX_SIZE_PER_PACKET) {
+ throw new IOException("Wrong packet size: " + readSize);
+ }
+
+ if (!_gotFollowingPacket) {
+ _plaintextBuffer = ByteBuffer.allocate(2000);
+ }
+
+ if ((header & HEADER_FLAG_FOLLOWING) != 0) {
+ _gotFollowingPacket = true;
+ } else {
+ _gotFollowingPacket = false;
+ }
+
+ _readBuffer.clear();
+ _readHeader = false;
+
+ if (_readBuffer.capacity() < readSize) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity());
+ }
+ _readBuffer = ByteBuffer.allocate(readSize);
+ }
+ _readBuffer.limit(readSize);
+ }
+
+ if (ch.read(_readBuffer) == -1) {
+ throw new IOException("Connection closed with -1 on read.");
+ }
+
+ if (_readBuffer.hasRemaining()) { // We're not done yet.
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Still has " + _readBuffer.remaining());
+ }
+ return null;
+ }
+
+ _readBuffer.flip();
+
+ ByteBuffer appBuf;
+
+ SSLSession sslSession = _sslEngine.getSession();
+ SSLEngineResult engResult;
+ int remaining = 0;
+
+ while (_readBuffer.hasRemaining()) {
+ remaining = _readBuffer.remaining();
+ appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
+ engResult = _sslEngine.unwrap(_readBuffer, appBuf);
+ if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
+ engResult.getStatus() != SSLEngineResult.Status.OK) {
+ throw new IOException("SSL: SSLEngine return bad result! " + engResult);
+ }
+ if (remaining == _readBuffer.remaining()) {
+ throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!");
+ }
+
+ appBuf.flip();
+ if (_plaintextBuffer.remaining() < appBuf.limit()) {
+ // We need to expand _plaintextBuffer for more data
+ ByteBuffer newBuffer = ByteBuffer.allocate(_plaintextBuffer.capacity() + appBuf.limit() * 5);
+ _plaintextBuffer.flip();
+ newBuffer.put(_plaintextBuffer);
+ _plaintextBuffer = newBuffer;
+ }
+ _plaintextBuffer.put(appBuf);
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Done with packet: " + appBuf.limit());
+ }
+ }
+
+ _readBuffer.clear();
+ _readHeader = true;
+
+ if (!_gotFollowingPacket) {
+ _plaintextBuffer.flip();
+ byte[] result = new byte[_plaintextBuffer.limit()];
+ _plaintextBuffer.get(result);
+ return result;
+ } else {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Waiting for more packets");
+ }
+ return null;
+ }
+ }
+
+ public void send(byte[] data) throws ClosedChannelException {
+ send(data, false);
+ }
+
+ public void send(byte[] data, boolean close) throws ClosedChannelException {
+ send(new ByteBuffer[] {ByteBuffer.wrap(data)}, close);
+ }
+
+ public void send(ByteBuffer[] data, boolean close) throws ClosedChannelException {
+ ByteBuffer[] item = new ByteBuffer[data.length + 1];
+ int remaining = 0;
+ for (int i = 0; i < data.length; i++) {
+ remaining += data[i].remaining();
+ item[i + 1] = data[i];
+ }
+
+ item[0] = ByteBuffer.allocate(4);
+ item[0].putInt(remaining);
+ item[0].flip();
+
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Sending packet of length " + remaining);
+ }
+
+ _writeQueue.add(item);
+ if (close) {
+ _writeQueue.add(new ByteBuffer[0]);
+ }
+ synchronized (this) {
+ if (_key == null) {
+ throw new ClosedChannelException();
+ }
+ _connection.change(SelectionKey.OP_WRITE, _key, null);
+ }
+ }
+
+ public void send(ByteBuffer[] data) throws ClosedChannelException {
+ send(data, false);
+ }
+
+ public synchronized void close() {
+ if (_key != null) {
+ _connection.close(_key);
+ }
+ }
+
+ public boolean write(SocketChannel ch) throws IOException {
+ ByteBuffer[] data = null;
+ while ((data = _writeQueue.poll()) != null) {
+ if (data.length == 0) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Closing connection requested");
+ }
+ return true;
+ }
+
+ ByteBuffer[] raw_data = new ByteBuffer[data.length - 1];
+ System.arraycopy(data, 1, raw_data, 0, data.length - 1);
+
+ doWrite(ch, raw_data, _sslEngine);
+ }
+ return false;
+ }
+
+ public InetSocketAddress getSocketAddress() {
+ return _addr;
+ }
+
+ public String getIpAddress() {
+ return _addr.getAddress().toString();
+ }
+
+ public synchronized void terminated() {
+ _key = null;
+ }
+
+ public synchronized void schedule(Task task) throws ClosedChannelException {
+ if (_key == null) {
+ throw new ClosedChannelException();
+ }
+ _connection.scheduleTask(task);
+ }
+
+ public static SSLContext initSSLContext(boolean isClient) throws GeneralSecurityException, IOException {
+ InputStream stream;
+ SSLContext sslContext = null;
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
+ KeyStore ks = KeyStore.getInstance("JKS");
+ TrustManager[] tms;
+
+ File confFile = PropertiesUtil.findConfigFile("db.properties");
+ if (null != confFile && !isClient) {
+ final String pass = DbProperties.getDbProperties().getProperty("db.cloud.keyStorePassphrase");
+ char[] passphrase = "vmops.com".toCharArray();
+ if (pass != null) {
+ passphrase = pass.toCharArray();
+ }
+ String confPath = confFile.getParent();
+ String keystorePath = confPath + keystoreFile;
+ if (new File(keystorePath).exists()) {
+ stream = new FileInputStream(keystorePath);
+ } else {
+ s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue.");
+ stream = NioConnection.class.getResourceAsStream("/cloud.keystore");
+ passphrase = "vmops.com".toCharArray();
+ }
+ ks.load(stream, passphrase);
+ stream.close();
+ kmf.init(ks, passphrase);
+ tmf.init(ks);
+ tms = tmf.getTrustManagers();
+ } else {
+ ks.load(null, null);
+ kmf.init(ks, null);
+ tms = new TrustManager[1];
+ tms[0] = new TrustAllManager();
+ }
+
+ sslContext = SSLUtils.getSSLContext();
+ sslContext.init(kmf.getKeyManagers(), tms, null);
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("SSL: SSLcontext has been initialized");
+ }
+
+ return sslContext;
+ }
+
+ public static void doHandshake(SocketChannel ch, SSLEngine sslEngine, boolean isClient) throws IOException {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("SSL: begin Handshake, isClient: " + isClient);
+ }
+
+ SSLEngineResult engResult;
+ SSLSession sslSession = sslEngine.getSession();
+ HandshakeStatus hsStatus;
+ ByteBuffer in_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ ByteBuffer in_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
+ ByteBuffer out_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ ByteBuffer out_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
+ int count;
+ ch.socket().setSoTimeout(60 * 1000);
+ InputStream inStream = ch.socket().getInputStream();
+ // Use readCh to make sure the timeout on reading is working
+ ReadableByteChannel readCh = Channels.newChannel(inStream);
+
+ if (isClient) {
+ hsStatus = SSLEngineResult.HandshakeStatus.NEED_WRAP;
+ } else {
+ hsStatus = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
+ }
+
+ while (hsStatus != SSLEngineResult.HandshakeStatus.FINISHED) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("SSL: Handshake status " + hsStatus);
+ }
+ engResult = null;
+ if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
+ out_pkgBuf.clear();
+ out_appBuf.clear();
+ out_appBuf.put("Hello".getBytes());
+ engResult = sslEngine.wrap(out_appBuf, out_pkgBuf);
+ out_pkgBuf.flip();
+ int remain = out_pkgBuf.limit();
+ while (remain != 0) {
+ remain -= ch.write(out_pkgBuf);
+ if (remain < 0) {
+ throw new IOException("Too much bytes sent?");
+ }
+ }
+ } else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
+ in_appBuf.clear();
+ // One packet may contained multiply operation
+ if (in_pkgBuf.position() == 0 || !in_pkgBuf.hasRemaining()) {
+ in_pkgBuf.clear();
+ count = 0;
+ try {
+ count = readCh.read(in_pkgBuf);
+ } catch (SocketTimeoutException ex) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("Handshake reading time out! Cut the connection");
+ }
+ count = -1;
+ }
+ if (count == -1) {
+ throw new IOException("Connection closed with -1 on reading size.");
+ }
+ in_pkgBuf.flip();
+ }
+ engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
+ ByteBuffer tmp_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ int loop_count = 0;
+ while (engResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
+ // The client is too slow? Cut it and let it reconnect
+ if (loop_count > 10) {
+ throw new IOException("Too many times in SSL BUFFER_UNDERFLOW, disconnect guest.");
+ }
+ // We need more packets to complete this operation
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("SSL: Buffer underflowed, getting more packets");
+ }
+ tmp_pkgBuf.clear();
+ count = ch.read(tmp_pkgBuf);
+ if (count == -1) {
+ throw new IOException("Connection closed with -1 on reading size.");
+ }
+ tmp_pkgBuf.flip();
+
+ in_pkgBuf.mark();
+ in_pkgBuf.position(in_pkgBuf.limit());
+ in_pkgBuf.limit(in_pkgBuf.limit() + tmp_pkgBuf.limit());
+ in_pkgBuf.put(tmp_pkgBuf);
+ in_pkgBuf.reset();
+
+ in_appBuf.clear();
+ engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
+ loop_count++;
+ }
+ } else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
+ Runnable run;
+ while ((run = sslEngine.getDelegatedTask()) != null) {
+ if (s_logger.isTraceEnabled()) {
+ s_logger.trace("SSL: Running delegated task!");
+ }
+ run.run();
+ }
+ } else if (hsStatus == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
+ throw new IOException("NOT a handshaking!");
+ }
+ if (engResult != null && engResult.getStatus() != SSLEngineResult.Status.OK) {
+ throw new IOException("Fail to handshake! " + engResult.getStatus());
+ }
+ if (engResult != null)
+ hsStatus = engResult.getHandshakeStatus();
+ else
+ hsStatus = sslEngine.getHandshakeStatus();
+ }
+ }
+
+}
[22/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/NioClient.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/NioClient.java b/utils/src/com/cloud/utils/nio/NioClient.java
deleted file mode 100644
index 2f742f9..0000000
--- a/utils/src/com/cloud/utils/nio/NioClient.java
+++ /dev/null
@@ -1,125 +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 com.cloud.utils.nio;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.security.GeneralSecurityException;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.utils.security.SSLUtils;
-
-public class NioClient extends NioConnection {
- private static final Logger s_logger = Logger.getLogger(NioClient.class);
-
- protected String _host;
- protected String _bindAddress;
- protected SocketChannel _clientConnection;
-
- public NioClient(String name, String host, int port, int workers, HandlerFactory factory) {
- super(name, port, workers, factory);
- _host = host;
- }
-
- public void setBindAddress(String ipAddress) {
- _bindAddress = ipAddress;
- }
-
- @Override
- protected void init() throws IOException {
- _selector = Selector.open();
- Task task = null;
-
- try {
- _clientConnection = SocketChannel.open();
- _clientConnection.configureBlocking(true);
- s_logger.info("Connecting to " + _host + ":" + _port);
-
- if (_bindAddress != null) {
- s_logger.info("Binding outbound interface at " + _bindAddress);
-
- InetSocketAddress bindAddr = new InetSocketAddress(_bindAddress, 0);
- _clientConnection.socket().bind(bindAddr);
- }
-
- InetSocketAddress peerAddr = new InetSocketAddress(_host, _port);
- _clientConnection.connect(peerAddr);
-
- SSLEngine sslEngine = null;
- // Begin SSL handshake in BLOCKING mode
- _clientConnection.configureBlocking(true);
-
- SSLContext sslContext = Link.initSSLContext(true);
- sslEngine = sslContext.createSSLEngine(_host, _port);
- sslEngine.setUseClientMode(true);
- sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols()));
-
- Link.doHandshake(_clientConnection, sslEngine, true);
- s_logger.info("SSL: Handshake done");
- s_logger.info("Connected to " + _host + ":" + _port);
-
- _clientConnection.configureBlocking(false);
- Link link = new Link(peerAddr, this);
- link.setSSLEngine(sslEngine);
- SelectionKey key = _clientConnection.register(_selector, SelectionKey.OP_READ);
- link.setKey(key);
- key.attach(link);
- // Notice we've already connected due to the handshake, so let's get the
- // remaining task done
- task = _factory.create(Task.Type.CONNECT, link, null);
- } catch (GeneralSecurityException e) {
- _selector.close();
- throw new IOException("Failed to initialise security", e);
- } catch (IOException e) {
- _selector.close();
- throw e;
- }
-
- _executor.execute(task);
- }
-
- @Override
- protected void registerLink(InetSocketAddress saddr, Link link) {
- // don't do anything.
- }
-
- @Override
- protected void unregisterLink(InetSocketAddress saddr) {
- // don't do anything.
- }
-
- @Override
- public void cleanUp() throws IOException {
- super.cleanUp();
- if (_clientConnection != null) {
- _clientConnection.close();
- }
- s_logger.info("NioClient connection closed");
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/NioConnection.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/NioConnection.java b/utils/src/com/cloud/utils/nio/NioConnection.java
deleted file mode 100644
index 4c66360..0000000
--- a/utils/src/com/cloud/utils/nio/NioConnection.java
+++ /dev/null
@@ -1,476 +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 com.cloud.utils.nio;
-
-import static com.cloud.utils.AutoCloseableUtil.closeAutoCloseable;
-
-import java.io.IOException;
-import java.net.ConnectException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.channels.CancelledKeyException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.utils.security.SSLUtils;
-
-import com.cloud.utils.concurrency.NamedThreadFactory;
-
-/**
- * NioConnection abstracts the NIO socket operations. The Java implementation
- * provides that.
- */
-public abstract class NioConnection implements Runnable {
- private static final Logger s_logger = Logger.getLogger(NioConnection.class);;
-
- protected Selector _selector;
- protected Thread _thread;
- protected boolean _isRunning;
- protected boolean _isStartup;
- protected int _port;
- protected List<ChangeRequest> _todos;
- protected HandlerFactory _factory;
- protected String _name;
- protected ExecutorService _executor;
-
- public NioConnection(String name, int port, int workers, HandlerFactory factory) {
- _name = name;
- _isRunning = false;
- _thread = null;
- _selector = null;
- _port = port;
- _factory = factory;
- _executor = new ThreadPoolExecutor(workers, 5 * workers, 1, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(name + "-Handler"));
- }
-
- public void start() {
- _todos = new ArrayList<ChangeRequest>();
-
- _thread = new Thread(this, _name + "-Selector");
- _isRunning = true;
- _thread.start();
- // Wait until we got init() done
- synchronized (_thread) {
- try {
- _thread.wait();
- } catch (InterruptedException e) {
- s_logger.warn("Interrupted start thread ", e);
- }
- }
- }
-
- public void stop() {
- _executor.shutdown();
- _isRunning = false;
- if (_thread != null) {
- _thread.interrupt();
- }
- }
-
- public boolean isRunning() {
- return _thread.isAlive();
- }
-
- public boolean isStartup() {
- return _isStartup;
- }
-
- @Override
- public void run() {
- synchronized (_thread) {
- try {
- init();
- } catch (ConnectException e) {
- s_logger.warn("Unable to connect to remote: is there a server running on port " + _port);
- return;
- } catch (IOException e) {
- s_logger.error("Unable to initialize the threads.", e);
- return;
- } catch (Exception e) {
- s_logger.error("Unable to initialize the threads due to unknown exception.", e);
- return;
- }
- _isStartup = true;
- _thread.notifyAll();
- }
-
- while (_isRunning) {
- try {
- _selector.select();
-
- // Someone is ready for I/O, get the ready keys
- Set<SelectionKey> readyKeys = _selector.selectedKeys();
- Iterator<SelectionKey> i = readyKeys.iterator();
-
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Keys Processing: " + readyKeys.size());
- }
- // Walk through the ready keys collection.
- while (i.hasNext()) {
- SelectionKey sk = i.next();
- i.remove();
-
- if (!sk.isValid()) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Selection Key is invalid: " + sk.toString());
- }
- Link link = (Link)sk.attachment();
- if (link != null) {
- link.terminated();
- } else {
- closeConnection(sk);
- }
- } else if (sk.isReadable()) {
- read(sk);
- } else if (sk.isWritable()) {
- write(sk);
- } else if (sk.isAcceptable()) {
- accept(sk);
- } else if (sk.isConnectable()) {
- connect(sk);
- }
- }
-
- s_logger.trace("Keys Done Processing.");
-
- processTodos();
- } catch (Throwable e) {
- s_logger.warn("Caught an exception but continuing on.", e);
- }
- }
- synchronized (_thread) {
- _isStartup = false;
- }
- }
-
- abstract void init() throws IOException;
-
- abstract void registerLink(InetSocketAddress saddr, Link link);
-
- abstract void unregisterLink(InetSocketAddress saddr);
-
- protected void accept(SelectionKey key) throws IOException {
- ServerSocketChannel serverSocketChannel = (ServerSocketChannel)key.channel();
-
- SocketChannel socketChannel = serverSocketChannel.accept();
- Socket socket = socketChannel.socket();
- socket.setKeepAlive(true);
-
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Connection accepted for " + socket);
- }
-
- // Begin SSL handshake in BLOCKING mode
- socketChannel.configureBlocking(true);
-
- SSLEngine sslEngine = null;
- try {
- SSLContext sslContext = Link.initSSLContext(false);
- sslEngine = sslContext.createSSLEngine();
- sslEngine.setUseClientMode(false);
- sslEngine.setNeedClientAuth(false);
- sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols()));
-
- Link.doHandshake(socketChannel, sslEngine, false);
-
- } catch (Exception e) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Socket " + socket + " closed on read. Probably -1 returned: " + e.getMessage());
- }
- closeAutoCloseable(socketChannel, "accepting socketChannel");
- closeAutoCloseable(socket, "opened socket");
- return;
- }
-
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: Handshake done");
- }
- socketChannel.configureBlocking(false);
- InetSocketAddress saddr = (InetSocketAddress)socket.getRemoteSocketAddress();
- Link link = new Link(saddr, this);
- link.setSSLEngine(sslEngine);
- link.setKey(socketChannel.register(key.selector(), SelectionKey.OP_READ, link));
- Task task = _factory.create(Task.Type.CONNECT, link, null);
- registerLink(saddr, link);
- _executor.execute(task);
- }
-
- protected void terminate(SelectionKey key) {
- Link link = (Link)key.attachment();
- closeConnection(key);
- if (link != null) {
- link.terminated();
- Task task = _factory.create(Task.Type.DISCONNECT, link, null);
- unregisterLink(link.getSocketAddress());
- _executor.execute(task);
- }
- }
-
- protected void read(SelectionKey key) throws IOException {
- Link link = (Link)key.attachment();
- try {
- SocketChannel socketChannel = (SocketChannel)key.channel();
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Reading from: " + socketChannel.socket().toString());
- }
- byte[] data = link.read(socketChannel);
- if (data == null) {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Packet is incomplete. Waiting for more.");
- }
- return;
- }
- Task task = _factory.create(Task.Type.DATA, link, data);
- _executor.execute(task);
- } catch (Exception e) {
- logDebug(e, key, 1);
- terminate(key);
- }
- }
-
- protected void logTrace(Exception e, SelectionKey key, int loc) {
- if (s_logger.isTraceEnabled()) {
- Socket socket = null;
- if (key != null) {
- SocketChannel ch = (SocketChannel)key.channel();
- if (ch != null) {
- socket = ch.socket();
- }
- }
-
- s_logger.trace("Location " + loc + ": Socket " + socket + " closed on read. Probably -1 returned.");
- }
- }
-
- protected void logDebug(Exception e, SelectionKey key, int loc) {
- if (s_logger.isDebugEnabled()) {
- Socket socket = null;
- if (key != null) {
- SocketChannel ch = (SocketChannel)key.channel();
- if (ch != null) {
- socket = ch.socket();
- }
- }
-
- s_logger.debug("Location " + loc + ": Socket " + socket + " closed on read. Probably -1 returned: " + e.getMessage());
- }
- }
-
- protected void processTodos() {
- List<ChangeRequest> todos;
- if (_todos.size() == 0) {
- return; // Nothing to do.
- }
-
- synchronized (this) {
- todos = _todos;
- _todos = new ArrayList<ChangeRequest>();
- }
-
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Todos Processing: " + todos.size());
- }
- SelectionKey key;
- for (ChangeRequest todo : todos) {
- switch (todo.type) {
- case ChangeRequest.CHANGEOPS:
- try {
- key = (SelectionKey)todo.key;
- if (key != null && key.isValid()) {
- if (todo.att != null) {
- key.attach(todo.att);
- Link link = (Link)todo.att;
- link.setKey(key);
- }
- key.interestOps(todo.ops);
- }
- } catch (CancelledKeyException e) {
- s_logger.debug("key has been cancelled");
- }
- break;
- case ChangeRequest.REGISTER:
- try {
- key = ((SocketChannel)(todo.key)).register(_selector, todo.ops, todo.att);
- if (todo.att != null) {
- Link link = (Link)todo.att;
- link.setKey(key);
- }
- } catch (ClosedChannelException e) {
- s_logger.warn("Couldn't register socket: " + todo.key);
- try {
- ((SocketChannel)(todo.key)).close();
- } catch (IOException ignore) {
- s_logger.info("[ignored] socket channel");
- } finally {
- Link link = (Link)todo.att;
- link.terminated();
- }
- }
- break;
- case ChangeRequest.CLOSE:
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Trying to close " + todo.key);
- }
- key = (SelectionKey)todo.key;
- closeConnection(key);
- if (key != null) {
- Link link = (Link)key.attachment();
- if (link != null) {
- link.terminated();
- }
- }
- break;
- default:
- s_logger.warn("Shouldn't be here");
- throw new RuntimeException("Shouldn't be here");
- }
- }
- s_logger.trace("Todos Done processing");
- }
-
- protected void connect(SelectionKey key) throws IOException {
- SocketChannel socketChannel = (SocketChannel)key.channel();
-
- try {
- socketChannel.finishConnect();
- key.interestOps(SelectionKey.OP_READ);
- Socket socket = socketChannel.socket();
- if (!socket.getKeepAlive()) {
- socket.setKeepAlive(true);
- }
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Connected to " + socket);
- }
- Link link = new Link((InetSocketAddress)socket.getRemoteSocketAddress(), this);
- link.setKey(key);
- key.attach(link);
- Task task = _factory.create(Task.Type.CONNECT, link, null);
- _executor.execute(task);
- } catch (IOException e) {
- logTrace(e, key, 2);
- terminate(key);
- }
- }
-
- protected void scheduleTask(Task task) {
- _executor.execute(task);
- }
-
- protected void write(SelectionKey key) throws IOException {
- Link link = (Link)key.attachment();
- try {
- if (s_logger.isTraceEnabled()) {
- s_logger.trace("Writing to " + link.getSocketAddress().toString());
- }
- boolean close = link.write((SocketChannel)key.channel());
- if (close) {
- closeConnection(key);
- link.terminated();
- } else {
- key.interestOps(SelectionKey.OP_READ);
- }
- } catch (Exception e) {
- logDebug(e, key, 3);
- terminate(key);
- }
- }
-
- protected void closeConnection(SelectionKey key) {
- if (key != null) {
- SocketChannel channel = (SocketChannel)key.channel();
- key.cancel();
- try {
- if (channel != null) {
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Closing socket " + channel.socket());
- }
- channel.close();
- }
- } catch (IOException ignore) {
- s_logger.info("[ignored] channel");
- }
- }
- }
-
- public void register(int ops, SocketChannel key, Object att) {
- ChangeRequest todo = new ChangeRequest(key, ChangeRequest.REGISTER, ops, att);
- synchronized (this) {
- _todos.add(todo);
- }
- _selector.wakeup();
- }
-
- public void change(int ops, SelectionKey key, Object att) {
- ChangeRequest todo = new ChangeRequest(key, ChangeRequest.CHANGEOPS, ops, att);
- synchronized (this) {
- _todos.add(todo);
- }
- _selector.wakeup();
- }
-
- public void close(SelectionKey key) {
- ChangeRequest todo = new ChangeRequest(key, ChangeRequest.CLOSE, 0, null);
- synchronized (this) {
- _todos.add(todo);
- }
- _selector.wakeup();
- }
-
- /* Release the resource used by the instance */
- public void cleanUp() throws IOException {
- if (_selector != null) {
- _selector.close();
- }
- }
-
- public class ChangeRequest {
- public static final int REGISTER = 1;
- public static final int CHANGEOPS = 2;
- public static final int CLOSE = 3;
-
- public Object key;
- public int type;
- public int ops;
- public Object att;
-
- public ChangeRequest(Object key, int type, int ops, Object att) {
- this.key = key;
- this.type = type;
- this.ops = ops;
- this.att = att;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/NioServer.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/NioServer.java b/utils/src/com/cloud/utils/nio/NioServer.java
deleted file mode 100644
index 98a4a51..0000000
--- a/utils/src/com/cloud/utils/nio/NioServer.java
+++ /dev/null
@@ -1,97 +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 com.cloud.utils.nio;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-import java.util.WeakHashMap;
-
-import org.apache.log4j.Logger;
-
-public class NioServer extends NioConnection {
- private final static Logger s_logger = Logger.getLogger(NioServer.class);
-
- protected InetSocketAddress _localAddr;
- private ServerSocketChannel _serverSocket;
-
- protected WeakHashMap<InetSocketAddress, Link> _links;
-
- public NioServer(String name, int port, int workers, HandlerFactory factory) {
- super(name, port, workers, factory);
- _localAddr = null;
- _links = new WeakHashMap<InetSocketAddress, Link>(1024);
- }
-
- @Override
- protected void init() throws IOException {
- _selector = SelectorProvider.provider().openSelector();
-
- _serverSocket = ServerSocketChannel.open();
- _serverSocket.configureBlocking(false);
-
- _localAddr = new InetSocketAddress(_port);
- _serverSocket.socket().bind(_localAddr);
-
- _serverSocket.register(_selector, SelectionKey.OP_ACCEPT, null);
-
- s_logger.info("NioConnection started and listening on " + _localAddr.toString());
- }
-
- @Override
- public void cleanUp() throws IOException {
- super.cleanUp();
- if (_serverSocket != null) {
- _serverSocket.close();
- }
- s_logger.info("NioConnection stopped on " + _localAddr.toString());
- }
-
- @Override
- protected void registerLink(InetSocketAddress addr, Link link) {
- _links.put(addr, link);
- }
-
- @Override
- protected void unregisterLink(InetSocketAddress saddr) {
- _links.remove(saddr);
- }
-
- /**
- * Sends the data to the address specified. If address is not already
- * connected, this does nothing and returns null. If address is already
- * connected, then it returns the attached object so the caller can
- * prepare for any responses.
- * @param saddr
- * @param data
- * @return null if not sent. attach object in link if sent.
- */
- public Object send(InetSocketAddress saddr, byte[] data) throws ClosedChannelException {
- Link link = _links.get(saddr);
- if (link == null) {
- return null;
- }
- link.send(data);
- return link.attachment();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/Task.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/Task.java b/utils/src/com/cloud/utils/nio/Task.java
deleted file mode 100644
index c77c703..0000000
--- a/utils/src/com/cloud/utils/nio/Task.java
+++ /dev/null
@@ -1,89 +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 com.cloud.utils.nio;
-
-import org.apache.log4j.Logger;
-
-/**
- * Task represents one todo item for the AgentManager or the AgentManager
- *
- */
-public abstract class Task implements Runnable {
- private static final Logger s_logger = Logger.getLogger(Task.class);
-
- public enum Type {
- CONNECT, // Process a new connection.
- DISCONNECT, // Process an existing connection disconnecting.
- DATA, // data incoming.
- CONNECT_FAILED, // Connection failed.
- OTHER // Allows other tasks to be defined by the caller.
- };
-
- Object _data;
- Type _type;
- Link _link;
-
- public Task(Type type, Link link, byte[] data) {
- _data = data;
- _type = type;
- _link = link;
- }
-
- public Task(Type type, Link link, Object data) {
- _data = data;
- _type = type;
- _link = link;
- }
-
- protected Task() {
- }
-
- public Type getType() {
- return _type;
- }
-
- public Link getLink() {
- return _link;
- }
-
- public byte[] getData() {
- return (byte[])_data;
- }
-
- public Object get() {
- return _data;
- }
-
- @Override
- public String toString() {
- return _type.toString();
- }
-
- abstract protected void doTask(Task task) throws Exception;
-
- @Override
- public final void run() {
- try {
- doTask(this);
- } catch (Throwable e) {
- s_logger.warn("Caught the following exception but pushing on", e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/nio/TrustAllManager.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/TrustAllManager.java b/utils/src/com/cloud/utils/nio/TrustAllManager.java
deleted file mode 100644
index 5dffd62..0000000
--- a/utils/src/com/cloud/utils/nio/TrustAllManager.java
+++ /dev/null
@@ -1,45 +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 com.cloud.utils.nio;
-
-public class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
- @Override
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
- return true;
- }
-
- public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
- return true;
- }
-
- @Override
- public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
- return;
- }
-
- @Override
- public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
- return;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
deleted file mode 100644
index bf001cd..0000000
--- a/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
+++ /dev/null
@@ -1,66 +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 com.cloud.utils.rest;
-
-import java.io.IOException;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethodBase;
-
-/**
- * Base 64 encoded authorization strategy. This implementation as opposed to
- * {@link RESTValidationStrategy} doesn't do a login after auth error, but instead
- * includes the encoded credentials in each request, instead of a cookie.
- */
-public class BasicEncodedRESTValidationStrategy extends RESTValidationStrategy {
-
- public BasicEncodedRESTValidationStrategy(final String host, final String adminuser, final String adminpass) {
- super();
- this.host = host;
- user = adminuser;
- password = adminpass;
- }
-
- public BasicEncodedRESTValidationStrategy() {
- }
-
- @Override
- public void executeMethod(final HttpMethodBase method, final HttpClient client,
- final String protocol)
- throws CloudstackRESTException, HttpException, IOException {
- if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
- throw new CloudstackRESTException("Hostname/credentials are null or empty");
- }
-
- final String encodedCredentials = encodeCredentials();
- method.setRequestHeader("Authorization", "Basic " + encodedCredentials);
- client.executeMethod(method);
- }
-
- private String encodeCredentials() {
- final String authString = user + ":" + password;
- final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
- final String authStringEnc = new String(authEncBytes);
- return authStringEnc;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/rest/CloudstackRESTException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/CloudstackRESTException.java b/utils/src/com/cloud/utils/rest/CloudstackRESTException.java
deleted file mode 100644
index 5985fa0..0000000
--- a/utils/src/com/cloud/utils/rest/CloudstackRESTException.java
+++ /dev/null
@@ -1,39 +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 com.cloud.utils.rest;
-
-public class CloudstackRESTException extends Exception {
-
- public CloudstackRESTException() {
- }
-
- public CloudstackRESTException(final String message) {
- super(message);
- }
-
- public CloudstackRESTException(final Throwable cause) {
- super(cause);
- }
-
- public CloudstackRESTException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/rest/RESTServiceConnector.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/com/cloud/utils/rest/RESTServiceConnector.java
deleted file mode 100644
index 6ededcb..0000000
--- a/utils/src/com/cloud/utils/rest/RESTServiceConnector.java
+++ /dev/null
@@ -1,395 +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 com.cloud.utils.rest;
-
-import com.google.gson.FieldNamingPolicy;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.reflect.TypeToken;
-import org.apache.cloudstack.utils.security.SSLUtils;
-import org.apache.cloudstack.utils.security.SecureSSLSocketFactory;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
-import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.httpclient.cookie.CookiePolicy;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.methods.StringRequestEntity;
-import org.apache.commons.httpclient.params.HttpConnectionParams;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
-import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
-import org.apache.log4j.Logger;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Type;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MalformedURLException;
-import java.net.Socket;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * This abstraction encapsulates client side code for REST service communication. It encapsulates
- * access in a delegate validation strategy. There may different implementations extending
- * {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
- *
- * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide
- * in the constructor a list of classes and a list of deserializers for these classes. These should
- * be a correlated so that Nth deserializer is correctly mapped to Nth class.
- */
-public class RESTServiceConnector {
- private static final String HTTPS = "https";
- protected static final String GET_METHOD_TYPE = "get";
- protected static final String DELETE_METHOD_TYPE = "delete";
- protected static final String PUT_METHOD_TYPE = "put";
- protected static final String POST_METHOD_TYPE = "post";
- private static final String TEXT_HTML_CONTENT_TYPE = "text/html";
- private static final String JSON_CONTENT_TYPE = "application/json";
- private static final String CONTENT_TYPE = "Content-Type";
- private static final int BODY_RESP_MAX_LEN = 1024;
- private static final int HTTPS_PORT = 443;
-
- private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class);
-
- protected final static String protocol = HTTPS;
-
- private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
-
- protected RESTValidationStrategy validation;
-
- private final HttpClient client;
-
- private final Gson gson;
-
-
- /**
- * Getter that may be needed only for test purpose
- *
- * @return
- */
- public Gson getGson() {
- return gson;
- }
-
- public RESTServiceConnector(final RESTValidationStrategy validationStrategy) {
- this(validationStrategy, null, null);
- }
-
- public RESTServiceConnector(final RESTValidationStrategy validationStrategy, final List<Class<?>> classList, final List<JsonDeserializer<?>> deserializerList) {
- validation = validationStrategy;
- client = createHttpClient();
- client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
-
- try {
- // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
- Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT));
- } catch (final IOException e) {
- s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
- }
-
- final GsonBuilder gsonBuilder = new GsonBuilder();
- if(classList != null && deserializerList != null) {
- for(int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
- gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
- }
- }
- gson = gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
- }
-
- public HttpClient createHttpClient() {
- return new HttpClient(s_httpClientManager);
- }
-
- public HttpMethod createMethod(final String type, final String uri) throws CloudstackRESTException {
- String url;
- try {
- url = new URL(protocol, validation.getHost(), uri).toString();
- } catch (final MalformedURLException e) {
- s_logger.error("Unable to build REST Service URL", e);
- throw new CloudstackRESTException("Unable to build Nicira API URL", e);
- }
-
- if (POST_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new PostMethod(url);
- } else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new GetMethod(url);
- } else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new DeleteMethod(url);
- } else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) {
- return new PutMethod(url);
- } else {
- throw new CloudstackRESTException("Requesting unknown method type");
- }
- }
-
- public void setControllerAddress(final String address) {
- validation.setHost(address);
- }
-
- public void setAdminCredentials(final String username, final String password) {
- validation.setUser(username);
- validation.setPassword(password);
- }
-
- public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
-
- final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri);
- pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
- try {
- pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
- } catch (final UnsupportedEncodingException e) {
- throw new CloudstackRESTException("Failed to encode json request body", e);
- }
-
- executeMethod(pm);
-
- if (pm.getStatusCode() != HttpStatus.SC_OK) {
- final String errorMessage = responseToErrorMessage(pm);
- pm.releaseConnection();
- s_logger.error("Failed to update object : " + errorMessage);
- throw new CloudstackRESTException("Failed to update object : " + errorMessage);
- }
- pm.releaseConnection();
- }
-
- @SuppressWarnings("unchecked")
- public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters)
- throws CloudstackRESTException {
-
- final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri);
- pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
- try {
- pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
- } catch (final UnsupportedEncodingException e) {
- throw new CloudstackRESTException("Failed to encode json request body", e);
- }
-
- executeMethod(pm);
-
- if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
- final String errorMessage = responseToErrorMessage(pm);
- pm.releaseConnection();
- s_logger.error("Failed to create object : " + errorMessage);
- throw new CloudstackRESTException("Failed to create object : " + errorMessage);
- }
-
- T result;
- try {
- result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
- } catch (final IOException e) {
- throw new CloudstackRESTException("Failed to decode json response body", e);
- } finally {
- pm.releaseConnection();
- }
-
- return result;
- }
-
- public void executeDeleteObject(final String uri) throws CloudstackRESTException {
- final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri);
- dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
-
- executeMethod(dm);
-
- if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
- final String errorMessage = responseToErrorMessage(dm);
- dm.releaseConnection();
- s_logger.error("Failed to delete object : " + errorMessage);
- throw new CloudstackRESTException("Failed to delete object : " + errorMessage);
- }
- dm.releaseConnection();
- }
-
- @SuppressWarnings("unchecked")
- public <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
- final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri);
- gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
- if (parameters != null && !parameters.isEmpty()) {
- final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
- for (final Entry<String, String> e : parameters.entrySet()) {
- nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
- }
- gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
- }
-
- executeMethod(gm);
-
- if (gm.getStatusCode() != HttpStatus.SC_OK) {
- final String errorMessage = responseToErrorMessage(gm);
- gm.releaseConnection();
- s_logger.error("Failed to retrieve object : " + errorMessage);
- throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
- }
-
- T returnValue;
- try {
- returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
- } catch (final IOException e) {
- s_logger.error("IOException while retrieving response body", e);
- throw new CloudstackRESTException(e);
- } finally {
- gm.releaseConnection();
- }
- return returnValue;
- }
-
- public void executeMethod(final HttpMethodBase method) throws CloudstackRESTException {
- try {
- validation.executeMethod(method, client, protocol);
- } catch (final HttpException e) {
- s_logger.error("HttpException caught while trying to connect to the REST Service", e);
- method.releaseConnection();
- throw new CloudstackRESTException("API call to REST Service Failed", e);
- } catch (final IOException e) {
- s_logger.error("IOException caught while trying to connect to the REST Service", e);
- method.releaseConnection();
- throw new CloudstackRESTException("API call to Nicira REST Service Failed", e);
- }
- }
-
- private String responseToErrorMessage(final HttpMethodBase method) {
- assert method.isRequestSent() : "no use getting an error message unless the request is sent";
-
- if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
- // The error message is the response content
- // Safety margin of 1024 characters, anything longer is probably useless
- // and will clutter the logs
- try {
- return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
- } catch (final IOException e) {
- s_logger.debug("Error while loading response body", e);
- }
- }
-
- // The default
- return method.getStatusText();
- }
-
- /* Some controllers use a self-signed certificate. The
- * TrustingProtocolSocketFactory will accept any provided
- * certificate when making an SSL connection to the SDN
- * Manager
- */
- private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
-
- private SSLSocketFactory ssf;
-
- public TrustingProtocolSocketFactory() throws IOException {
- // Create a trust manager that does not validate certificate chains
- final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- @Override
- public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
- // Trust always
- }
-
- @Override
- public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
- // Trust always
- }
- }};
-
- try {
- // Install the all-trusting trust manager
- final SSLContext sc = SSLUtils.getSSLContext();
- sc.init(null, trustAllCerts, new java.security.SecureRandom());
- ssf = new SecureSSLSocketFactory(sc);
- } catch (final KeyManagementException e) {
- throw new IOException(e);
- } catch (final NoSuchAlgorithmException e) {
- throw new IOException(e);
- }
- }
-
- @Override
- public Socket createSocket(final String host, final int port) throws IOException {
- SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
- socket.setEnabledProtocols(SSLUtils.getSupportedProtocols(socket.getEnabledProtocols()));
- return socket;
- }
-
- @Override
- public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
- Socket socket = ssf.createSocket(address, port, localAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- }
-
- @Override
- public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
- Socket s = ssf.createSocket(socket, host, port, autoClose);
- if (s instanceof SSLSocket) {
- ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
- }
- return s;
- }
-
- @Override
- public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
- throws IOException, UnknownHostException, ConnectTimeoutException {
- final int timeout = params.getConnectionTimeout();
- if (timeout == 0) {
- Socket socket = createSocket(host, port, localAddress, localPort);
- if (socket instanceof SSLSocket) {
- ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
- }
- return socket;
- } else {
- final Socket s = ssf.createSocket();
- if (s instanceof SSLSocket) {
- ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols()));
- }
- s.bind(new InetSocketAddress(localAddress, localPort));
- s.connect(new InetSocketAddress(host, port), timeout);
- return s;
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java
deleted file mode 100644
index 77ac8d0..0000000
--- a/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java
+++ /dev/null
@@ -1,165 +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 com.cloud.utils.rest;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.log4j.Logger;
-
-/**
- * Basic authentication strategy. This strategy needs user and password for authentication.
- *
- * A login URL is needed which will be used for login and getting the cookie to be
- * used in next requests. If an executeMethod request fails due to authorization it will try
- * to login, get the cookie and repeat the attempt to execute the method.
- */
-public class RESTValidationStrategy {
-
- private static final Logger s_logger = Logger.getLogger(RESTValidationStrategy.class);
-
- protected String host;
- protected String user;
- protected String password;
- protected String serverVersion;
- protected String loginUrl;
-
- public RESTValidationStrategy(final String host, final String user, final String password,
- final String serverVersion, final String loginUrl) {
- super();
- this.host = host;
- this.user = user;
- this.password = password;
- this.serverVersion = serverVersion;
- this.loginUrl = loginUrl;
- }
-
- public RESTValidationStrategy(final String loginUrl) {
- this.loginUrl = loginUrl;
- }
-
- public RESTValidationStrategy() {
- }
-
- public String getUser() {
- return user;
- }
-
- public void setUser(final String user) {
- this.user = user;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(final String password) {
- this.password = password;
- }
-
- public String getLoginUrl() {
- return loginUrl;
- }
-
- public void setLoginUrl(final String loginUrl) {
- this.loginUrl = loginUrl;
- }
-
- public String getHost() {
- return host;
- }
-
- public void setHost(final String host) {
- this.host = host;
- }
-
- public void executeMethod(final HttpMethodBase method, final HttpClient client,
- final String protocol)
- throws CloudstackRESTException, HttpException, IOException {
- if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
- throw new CloudstackRESTException("Hostname/credentials are null or empty");
- }
-
- client.executeMethod(method);
- if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
- method.releaseConnection();
- // login and try again
- login(protocol, client);
- client.executeMethod(method);
- }
- }
-
- /**
- * Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable.
- * <p>
- * The method returns false if the login failed or the connection could not be made.
- *
- */
- protected void login(final String protocol,
- final HttpClient client)
- throws CloudstackRESTException {
- String url;
-
- if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
- throw new CloudstackRESTException("Hostname/credentials are null or empty");
- }
-
- try {
- url = new URL(protocol, host, loginUrl).toString();
- } catch (final MalformedURLException e) {
- s_logger.error("Unable to build Nicira API URL", e);
- throw new CloudstackRESTException("Unable to build Nicira API URL", e);
- }
-
- final PostMethod pm = new PostMethod(url);
- pm.addParameter("username", user);
- pm.addParameter("password", password);
-
- try {
- client.executeMethod(pm);
- } catch (final HttpException e) {
- throw new CloudstackRESTException("REST Service API login failed ", e);
- } catch (final IOException e) {
- throw new CloudstackRESTException("REST Service API login failed ", e);
- } finally {
- pm.releaseConnection();
- }
-
- if (pm.getStatusCode() != HttpStatus.SC_OK) {
- s_logger.error("REST Service API login failed : " + pm.getStatusText());
- throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText());
- }
-
- // Extract the version for later use
- if (pm.getResponseHeader("Server") != null) {
- serverVersion = pm.getResponseHeader("Server").getValue();
- s_logger.debug("Server reports version " + serverVersion);
- }
-
- // Success; the cookie required for login is kept in _client
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/script/OutputInterpreter.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/script/OutputInterpreter.java b/utils/src/com/cloud/utils/script/OutputInterpreter.java
deleted file mode 100644
index 654f87e..0000000
--- a/utils/src/com/cloud/utils/script/OutputInterpreter.java
+++ /dev/null
@@ -1,141 +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 com.cloud.utils.script;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-
-import org.apache.log4j.Logger;
-
-/**
- */
-public abstract class OutputInterpreter {
- public boolean drain() {
- return false;
- }
-
- public String processError(BufferedReader reader) throws IOException {
- StringBuilder buff = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- buff.append(line);
- }
- return buff.toString();
- }
-
- public abstract String interpret(BufferedReader reader) throws IOException;
-
- public static final OutputInterpreter NoOutputParser = new OutputInterpreter() {
- @Override
- public String interpret(BufferedReader reader) throws IOException {
- return null;
- }
- };
-
- public static class TimedOutLogger extends OutputInterpreter {
- private static final Logger s_logger = Logger.getLogger(TimedOutLogger.class);
- Process _process;
-
- public TimedOutLogger(Process process) {
- _process = process;
- }
-
- @Override
- public boolean drain() {
- return true;
- }
-
- @Override
- public String interpret(BufferedReader reader) throws IOException {
- StringBuilder buff = new StringBuilder();
-
- while (reader.ready()) {
- buff.append(reader.readLine());
- }
-
- _process.destroy();
-
- try {
- while (reader.ready()) {
- buff.append(reader.readLine());
- }
- } catch (IOException e) {
- s_logger.info("[ignored] can not append line to buffer",e);
- }
-
- return buff.toString();
- }
- }
-
- public static class OutputLogger extends OutputInterpreter {
- Logger _logger;
-
- public OutputLogger(Logger logger) {
- _logger = logger;
- }
-
- @Override
- public String interpret(BufferedReader reader) throws IOException {
- StringBuilder builder = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- builder.append(line).append("\n");
- }
- if (builder.length() > 0) {
- _logger.debug(builder.toString());
- }
- return null;
- }
- }
-
- public static class OneLineParser extends OutputInterpreter {
- String line = null;
-
- @Override
- public String interpret(BufferedReader reader) throws IOException {
- line = reader.readLine();
- return null;
- }
-
- public String getLine() {
- return line;
- }
- };
-
- public static class AllLinesParser extends OutputInterpreter {
- String allLines = null;
-
- @Override
- public String interpret(BufferedReader reader) throws IOException {
- StringBuilder builder = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- builder.append(line).append("\n");
- }
- allLines = builder.toString();
- return null;
- }
-
- public String getLines() {
- return allLines;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/script/Script.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java
deleted file mode 100644
index 487c62c..0000000
--- a/utils/src/com/cloud/utils/script/Script.java
+++ /dev/null
@@ -1,502 +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 com.cloud.utils.script;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.PropertiesUtil;
-import com.cloud.utils.concurrency.NamedThreadFactory;
-import com.cloud.utils.script.OutputInterpreter.TimedOutLogger;
-
-public class Script implements Callable<String> {
- private static final Logger s_logger = Logger.getLogger(Script.class);
-
- private final Logger _logger;
-
- public static final String ERR_EXECUTE = "execute.error";
- public static final String ERR_TIMEOUT = "timeout";
- private int _defaultTimeout = 3600 * 1000; /* 1 hour */
- private volatile boolean _isTimeOut = false;
-
- private boolean _passwordCommand = false;
-
- private static final ScheduledExecutorService s_executors = Executors.newScheduledThreadPool(10, new NamedThreadFactory("Script"));
-
- String _workDir;
- ArrayList<String> _command;
- long _timeout;
- Process _process;
- Thread _thread;
-
- public int getExitValue() {
- return _process.exitValue();
- }
-
- public Script(String command, long timeout, Logger logger) {
- _command = new ArrayList<String>();
- _command.add(command);
- _timeout = timeout;
- if (_timeout == 0) {
- /* always using default timeout 1 hour to avoid thread hang */
- _timeout = _defaultTimeout;
- }
- _process = null;
- _logger = logger != null ? logger : s_logger;
- }
-
- public Script(boolean runWithSudo, String command, long timeout, Logger logger) {
- this(command, timeout, logger);
- if (runWithSudo) {
- _command.add(0, "sudo");
- }
- }
-
- public Script(String command, Logger logger) {
- this(command, 0, logger);
- }
-
- public Script(String command) {
- this(command, 0, s_logger);
- }
-
- public Script(String command, long timeout) {
- this(command, timeout, s_logger);
- }
-
- public void add(String... params) {
- for (String param : params) {
- _command.add(param);
- }
- }
-
- public void add(String param) {
- _command.add(param);
- }
-
- public Script set(String name, String value) {
- _command.add(name);
- _command.add(value);
- return this;
- }
-
- public void setWorkDir(String workDir) {
- _workDir = workDir;
- }
-
- protected String buildCommandLine(String[] command) {
- StringBuilder builder = new StringBuilder();
- boolean obscureParam = false;
- for (int i = 0; i < command.length; i++) {
- String cmd = command[i];
- if (obscureParam) {
- builder.append("******").append(" ");
- obscureParam = false;
- } else {
- builder.append(command[i]).append(" ");
- }
-
- if ("-y".equals(cmd) || "-z".equals(cmd)) {
- obscureParam = true;
- _passwordCommand = true;
- }
- }
- return builder.toString();
- }
-
- protected String buildCommandLine(List<String> command) {
- StringBuilder builder = new StringBuilder();
- boolean obscureParam = false;
- for (String cmd : command) {
- if (obscureParam) {
- builder.append("******").append(" ");
- obscureParam = false;
- } else {
- builder.append(cmd).append(" ");
- }
-
- if ("-y".equals(cmd) || "-z".equals(cmd)) {
- obscureParam = true;
- _passwordCommand = true;
- }
- }
- return builder.toString();
- }
-
- public String execute() {
- return execute(new OutputInterpreter.OutputLogger(_logger));
- }
-
- @Override
- public String toString() {
- String[] command = _command.toArray(new String[_command.size()]);
- return buildCommandLine(command);
- }
-
- static String stackTraceAsString(Throwable throwable) {
- //TODO: a StringWriter is bit to heavy weight
- try(StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out);) {
- throwable.printStackTrace(writer);
- return out.toString();
- } catch (IOException e) {
- return "";
- }
- }
-
- public String execute(OutputInterpreter interpreter) {
- String[] command = _command.toArray(new String[_command.size()]);
-
- if (_logger.isDebugEnabled()) {
- _logger.debug("Executing: " + buildCommandLine(command));
- }
-
- try {
- ProcessBuilder pb = new ProcessBuilder(command);
- pb.redirectErrorStream(true);
- if (_workDir != null)
- pb.directory(new File(_workDir));
-
- _process = pb.start();
- if (_process == null) {
- _logger.warn("Unable to execute: " + buildCommandLine(command));
- return "Unable to execute the command: " + command[0];
- }
-
- BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));
-
- _thread = Thread.currentThread();
- ScheduledFuture<String> future = null;
- if (_timeout > 0) {
- future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
- }
-
- Task task = null;
- if (interpreter != null && interpreter.drain()) {
- task = new Task(interpreter, ir);
- s_executors.execute(task);
- }
-
- while (true) {
- try {
- if (_process.waitFor() == 0) {
- _logger.debug("Execution is successful.");
- if (interpreter != null) {
- return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
- } else {
- // null return exitValue apparently
- return String.valueOf(_process.exitValue());
- }
- } else {
- break;
- }
- } catch (InterruptedException e) {
- if (!_isTimeOut) {
- /*
- * This is not timeout, we are interrupted by others,
- * continue
- */
- _logger.debug("We are interrupted but it's not a timeout, just continue");
- continue;
- }
-
- TimedOutLogger log = new TimedOutLogger(_process);
- Task timedoutTask = new Task(log, ir);
-
- timedoutTask.run();
- if (!_passwordCommand) {
- _logger.warn("Timed out: " + buildCommandLine(command) + ". Output is: " + timedoutTask.getResult());
- } else {
- _logger.warn("Timed out: " + buildCommandLine(command));
- }
-
- return ERR_TIMEOUT;
- } finally {
- if (future != null) {
- future.cancel(false);
- }
- Thread.interrupted();
- }
- }
-
- _logger.debug("Exit value is " + _process.exitValue());
-
- BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);
-
- String error;
- if (interpreter != null) {
- error = interpreter.processError(reader);
- } else {
- error = String.valueOf(_process.exitValue());
- }
-
- if (_logger.isDebugEnabled()) {
- _logger.debug(error);
- }
- return error;
- } catch (SecurityException ex) {
- _logger.warn("Security Exception....not running as root?", ex);
- return stackTraceAsString(ex);
- } catch (Exception ex) {
- _logger.warn("Exception: " + buildCommandLine(command), ex);
- return stackTraceAsString(ex);
- } finally {
- if (_process != null) {
- IOUtils.closeQuietly(_process.getErrorStream());
- IOUtils.closeQuietly(_process.getOutputStream());
- IOUtils.closeQuietly(_process.getInputStream());
- _process.destroy();
- }
- }
- }
-
- @Override
- public String call() {
- try {
- _logger.trace("Checking exit value of process");
- _process.exitValue();
- _logger.trace("Script ran within the alloted time");
- } catch (IllegalThreadStateException e) {
- _logger.warn("Interrupting script.");
- _isTimeOut = true;
- _thread.interrupt();
- }
- return null;
- }
-
- public static class Task implements Runnable {
- OutputInterpreter interpreter;
- BufferedReader reader;
- String result;
- boolean done;
-
- public Task(OutputInterpreter interpreter, BufferedReader reader) {
- this.interpreter = interpreter;
- this.reader = reader;
- result = null;
- }
-
- @Override
- public void run() {
- synchronized(this) {
- done = false;
- try {
- result = interpreter.interpret(reader);
- } catch (IOException ex) {
- result = stackTraceAsString(ex);
- } catch (Exception ex) {
- result = stackTraceAsString(ex);
- } finally {
- done = true;
- notifyAll();
- IOUtils.closeQuietly(reader);
- }
- }
- }
-
- public synchronized String getResult() throws InterruptedException {
- if (!done) {
- wait();
- }
- return result;
- }
- }
-
- public static String findScript(String path, String script) {
- s_logger.debug("Looking for " + script + " in the classpath");
-
- URL url = ClassLoader.getSystemResource(script);
- s_logger.debug("System resource: " + url);
- File file = null;
- if (url != null) {
- file = new File(url.getFile());
- s_logger.debug("Absolute path = " + file.getAbsolutePath());
- return file.getAbsolutePath();
- }
-
- if (path == null) {
- s_logger.warn("No search path specified, unable to look for " + script);
- return null;
- }
- path = path.replace("/", File.separator);
-
- /**
- * Look in WEB-INF/classes of the webapp
- * URI workaround the URL encoding of url.getFile
- */
- if (path.endsWith(File.separator)) {
- url = Script.class.getClassLoader().getResource(path + script);
- } else {
- url = Script.class.getClassLoader().getResource(path + File.separator + script);
- }
- s_logger.debug("Classpath resource: " + url);
- if (url != null) {
- try {
- file = new File(new URI(url.toString()).getPath());
- s_logger.debug("Absolute path = " + file.getAbsolutePath());
- return file.getAbsolutePath();
- } catch (URISyntaxException e) {
- s_logger.warn("Unable to convert " + url.toString() + " to a URI");
- }
- }
-
- if (path.endsWith(File.separator)) {
- path = path.substring(0, path.lastIndexOf(File.separator));
- }
-
- if (path.startsWith(File.separator)) {
- // Path given was absolute so we assume the caller knows what they want.
- file = new File(path + File.separator + script);
- return file.exists() ? file.getAbsolutePath() : null;
- }
-
- s_logger.debug("Looking for " + script);
- String search = null;
- for (int i = 0; i < 3; i++) {
- if (i == 0) {
- String cp = Script.class.getResource(Script.class.getSimpleName() + ".class").toExternalForm();
- int begin = cp.indexOf(File.separator);
-
- // work around with the inconsistency of java classpath and file separator on Windows 7
- if (begin < 0)
- begin = cp.indexOf('/');
-
- int endBang = cp.lastIndexOf("!");
- int end = cp.lastIndexOf(File.separator, endBang);
- if (end < 0)
- end = cp.lastIndexOf('/', endBang);
- if (end < 0)
- cp = cp.substring(begin);
- else
- cp = cp.substring(begin, end);
-
- s_logger.debug("Current binaries reside at " + cp);
- search = cp;
- } else if (i == 1) {
- s_logger.debug("Searching in environment.properties");
- try {
- final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
- if (propsFile == null) {
- s_logger.debug("environment.properties could not be opened");
- } else {
- final Properties props = PropertiesUtil.loadFromFile(propsFile);
- search = props.getProperty("paths.script");
- }
- } catch (IOException e) {
- s_logger.debug("environment.properties could not be opened");
- continue;
- }
- s_logger.debug("environment.properties says scripts should be in " + search);
- } else {
- s_logger.debug("Searching in the current directory");
- search = ".";
- }
-
- search += File.separatorChar + path + File.separator;
- do {
- search = search.substring(0, search.lastIndexOf(File.separator));
- file = new File(search + File.separator + script);
- s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
- } while (!file.exists() && search.lastIndexOf(File.separator) != -1);
-
- if (file.exists()) {
- return file.getAbsolutePath();
- }
-
- }
-
- search = System.getProperty("paths.script");
-
- search += File.separatorChar + path + File.separator;
- do {
- search = search.substring(0, search.lastIndexOf(File.separator));
- file = new File(search + File.separator + script);
- s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
- } while (!file.exists() && search.lastIndexOf(File.separator) != -1);
-
- if (file.exists()) {
- return file.getAbsolutePath();
- }
-
- s_logger.warn("Unable to find script " + script);
- return null;
- }
-
- public static String runSimpleBashScript(String command) {
- return Script.runSimpleBashScript(command, 0);
- }
-
- public static String runSimpleBashScript(String command, int timeout) {
-
- Script s = new Script("/bin/bash", timeout);
- s.add("-c");
- s.add(command);
-
- OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
- if (s.execute(parser) != null)
- return null;
-
- String result = parser.getLine();
- if (result == null || result.trim().isEmpty())
- return null;
- else
- return result.trim();
- }
-
- public static int runSimpleBashScriptForExitValue(String command) {
- return runSimpleBashScriptForExitValue(command, 0);
- }
-
- public static int runSimpleBashScriptForExitValue(String command, int timeout) {
-
- Script s = new Script("/bin/bash", timeout);
- s.add("-c");
- s.add(command);
-
- String result = s.execute(null);
- if (result == null || result.trim().isEmpty())
- return -1;
- else {
- try {
- return Integer.parseInt(result.trim());
- } catch (NumberFormatException e) {
- return -1;
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/script/Script2.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/script/Script2.java b/utils/src/com/cloud/utils/script/Script2.java
deleted file mode 100644
index 03c0e0d..0000000
--- a/utils/src/com/cloud/utils/script/Script2.java
+++ /dev/null
@@ -1,70 +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 com.cloud.utils.script;
-
-import java.util.HashMap;
-
-import org.apache.log4j.Logger;
-
-public class Script2 extends Script {
- HashMap<String, ParamType> _params = new HashMap<String, ParamType>();
-
- public static enum ParamType {
- NORMAL, PASSWORD,
- }
-
- public Script2(String command, Logger logger) {
- this(command, 0, logger);
- }
-
- public Script2(String command, long timeout, Logger logger) {
- super(command, timeout, logger);
- }
-
- public void add(String param, ParamType type) {
- _params.put(param, type);
- super.add(param);
- }
-
- @Override
- public void add(String param) {
- add(param, ParamType.NORMAL);
- }
-
- private ParamType getType(String cmd) {
- return _params.get(cmd);
- }
-
- @Override
- protected String buildCommandLine(String[] command) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < command.length; i++) {
- String cmd = command[i];
- ParamType type = getType(cmd);
- if (type == ParamType.PASSWORD) {
- builder.append("******").append(" ");
- } else {
- builder.append(command[i]).append(" ");
- }
- }
-
- return builder.toString();
- }
-}
[39/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java
deleted file mode 100644
index e614db6..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java
+++ /dev/null
@@ -1,58 +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 com.cloud.network.nicira;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-@SuppressWarnings("serial")
-public abstract class AccessRule implements Serializable {
-
- public static final String ETHERTYPE_IPV4 = "IPv4";
- public static final String ETHERTYPE_IPV6 = "IPv6";
-
- protected String ethertype = ETHERTYPE_IPV4;
-
- protected int protocol;
-
-
- public String getEthertype() {
- return ethertype;
- }
-
- public void setEthertype(String ethertype) {
- this.ethertype = ethertype;
- }
-
- public int getProtocol() {
- return protocol;
- }
-
- public void setProtocol(int protocol) {
- this.protocol = protocol;
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java
deleted file mode 100644
index 870124e..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java
+++ /dev/null
@@ -1,23 +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 com.cloud.network.nicira;
-
-public class Acl extends AccessConfiguration<AclRule> {
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java
deleted file mode 100644
index 8a4c053..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java
+++ /dev/null
@@ -1,209 +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 com.cloud.network.nicira;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-
-@SuppressWarnings("serial")
-public class AclRule extends AccessRule {
-
- public static final String ETHERTYPE_ARP = "ARP";
-
- /**
- * @TODO Convert this String into Enum and check the JSON communication still works
- */
- protected String action;
-
- protected String sourceIpPrefix;
-
- protected String destinationIpPrefix;
-
- protected String sourceMacAddress;
-
- protected String destinationMacAddress;
-
- protected Integer sourcePortRangeMin;
-
- protected Integer destinationPortRangeMin;
-
- protected Integer sourcePortRangeMax;
-
- protected Integer destinationPortRangeMax;
-
- protected Integer icmpProtocolCode;
-
- protected Integer icmpProtocolType;
-
- protected int order;
-
-
- /**
- * Default constructor
- */
- public AclRule() {
- }
-
- /**
- * Fully parameterized constructor
- */
- public AclRule(String ethertype, int protocol, String action, String sourceMacAddress,
- String destinationMacAddress, String sourceIpPrefix, String destinationIpPrefix,
- Integer sourcePortRangeMin, Integer sourcePortRangeMax,
- Integer destinationPortRangeMin, Integer destinationPortRangeMax,
- int order, Integer icmpProtocolCode, Integer icmpProtocolType) {
- this.ethertype = ethertype;
- this.protocol = protocol;
- this.action = action;
- this.sourceMacAddress = sourceMacAddress;
- this.destinationMacAddress = destinationMacAddress;
- this.sourceIpPrefix = sourceIpPrefix;
- this.destinationIpPrefix = destinationIpPrefix;
- this.sourcePortRangeMin = sourcePortRangeMin;
- this.sourcePortRangeMax = sourcePortRangeMax;
- this.destinationPortRangeMin = destinationPortRangeMin;
- this.destinationPortRangeMax = destinationPortRangeMax;
- this.order = order;
- this.icmpProtocolCode = icmpProtocolCode;
- this.icmpProtocolType = icmpProtocolType;
- }
-
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getSourceIpPrefix() {
- return sourceIpPrefix;
- }
-
- public void setSourceIpPrefix(String sourceIpPrefix) {
- this.sourceIpPrefix = sourceIpPrefix;
- }
-
- public String getDestinationIpPrefix() {
- return destinationIpPrefix;
- }
-
- public void setDestinationIpPrefix(String destinationIpPrefix) {
- this.destinationIpPrefix = destinationIpPrefix;
- }
-
- public String getSourceMacAddress() {
- return sourceMacAddress;
- }
-
- public void setSourceMacAddress(String sourceMacAddress) {
- this.sourceMacAddress = sourceMacAddress;
- }
-
- public String getDestinationMacAddress() {
- return destinationMacAddress;
- }
-
- public void setDestinationMacAddress(String destinationMacAddress) {
- this.destinationMacAddress = destinationMacAddress;
- }
-
- public Integer getSourcePortRangeMin() {
- return sourcePortRangeMin;
- }
-
- public void setSourcePortRangeMin(Integer sourcePortRangeMin) {
- this.sourcePortRangeMin = sourcePortRangeMin;
- }
-
- public Integer getDestinationPortRangeMin() {
- return destinationPortRangeMin;
- }
-
- public void setDestinationPortRangeMin(Integer destinationPortRangeMin) {
- this.destinationPortRangeMin = destinationPortRangeMin;
- }
-
- public Integer getSourcePortRangeMax() {
- return sourcePortRangeMax;
- }
-
- public void setSourcePortRangeMax(Integer sourcePortRangeMax) {
- this.sourcePortRangeMax = sourcePortRangeMax;
- }
-
- public Integer getDestinationPortRangeMax() {
- return destinationPortRangeMax;
- }
-
- public void setDestinationPortRangeMax(Integer destinationPortRangeMax) {
- this.destinationPortRangeMax = destinationPortRangeMax;
- }
-
- public Integer getIcmpProtocolCode() {
- return icmpProtocolCode;
- }
-
- public void setIcmpProtocolCode(Integer icmpProtocolCode) {
- this.icmpProtocolCode = icmpProtocolCode;
- }
-
- public Integer getIcmpProtocolType() {
- return icmpProtocolType;
- }
-
- public void setIcmpProtocolType(Integer icmpProtocolType) {
- this.icmpProtocolType = icmpProtocolType;
- }
-
- public int getOrder() {
- return order;
- }
-
- public void setOrder(int order) {
- this.order = order;
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 31)
- .append(ethertype).append(protocol)
- .toHashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == null) {
- return false;
- }
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof AclRule)) {
- return false;
- }
- AclRule another = (AclRule) obj;
- return new EqualsBuilder()
- .append(ethertype, another.ethertype)
- .append(protocol, another.protocol)
- .isEquals();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java
deleted file mode 100644
index 90ff131..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java
+++ /dev/null
@@ -1,24 +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 com.cloud.network.nicira;
-
-public abstract class Attachment {
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java
deleted file mode 100644
index afcd233..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java
+++ /dev/null
@@ -1,85 +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 com.cloud.network.nicira;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-public abstract class BaseNiciraEntity implements Serializable {
- protected String href;
- protected String schema;
- protected String uuid;
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(final String uuid) {
- this.uuid = uuid;
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(final String href) {
- this.href = href;
- }
-
- public String getSchema() {
- return schema;
- }
-
- public void setSchema(final String schema) {
- this.schema = schema;
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 31)
- .append(this.getClass())
- .append(uuid)
- .toHashCode();
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (obj == null) {
- return false;
- }
- if (obj == this) {
- return true;
- }
- if (!(this.getClass().isInstance(obj))) {
- return false;
- }
- final BaseNiciraEntity another = (BaseNiciraEntity) obj;
- return new EqualsBuilder().append(uuid, another.uuid).isEquals();
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java
deleted file mode 100644
index 0e21ddb..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java
+++ /dev/null
@@ -1,44 +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 com.cloud.network.nicira;
-
-import java.util.List;
-
-public abstract class BaseNiciraNamedEntity extends BaseNiciraEntity {
-
- protected String displayName;
- protected List<NiciraNvpTag> tags;
-
- public String getDisplayName() {
- return displayName;
- }
-
- public void setDisplayName(final String displayName) {
- this.displayName = displayName;
- }
-
- public List<NiciraNvpTag> getTags() {
- return tags;
- }
-
- public void setTags(final List<NiciraNvpTag> tags) {
- this.tags = tags;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java
deleted file mode 100644
index 8d6399e..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java
+++ /dev/null
@@ -1,87 +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 com.cloud.network.nicira;
-
-public class ControlClusterStatus {
- private String clusterStatus;
- private Stats nodeStats;
- private Stats queueStats;
- private Stats portStats;
- private Stats routerportStats;
- private Stats switchStats;
- private Stats zoneStats;
- private Stats routerStats;
- private Stats securityProfileStats;
-
- public String getClusterStatus() {
- return clusterStatus;
- }
-
- public Stats getNodeStats() {
- return nodeStats;
- }
-
- public Stats getLqueueStats() {
- return queueStats;
- }
-
- public Stats getLportStats() {
- return portStats;
- }
-
- public Stats getLrouterportStats() {
- return routerportStats;
- }
-
- public Stats getLswitchStats() {
- return switchStats;
- }
-
- public Stats getZoneStats() {
- return zoneStats;
- }
-
- public Stats getLrouterStats() {
- return routerStats;
- }
-
- public Stats getSecurityProfileStats() {
- return securityProfileStats;
- }
-
- public class Stats {
- private int errorStateCount;
- private int registeredCount;
- private int activeCount;
-
- public int getErrorStateCount() {
- return errorStateCount;
- }
-
- public int getRegisteredCount() {
- return registeredCount;
- }
-
- public int getActiveCount() {
- return activeCount;
- }
-
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java
deleted file mode 100644
index a0d5afc..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java
+++ /dev/null
@@ -1,113 +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 com.cloud.network.nicira;
-
-public class DestinationNatRule extends NatRule {
- private String toDestinationIpAddress;
- private Integer toDestinationPort;
-
- public DestinationNatRule() {
- setType("DestinationNatRule");
- }
-
- public String getToDestinationIpAddress() {
- return toDestinationIpAddress;
- }
-
- public void setToDestinationIpAddress(final String toDestinationIpAddress) {
- this.toDestinationIpAddress = toDestinationIpAddress;
- }
-
- public Integer getToDestinationPort() {
- return toDestinationPort;
- }
-
- public void setToDestinationPort(final Integer toDestinationPort) {
- this.toDestinationPort = toDestinationPort;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((toDestinationIpAddress == null) ? 0 : toDestinationIpAddress.hashCode());
- result = prime * result + ((toDestinationPort == null) ? 0 : toDestinationPort.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!super.equals(obj)) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- DestinationNatRule other = (DestinationNatRule)obj;
- if (toDestinationIpAddress == null) {
- if (other.toDestinationIpAddress != null) {
- return false;
- }
- } else if (!toDestinationIpAddress.equals(other.toDestinationIpAddress)) {
- return false;
- }
- if (toDestinationPort == null) {
- if (other.toDestinationPort != null) {
- return false;
- }
- } else if (!toDestinationPort.equals(other.toDestinationPort)) {
- return false;
- }
- return true;
- }
-
- @Override
- public boolean equalsIgnoreUuid(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!super.equalsIgnoreUuid(obj)) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- DestinationNatRule other = (DestinationNatRule)obj;
- if (toDestinationIpAddress == null) {
- if (other.toDestinationIpAddress != null) {
- return false;
- }
- } else if (!toDestinationIpAddress.equals(other.toDestinationIpAddress)) {
- return false;
- }
- if (toDestinationPort == null) {
- if (other.toDestinationPort != null) {
- return false;
- }
- } else if (!toDestinationPort.equals(other.toDestinationPort)) {
- return false;
- }
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java
deleted file mode 100644
index a1d5ce4..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java
+++ /dev/null
@@ -1,55 +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 com.cloud.network.nicira;
-
-/**
- *
- */
-public class L3GatewayAttachment extends Attachment {
- private String l3GatewayServiceUuid;
- private final String type = "L3GatewayAttachment";
- private Long vlanId;
-
- public L3GatewayAttachment(String l3GatewayServiceUuid) {
- this.l3GatewayServiceUuid = l3GatewayServiceUuid;
- }
-
- public L3GatewayAttachment(final String l3GatewayServiceUuid, final long vlanId) {
- this.l3GatewayServiceUuid = l3GatewayServiceUuid;
- this.vlanId = vlanId;
- }
-
- public String getL3GatewayServiceUuid() {
- return l3GatewayServiceUuid;
- }
-
- public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) {
- this.l3GatewayServiceUuid = l3GatewayServiceUuid;
- }
-
- public long getVlanId() {
- return vlanId;
- }
-
- public void setVlanId(long vlanId) {
- this.vlanId = vlanId;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java
deleted file mode 100644
index edc9351..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java
+++ /dev/null
@@ -1,71 +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 com.cloud.network.nicira;
-
-
-/**
- *
- */
-public class LogicalRouter extends BaseNiciraNamedEntity {
- public static final String REPLICATION_MODE_SERVICE = "service";
- public static final String REPLICATION_MODE_SOURCE = "source";
-
- private final String type = "LogicalRouterConfig";
- private RoutingConfig routingConfig;
- private boolean distributed;
- private boolean natSynchronizationEnabled;
- private String replicationMode;
-
- public String getType() {
- return type;
- }
-
- public RoutingConfig getRoutingConfig() {
- return routingConfig;
- }
-
- public void setRoutingConfig(final RoutingConfig routingConfig) {
- this.routingConfig = routingConfig;
- }
-
- public boolean isDistributed() {
- return distributed;
- }
-
- public void setDistributed(final boolean distributed) {
- this.distributed = distributed;
- }
-
- public boolean isNatSynchronizationEnabled() {
- return natSynchronizationEnabled;
- }
-
- public void setNatSynchronizationEnabled(final boolean natSynchronizationEnabled) {
- this.natSynchronizationEnabled = natSynchronizationEnabled;
- }
-
- public String getReplicationMode() {
- return replicationMode;
- }
-
- public void setReplicationMode(final String replicationMode) {
- this.replicationMode = replicationMode;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java
deleted file mode 100644
index d9ee09a..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java
+++ /dev/null
@@ -1,62 +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 com.cloud.network.nicira;
-
-import java.util.List;
-
-public class LogicalRouterPort extends BaseNiciraNamedEntity {
- private Integer portno;
- private boolean adminStatusEnabled;
- private List<String> ipAddresses;
- private String macAddress;
- private final String type = "LogicalRouterPortConfig";
-
- public int getPortno() {
- return portno;
- }
-
- public void setPortno(final int portno) {
- this.portno = portno;
- }
-
- public boolean isAdminStatusEnabled() {
- return adminStatusEnabled;
- }
-
- public void setAdminStatusEnabled(final boolean adminStatusEnabled) {
- this.adminStatusEnabled = adminStatusEnabled;
- }
-
- public List<String> getIpAddresses() {
- return ipAddresses;
- }
-
- public void setIpAddresses(final List<String> ipAddresses) {
- this.ipAddresses = ipAddresses;
- }
-
- public String getMacAddress() {
- return macAddress;
- }
-
- public void setMacAddress(final String macAddress) {
- this.macAddress = macAddress;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java
deleted file mode 100644
index b527d94..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java
+++ /dev/null
@@ -1,60 +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 com.cloud.network.nicira;
-
-import java.util.List;
-
-public class LogicalSwitch extends BaseNiciraNamedEntity {
- public static final String REPLICATION_MODE_SERVICE = "service";
- public static final String REPLICATION_MODE_SOURCE = "source";
-
- private final String type = "LogicalSwitchConfig";
- private boolean portIsolationEnabled;
- private List<TransportZoneBinding> transportZones;
- private String replicationMode;
-
- public boolean isPortIsolationEnabled() {
- return portIsolationEnabled;
- }
-
- public void setPortIsolationEnabled(final boolean portIsolationEnabled) {
- this.portIsolationEnabled = portIsolationEnabled;
- }
-
- public String getType() {
- return type;
- }
-
- public List<TransportZoneBinding> getTransportZones() {
- return transportZones;
- }
-
- public void setTransportZones(final List<TransportZoneBinding> transportZones) {
- this.transportZones = transportZones;
- }
-
- public String getReplicationMode() {
- return replicationMode;
- }
-
- public void setReplicationMode(final String replicationMode) {
- this.replicationMode = replicationMode;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java
deleted file mode 100644
index 5e07423..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java
+++ /dev/null
@@ -1,82 +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 com.cloud.network.nicira;
-
-import java.util.List;
-
-public class LogicalSwitchPort extends BaseNiciraNamedEntity {
- private Integer portno;
- private boolean adminStatusEnabled;
- private String queueUuid;
- private List<String> securityProfiles;
- private List<String> mirrorTargets;
- private final String type = "LogicalSwitchPortConfig";
-
- public LogicalSwitchPort() {
- super();
- }
-
- public LogicalSwitchPort(final String displayName, final List<NiciraNvpTag> tags, final boolean adminStatusEnabled) {
- super();
- this.displayName = displayName;
- this.tags = tags;
- this.adminStatusEnabled = adminStatusEnabled;
- }
-
- public Integer getPortno() {
- return portno;
- }
-
- public void setPortno(final Integer portno) {
- this.portno = portno;
- }
-
- public boolean isAdminStatusEnabled() {
- return adminStatusEnabled;
- }
-
- public void setAdminStatusEnabled(final boolean adminStatusEnabled) {
- this.adminStatusEnabled = adminStatusEnabled;
- }
-
- public String getQueueUuid() {
- return queueUuid;
- }
-
- public void setQueueUuid(final String queueUuid) {
- this.queueUuid = queueUuid;
- }
-
- public List<String> getSecurityProfiles() {
- return securityProfiles;
- }
-
- public void setSecurityProfiles(final List<String> securityProfiles) {
- this.securityProfiles = securityProfiles;
- }
-
- public List<String> getMirrorTargets() {
- return mirrorTargets;
- }
-
- public void setMirrorTargets(final List<String> mirrorTargets) {
- this.mirrorTargets = mirrorTargets;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java
deleted file mode 100644
index ae3a86c..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java
+++ /dev/null
@@ -1,146 +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 com.cloud.network.nicira;
-
-/**
- *
- */
-public class Match {
- private Integer protocol;
- private String sourceIpAddresses;
- private String destinationIpAddresses;
- private Integer sourcePort;
- private Integer destinationPort;
- private String ethertype = "IPv4";
-
- public Integer getProtocol() {
- return protocol;
- }
-
- public void setProtocol(final Integer protocol) {
- this.protocol = protocol;
- }
-
- public Integer getSourcePort() {
- return sourcePort;
- }
-
- public void setSourcePort(final Integer sourcePort) {
- this.sourcePort = sourcePort;
- }
-
- public Integer getDestinationPort() {
- return destinationPort;
- }
-
- public void setDestinationPort(final Integer destinationPort) {
- this.destinationPort = destinationPort;
- }
-
- public String getEthertype() {
- return ethertype;
- }
-
- public void setEthertype(final String ethertype) {
- this.ethertype = ethertype;
- }
-
- public String getSourceIpAddresses() {
- return sourceIpAddresses;
- }
-
- public void setSourceIpAddresses(final String sourceIpAddresses) {
- this.sourceIpAddresses = sourceIpAddresses;
- }
-
- public String getDestinationIpAddresses() {
- return destinationIpAddresses;
- }
-
- public void setDestinationIpAddresses(final String destinationIpAddresses) {
- this.destinationIpAddresses = destinationIpAddresses;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((destinationIpAddresses == null) ? 0 : destinationIpAddresses.hashCode());
- result = prime * result + ((destinationPort == null) ? 0 : destinationPort.hashCode());
- result = prime * result + ((ethertype == null) ? 0 : ethertype.hashCode());
- result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
- result = prime * result + ((sourceIpAddresses == null) ? 0 : sourceIpAddresses.hashCode());
- result = prime * result + ((sourcePort == null) ? 0 : sourcePort.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- Match other = (Match)obj;
- if (destinationIpAddresses == null) {
- if (other.destinationIpAddresses != null)
- return false;
- } else if (!destinationIpAddresses.equals(other.destinationIpAddresses)) {
- return false;
- }
- if (destinationPort == null) {
- if (other.destinationPort != null) {
- return false;
- }
- } else if (!destinationPort.equals(other.destinationPort)) {
- return false;
- }
- if (ethertype == null) {
- if (other.ethertype != null)
- return false;
- } else if (!ethertype.equals(other.ethertype)) {
- return false;
- }
- if (protocol == null) {
- if (other.protocol != null)
- return false;
- } else if (!protocol.equals(other.protocol)) {
- return false;
- }
- if (sourceIpAddresses == null) {
- if (other.sourceIpAddresses != null)
- return false;
- } else if (!sourceIpAddresses.equals(other.sourceIpAddresses)) {
- return false;
- }
- if (sourcePort == null) {
- if (other.sourcePort != null)
- return false;
- } else if (!sourcePort.equals(other.sourcePort)) {
- return false;
- }
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java
deleted file mode 100644
index 912e352..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java
+++ /dev/null
@@ -1,130 +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 com.cloud.network.nicira;
-
-import java.util.UUID;
-
-/**
- *
- */
-public abstract class NatRule {
- protected Match match;
- protected UUID uuid;
- protected String type;
- protected int order;
-
- public NatRule() {
- }
-
- public Match getMatch() {
- return match;
- }
-
- public void setMatch(final Match match) {
- this.match = match;
- }
-
- public UUID getUuid() {
- return uuid;
- }
-
- public void setUuid(final UUID uuid) {
- this.uuid = uuid;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(final String type) {
- this.type = type;
- }
-
- public int getOrder() {
- return order;
- }
-
- public void setOrder(final int order) {
- this.order = order;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((match == null) ? 0 : match.hashCode());
- result = prime * result + order;
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- NatRule other = (NatRule)obj;
- if (match == null) {
- if (other.match != null)
- return false;
- } else if (!match.equals(other.match))
- return false;
- if (order != other.order)
- return false;
- if (type == null) {
- if (other.type != null)
- return false;
- } else if (!type.equals(other.type))
- return false;
- if (uuid == null) {
- if (other.uuid != null)
- return false;
- } else if (!uuid.equals(other.uuid))
- return false;
- return true;
- }
-
- public boolean equalsIgnoreUuid(final Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- NatRule other = (NatRule)obj;
- if (match == null) {
- if (other.match != null)
- return false;
- } else if (!match.equals(other.match))
- return false;
- if (order != other.order)
- return false;
- if (type == null) {
- if (other.type != null)
- return false;
- } else if (!type.equals(other.type))
- return false;
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java
deleted file mode 100644
index 810453c..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java
+++ /dev/null
@@ -1,658 +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 com.cloud.network.nicira;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.reflect.TypeToken;
-
-import com.cloud.utils.rest.CloudstackRESTException;
-import com.cloud.utils.rest.RESTServiceConnector;
-import com.cloud.utils.rest.RESTValidationStrategy;
-
-@SuppressWarnings("rawtypes")
-public class NiciraNvpApi {
- protected static final String GET_METHOD_TYPE = "get";
- protected static final String DELETE_METHOD_TYPE = "delete";
- protected static final String PUT_METHOD_TYPE = "put";
- protected static final String POST_METHOD_TYPE = "post";
-
- protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile";
- protected static final String ACL_URI_PREFIX = "/ws.v1/acl";
- private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch";
- private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter";
- private static final String LOGIN_URL = "/ws.v1/login";
-
- protected RESTServiceConnector restConnector;
-
- protected final static Map<Class, String> prefixMap;
-
- protected final static Map<Class, Type> listTypeMap;
-
- protected final static Map<String, String> defaultListParams;
-
- static {
- prefixMap = new HashMap<Class, String>();
- prefixMap.put(SecurityProfile.class, SEC_PROFILE_URI_PREFIX);
- prefixMap.put(Acl.class, ACL_URI_PREFIX);
- prefixMap.put(LogicalSwitch.class, SWITCH_URI_PREFIX);
- prefixMap.put(LogicalRouter.class, ROUTER_URI_PREFIX);
-
- listTypeMap = new HashMap<Class, Type>();
- listTypeMap.put(SecurityProfile.class, new TypeToken<NiciraNvpList<SecurityProfile>>() {
- }.getType());
- listTypeMap.put(Acl.class, new TypeToken<NiciraNvpList<Acl>>() {
- }.getType());
- listTypeMap.put(LogicalSwitch.class, new TypeToken<NiciraNvpList<LogicalSwitch>>() {
- }.getType());
- listTypeMap.put(LogicalRouter.class, new TypeToken<NiciraNvpList<LogicalRouter>>() {
- }.getType());
-
- defaultListParams = new HashMap<String, String>();
- defaultListParams.put("fields", "*");
- }
-
- public NiciraNvpApi() {
- final List<Class<?>> classList = new ArrayList<Class<?>>();
- classList.add(NatRule.class);
- classList.add(RoutingConfig.class);
- final List<JsonDeserializer<?>> deserializerList = new ArrayList<JsonDeserializer<?>>();
- deserializerList.add(new NatRuleAdapter());
- deserializerList.add(new RoutingConfigAdapter());
-
- restConnector = new RESTServiceConnector(new RESTValidationStrategy(LOGIN_URL), classList, deserializerList);
- }
-
- public NiciraNvpApi(final String address, final String username, final String password) {
- this();
- restConnector.setControllerAddress(address);
- restConnector.setAdminCredentials(username, password);
- }
-
- public void setControllerAddress(final String address) {
- restConnector.setControllerAddress(address);
- }
-
- public void setAdminCredentials(final String username, final String password) {
- restConnector.setAdminCredentials(username, password);
- }
-
- /**
- * POST
- *
- * @param entity
- * @return
- * @throws NiciraNvpApiException
- */
- protected <T> T create(final T entity) throws NiciraNvpApiException {
- final String uri = prefixMap.get(entity.getClass());
- return createWithUri(entity, uri);
- }
-
- /**
- * POST
- *
- * @param entity
- * @return
- * @throws NiciraNvpApiException
- */
- protected <T> T createWithUri(final T entity, final String uri) throws NiciraNvpApiException {
- T createdEntity;
- try {
- createdEntity = restConnector.executeCreateObject(entity, new TypeToken<T>() {
- }.getType(), uri, Collections.<String, String> emptyMap());
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
-
- return createdEntity;
- }
-
- /**
- * GET list of items
- *
- * @return
- * @throws NiciraNvpApiException
- */
- protected <T> NiciraNvpList<T> find(final Class<T> clazz) throws NiciraNvpApiException {
- return find(null, clazz);
- }
-
- /**
- * GET list of items
- *
- * @param uuid
- * @return
- * @throws NiciraNvpApiException
- */
- public <T> NiciraNvpList<T> find(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
- final String uri = prefixMap.get(clazz);
- Map<String, String> params = defaultListParams;
- if (uuid != null) {
- params = new HashMap<String, String>(defaultListParams);
- params.put("uuid", uuid);
- }
-
- NiciraNvpList<T> entities;
- try {
- entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
-
- if (entities == null) {
- throw new NiciraNvpApiException("Unexpected response from API");
- }
-
- return entities;
- }
-
- /**
- * PUT item given a UUID as key and an item object
- * with the new data
- *
- * @param item
- * @param uuid
- * @throws NiciraNvpApiException
- */
- public <T> void update(final T item, final String uuid)
- throws NiciraNvpApiException {
- final String uri = prefixMap.get(item.getClass()) + "/" + uuid;
- updateWithUri(item, uri);
- }
-
- /**
- * PUT item given a UUID as key and an item object
- * with the new data
- *
- * @param item
- * @param uuid
- * @throws NiciraNvpApiException
- */
- public <T> void updateWithUri(final T item, final String uri)
- throws NiciraNvpApiException {
- try {
- restConnector.executeUpdateObject(item, uri, Collections.<String, String> emptyMap());
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
- }
-
- /**
- * DELETE Security Profile given a UUID as key
- *
- * @param securityProfileUuid
- * @throws NiciraNvpApiException
- */
- public <T> void delete(final String uuid, final Class<T> clazz)
- throws NiciraNvpApiException {
- final String uri = prefixMap.get(clazz) + "/" + uuid;
- deleteWithUri(uri);
- }
-
- /**
- * DELETE Security Profile given a UUID as key
- *
- * @param securityProfileUuid
- * @throws NiciraNvpApiException
- */
- public <T> void deleteWithUri(final String uri)
- throws NiciraNvpApiException {
- try {
- restConnector.executeDeleteObject(uri);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
- }
-
- /**
- * POST {@link SecurityProfile}
- *
- * @param securityProfile
- * @return
- * @throws NiciraNvpApiException
- */
- public SecurityProfile createSecurityProfile(final SecurityProfile securityProfile) throws NiciraNvpApiException {
- return create(securityProfile);
- }
-
- /**
- * GET list of {@link SecurityProfile}
- *
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<SecurityProfile> findSecurityProfile() throws NiciraNvpApiException {
- return findSecurityProfile(null);
- }
-
- /**
- * GET list of {@link SecurityProfile} filtered by UUID
- *
- * We could have invoked the service:
- * SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid
- * but it is not working currently
- *
- * @param uuid
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<SecurityProfile> findSecurityProfile(final String uuid) throws NiciraNvpApiException {
- return find(uuid, SecurityProfile.class);
- }
-
- /**
- * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile}
- * with the new data
- *
- * @param securityProfile
- * @param securityProfileUuid
- * @throws NiciraNvpApiException
- */
- public void updateSecurityProfile(final SecurityProfile securityProfile,
- final String securityProfileUuid)
- throws NiciraNvpApiException {
- update(securityProfile, securityProfileUuid);
- }
-
- /**
- * DELETE Security Profile given a UUID as key
- *
- * @param securityProfileUuid
- * @throws NiciraNvpApiException
- */
- public void deleteSecurityProfile(final String securityProfileUuid)
- throws NiciraNvpApiException {
- delete(securityProfileUuid, SecurityProfile.class);
- }
-
-
- /**
- * POST {@link Acl}
- *
- * @param acl
- * @return
- * @throws NiciraNvpApiException
- */
- public Acl createAcl(final Acl acl) throws NiciraNvpApiException {
- return create(acl);
- }
-
- /**
- * GET list of {@link Acl}
- *
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<Acl> findAcl() throws NiciraNvpApiException {
- return findAcl(null);
- }
-
- /**
- * GET list of {@link Acl} filtered by UUID
- *
- * @param uuid
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<Acl> findAcl(final String uuid) throws NiciraNvpApiException {
- return find(uuid, Acl.class);
- }
-
- /**
- * PUT {@link Acl} given a UUID as key and a {@link Acl}
- * with the new data
- *
- * @param acl
- * @param aclUuid
- * @throws NiciraNvpApiException
- */
- public void updateAcl(final Acl acl,
- final String aclUuid)
- throws NiciraNvpApiException {
- update(acl, aclUuid);
- }
-
- /**
- * DELETE Acl given a UUID as key
- *
- * @param acl
- * @throws NiciraNvpApiException
- */
- public void deleteAcl(final String aclUuid) throws NiciraNvpApiException {
- delete(aclUuid, Acl.class);
- }
-
- public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException {
- return create(logicalSwitch);
- }
-
- /**
- * GET list of {@link LogicalSwitch}
- *
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<LogicalSwitch> findLogicalSwitch() throws NiciraNvpApiException {
- return findLogicalSwitch(null);
- }
-
- /**
- * GET list of {@link LogicalSwitch} filtered by UUID
- *
- * @param uuid
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<LogicalSwitch> findLogicalSwitch(final String uuid) throws NiciraNvpApiException {
- return find(uuid, LogicalSwitch.class);
- }
-
- /**
- * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch}
- * with the new data
- *
- * @param logicalSwitch
- * @param logicalSwitchUuid
- * @throws NiciraNvpApiException
- */
- public void updateLogicalSwitch(final LogicalSwitch logicalSwitch,
- final String logicalSwitchUuid)
- throws NiciraNvpApiException {
- update(logicalSwitch, logicalSwitchUuid);
- }
-
- public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException {
- delete(uuid, LogicalSwitch.class);
- }
-
- public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
- return createWithUri(logicalSwitchPort, uri);
- }
-
- public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPort.getUuid();
- updateWithUri(logicalSwitchPort, uri);
- }
-
- public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid,
- final Attachment attachment) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment";
- updateWithUri(attachment, uri);
- }
-
- public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid;
- deleteWithUri(uri);
- }
-
- public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("attachment_vif_uuid", vifAttachmentUuid);
- params.put("fields", "uuid");
-
- NiciraNvpList<LogicalSwitchPort> lspl;
- try {
- lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
- }.getType(), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
-
- if (lspl == null || lspl.getResultCount() != 1) {
- throw new NiciraNvpApiException("Unexpected response from API");
- }
-
- final LogicalSwitchPort lsp = lspl.getResults().get(0);
- return lsp.getUuid();
- }
-
- public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException {
- final String uri = "/ws.v1/control-cluster/status";
- ControlClusterStatus ccs;
- try {
- ccs = restConnector.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
- }.getType(), uri, null);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
-
- return ccs;
- }
-
- public NiciraNvpList<LogicalSwitchPort> findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
- final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("uuid", logicalSwitchPortUuid);
- params.put("fields", "uuid");
-
- NiciraNvpList<LogicalSwitchPort> lspl;
- try {
- lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
- }.getType(), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
-
- if (lspl == null) {
- throw new NiciraNvpApiException("Unexpected response from API");
- }
-
- return lspl;
- }
-
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("uuid", logicalRouterPortUuid);
- params.put("fields", "uuid");
-
- NiciraNvpList<LogicalRouterPort> lrpl;
- try {
- lrpl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
- }.getType(), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
-
- if (lrpl == null) {
- throw new NiciraNvpApiException("Unexpected response from API");
- }
-
- return lrpl;
- }
-
- public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException {
- return create(logicalRouter);
- }
-
- /**
- * GET list of {@link LogicalRouter}
- *
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<LogicalRouter> findLogicalRouter() throws NiciraNvpApiException {
- return findLogicalRouter(null);
- }
-
- /**
- * GET list of {@link LogicalRouter} filtered by UUID
- *
- * @param uuid
- * @return
- * @throws NiciraNvpApiException
- */
- public NiciraNvpList<LogicalRouter> findLogicalRouter(final String uuid) throws NiciraNvpApiException {
- return find(uuid, LogicalRouter.class);
- }
-
- public LogicalRouter findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
- return findLogicalRouter(logicalRouterUuid).getResults().get(0);
- }
-
- public void updateLogicalRouter(final LogicalRouter logicalRouter,
- final String logicalRouterUuid)
- throws NiciraNvpApiException {
- update(logicalRouter, logicalRouterUuid);
- }
-
- public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid;
- deleteWithUri(uri);
- }
-
- public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- return createWithUri(logicalRouterPort, uri);
- }
-
- public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid;
- deleteWithUri(uri);
- }
-
- public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid();
- updateWithUri(logicalRouterPort, uri);
- }
-
- public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment)
- throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment";
- updateWithUri(attachment, uri);
- }
-
- public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
- return createWithUri(natRule, uri);
- }
-
- public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid();
- updateWithUri(natRule, uri);
- }
-
- public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString();
- deleteWithUri(uri);
- }
-
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid,
- final long vlanId) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("attachment_gwsvc_uuid", gatewayServiceUuid);
- params.put("attachment_vlan", "0");
- params.put("fields", "*");
-
- try {
- return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
- }.getType(), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
- }
-
- public NiciraNvpList<NatRule> findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("fields", "*");
-
- try {
- return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<NatRule>>() {
- }.getType(), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
- }
-
- public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid)
- throws NiciraNvpApiException {
- final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
- final Map<String, String> params = new HashMap<String, String>();
- params.put("fields", "*");
- params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid);
-
- try {
- return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
- }.getType(), uri, params);
- } catch (final CloudstackRESTException e) {
- throw new NiciraNvpApiException(e);
- }
- }
-
- public static class NatRuleAdapter implements JsonDeserializer<NatRule> {
-
- @Override
- public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
- final JsonObject jsonObject = jsonElement.getAsJsonObject();
-
- if (!jsonObject.has("type")) {
- throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object");
- }
-
- final String natRuleType = jsonObject.get("type").getAsString();
- if ("SourceNatRule".equals(natRuleType)) {
- return context.deserialize(jsonElement, SourceNatRule.class);
- } else if ("DestinationNatRule".equals(natRuleType)) {
- return context.deserialize(jsonElement, DestinationNatRule.class);
- }
-
- throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\"");
- }
- }
-
- public static class RoutingConfigAdapter implements JsonDeserializer<RoutingConfig> {
-
- private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig";
- private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig";
-
- @Override
- public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
- final JsonObject jsonObject = jsonElement.getAsJsonObject();
-
- if (!jsonObject.has("type")) {
- throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object");
- }
-
- final String routingConfigType = jsonObject.get("type").getAsString();
- if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) {
- return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class);
- } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) {
- return context.deserialize(jsonElement, RoutingTableRoutingConfig.class);
- }
-
- throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\"");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java
deleted file mode 100644
index 0d27820..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java
+++ /dev/null
@@ -1,39 +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 com.cloud.network.nicira;
-
-public class NiciraNvpApiException extends Exception {
-
- public NiciraNvpApiException() {
- }
-
- public NiciraNvpApiException(final String message) {
- super(message);
- }
-
- public NiciraNvpApiException(final Throwable cause) {
- super(cause);
- }
-
- public NiciraNvpApiException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java
deleted file mode 100644
index 34b5e19..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java
+++ /dev/null
@@ -1,48 +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 com.cloud.network.nicira;
-
-import java.util.List;
-
-public class NiciraNvpList<T> {
- private List<T> results;
- private int resultCount;
-
- public List<T> getResults() {
- return this.results;
- }
-
- public void setResults(List<T> results) {
- this.results = results;
- }
-
- public int getResultCount() {
- return resultCount;
- }
-
- public void setResultCount(int resultCount) {
- this.resultCount = resultCount;
- }
-
- public boolean isEmpty() {
- return this.resultCount == 0;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java
deleted file mode 100644
index 625e49c..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java
+++ /dev/null
@@ -1,64 +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 com.cloud.network.nicira;
-
-import org.apache.log4j.Logger;
-
-public class NiciraNvpTag {
- private static final int TAG_MAX_LEN = 40;
- private static final Logger s_logger = Logger.getLogger(NiciraNvpTag.class);
- private String scope;
- private String tag;
-
- public NiciraNvpTag() {
- }
-
- public NiciraNvpTag(String scope, String tag) {
- this.scope = scope;
- if (tag.length() > 40) {
- s_logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters");
- this.tag = tag.substring(0, TAG_MAX_LEN);
- } else {
- this.tag = tag;
- }
- }
-
- public String getScope() {
- return scope;
- }
-
- public void setScope(String scope) {
- this.scope = scope;
- }
-
- public String getTag() {
- return tag;
- }
-
- public void setTag(String tag) {
- if (tag.length() > 40) {
- s_logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters");
- this.tag = tag.substring(0, 40);
- } else {
- this.tag = tag;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java
deleted file mode 100644
index 26fa048..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java
+++ /dev/null
@@ -1,41 +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 com.cloud.network.nicira;
-
-/**
- *
- */
-public class PatchAttachment extends Attachment {
- private final String type = "PatchAttachment";
- private String peerPortUuid;
-
- public PatchAttachment(String peerPortUuid) {
- this.peerPortUuid = peerPortUuid;
- }
-
- public String getPeerPortUuid() {
- return peerPortUuid;
- }
-
- public void setPeerPortUuid(String peerPortUuid) {
- this.peerPortUuid = peerPortUuid;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java
deleted file mode 100644
index 8dd8840..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java
+++ /dev/null
@@ -1,40 +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 com.cloud.network.nicira;
-
-/**
- *
- */
-public class RouterNextHop {
- private String gatewayIpAddress;
- private final String type = "RouterNextHop";
-
- public RouterNextHop(String gatewayIpAddress) {
- this.gatewayIpAddress = gatewayIpAddress;
- }
-
- public String getGatewayIpAddress() {
- return gatewayIpAddress;
- }
-
- public void setGatewayIpAddress(String gatewayIpAddress) {
- this.gatewayIpAddress = gatewayIpAddress;
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java
deleted file mode 100644
index 5eaef0a..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java
+++ /dev/null
@@ -1,24 +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 com.cloud.network.nicira;
-
-public class RoutingConfig {
-
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingTableRoutingConfig.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingTableRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingTableRoutingConfig.java
deleted file mode 100644
index f0a80b8..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingTableRoutingConfig.java
+++ /dev/null
@@ -1,30 +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 com.cloud.network.nicira;
-
-/**
- *
- */
-public class RoutingTableRoutingConfig extends RoutingConfig {
- public final String type = "RoutingTableRoutingConfig";
-
- public RoutingTableRoutingConfig() {
- }
-}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b0989d/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java
deleted file mode 100644
index d83ce49..0000000
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java
+++ /dev/null
@@ -1,24 +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 com.cloud.network.nicira;
-
-@SuppressWarnings("serial")
-public class SecurityProfile extends AccessConfiguration<SecurityRule> {
-}
[18/50] [abbrv] git commit: updated refs/heads/deploy-from-snapshot
to 44ba14d
Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
new file mode 100644
index 0000000..447e21b
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
@@ -0,0 +1,999 @@
+//
+// 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 com.cloud.utils.cisco.n1kv.vsm;
+
+import java.util.List;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.ls.DOMImplementationLS;
+import org.w3c.dom.ls.LSSerializer;
+
+import com.cloud.utils.Pair;
+
+public class VsmCommand {
+
+ private static final Logger s_logger = Logger.getLogger(VsmCommand.class);
+ private static final String s_namespace = "urn:ietf:params:xml:ns:netconf:base:1.0";
+ private static final String s_ciscons = "http://www.cisco.com/nxos:1.0:ppm";
+ private static final String s_configuremode = "__XML__MODE__exec_configure";
+ private static final String s_portprofmode = "__XML__MODE_port-prof";
+ private static final String s_policymapmode = "__XML__MODE_policy-map";
+ private static final String s_classtypemode = "__XML__MODE_policy-map_class_type";
+ private static final String s_paramvalue = "__XML__PARAM_value";
+
+ public enum PortProfileType {
+ none, vethernet, ethernet;
+ }
+
+ public enum BindingType {
+ none, portbindingstatic, portbindingdynamic, portbindingephermal;
+ }
+
+ public enum SwitchPortMode {
+ none, access, trunk, privatevlanhost, privatevlanpromiscuous
+ }
+
+ public enum OperationType {
+ addvlanid, removevlanid
+ }
+
+ public static String getAddPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(configPortProfileDetails(doc, name, type, binding, mode, vlanid, vdc, espName));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating add port profile message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating add port profile message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getAddPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(configPortProfileDetails(doc, name, type, binding, mode, vlanid));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating add port profile message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating add port profile message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getUpdatePortProfile(String name, SwitchPortMode mode, List<Pair<VsmCommand.OperationType, String>> params) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to update the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(configPortProfileDetails(doc, name, mode, params));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating update port profile message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating update port profile message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getDeletePortProfile(String portName) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(deletePortProfileDetails(doc, portName));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating delete port profile message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating delete port profile message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getAddPolicyMap(String name, int averageRate, int maxRate, int burstRate) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(policyMapDetails(doc, name, averageRate, maxRate, burstRate));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating policy map message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating policy map message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getDeletePolicyMap(String name) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(deletePolicyMapDetails(doc, name));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating delete policy map message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating delete policy map message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getServicePolicy(String policyMap, String portProfile, boolean attach) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(serviceDetails(doc, policyMap, portProfile, attach));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating attach/detach service policy message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating attach/detach service policy message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getPortProfile(String name) {
+ try {
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ Element get = doc.createElement("nf:get");
+ doc.getDocumentElement().appendChild(get);
+
+ Element filter = doc.createElement("nf:filter");
+ filter.setAttribute("type", "subtree");
+ get.appendChild(filter);
+
+ // Create the show port-profile name <profile-name> command.
+ Element show = doc.createElement("show");
+ filter.appendChild(show);
+ Element portProfile = doc.createElement("port-profile");
+ show.appendChild(portProfile);
+ Element nameNode = doc.createElement("name");
+ portProfile.appendChild(nameNode);
+
+ // Profile name
+ Element profileName = doc.createElement("profile_name");
+ profileName.setTextContent(name);
+ nameNode.appendChild(profileName);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating the message to get port profile details: " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating the message to get port profile details: " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getPolicyMap(String name) {
+ try {
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ Element get = doc.createElement("nf:get");
+ doc.getDocumentElement().appendChild(get);
+
+ Element filter = doc.createElement("nf:filter");
+ filter.setAttribute("type", "subtree");
+ get.appendChild(filter);
+
+ // Create the show port-profile name <profile-name> command.
+ Element show = doc.createElement("show");
+ filter.appendChild(show);
+ Element policyMap = doc.createElement("policy-map");
+ show.appendChild(policyMap);
+ Element nameNode = doc.createElement("name");
+ nameNode.setTextContent(name);
+ policyMap.appendChild(nameNode);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating the message to get policy map details : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating the message to get policy map details : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getHello() {
+ try {
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+
+ // Root elements.
+ Document doc = domImpl.createDocument(s_namespace, "nc:hello", null);
+
+ // Client capacity. We are only supporting basic capacity.
+ Element capabilities = doc.createElement("nc:capabilities");
+ Element capability = doc.createElement("nc:capability");
+ capability.setTextContent("urn:ietf:params:xml:ns:netconf:base:1.0");
+
+ capabilities.appendChild(capability);
+ doc.getDocumentElement().appendChild(capabilities);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while creating hello message : " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while creating hello message : " + e.getMessage());
+ return null;
+ }
+ }
+
+ public static String getVServiceNode(String vlanId, String ipAddr) {
+ try {
+ // Create the document and root element.
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementation domImpl = docBuilder.getDOMImplementation();
+ Document doc = createDocument(domImpl);
+
+ // Edit configuration command.
+ Element editConfig = doc.createElement("nf:edit-config");
+ doc.getDocumentElement().appendChild(editConfig);
+
+ // Command to get into exec configure mode.
+ Element target = doc.createElement("nf:target");
+ Element running = doc.createElement("nf:running");
+ target.appendChild(running);
+ editConfig.appendChild(target);
+
+ // Command to create the port profile with the desired configuration.
+ Element config = doc.createElement("nf:config");
+ config.appendChild(configVServiceNodeDetails(doc, vlanId, ipAddr));
+ editConfig.appendChild(config);
+
+ return serialize(domImpl, doc);
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error while adding vservice node for vlan " + vlanId + ", " + e.getMessage());
+ return null;
+ } catch (DOMException e) {
+ s_logger.error("Error while adding vservice node for vlan " + vlanId + ", " + e.getMessage());
+ return null;
+ }
+ }
+
+ private static Element configVServiceNodeDetails(Document doc, String vlanId, String ipAddr) {
+ // In mode, exec_configure.
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // vservice node %name% type asa
+ Element vservice = doc.createElement("vservice");
+ vservice.appendChild(doc.createElement("node"))
+ .appendChild(doc.createElement("ASA_" + vlanId))
+ .appendChild(doc.createElement("type"))
+ .appendChild(doc.createElement("asa"));
+ modeConfigure.appendChild(vservice);
+
+ Element address = doc.createElement(s_paramvalue);
+ address.setAttribute("isKey", "true");
+ address.setTextContent(ipAddr);
+
+ // ip address %ipAddr%
+ modeConfigure.appendChild(doc.createElement("ip")).appendChild(doc.createElement("address")).appendChild(doc.createElement("value")).appendChild(address);
+
+ Element vlan = doc.createElement(s_paramvalue);
+ vlan.setAttribute("isKey", "true");
+ vlan.setTextContent(vlanId);
+
+ // adjacency l2 vlan %vlanId%
+ modeConfigure.appendChild(doc.createElement("adjacency"))
+ .appendChild(doc.createElement("l2"))
+ .appendChild(doc.createElement("vlan"))
+ .appendChild(doc.createElement("value"))
+ .appendChild(vlan);
+
+ // fail-mode close
+ modeConfigure.appendChild(doc.createElement("fail-mode")).appendChild(doc.createElement("close"));
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element configPortProfileDetails(Document doc, String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc,
+ String espName) {
+
+ // In mode, exec_configure.
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Port profile name and type configuration.
+ Element portProfile = doc.createElement("port-profile");
+ modeConfigure.appendChild(portProfile);
+
+ // Port profile type.
+ Element portDetails = doc.createElement("name");
+ switch (type) {
+ case none:
+ portProfile.appendChild(portDetails);
+ break;
+ case ethernet: {
+ Element typetag = doc.createElement("type");
+ Element ethernettype = doc.createElement("ethernet");
+ portProfile.appendChild(typetag);
+ typetag.appendChild(ethernettype);
+ ethernettype.appendChild(portDetails);
+ }
+ break;
+ case vethernet: {
+ Element typetag = doc.createElement("type");
+ Element ethernettype = doc.createElement("vethernet");
+ portProfile.appendChild(typetag);
+ typetag.appendChild(ethernettype);
+ ethernettype.appendChild(portDetails);
+ }
+ break;
+ }
+
+ // Port profile name.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(name);
+ portDetails.appendChild(value);
+
+ // element for port prof mode.
+ Element portProf = doc.createElement(s_portprofmode);
+ portDetails.appendChild(portProf);
+
+ // Binding type.
+ if (binding != BindingType.none) {
+ portProf.appendChild(getBindingType(doc, binding));
+ }
+
+ if (mode != SwitchPortMode.none) {
+ // Switchport mode.
+ portProf.appendChild(getSwitchPortMode(doc, mode));
+ // Adding vlan details.
+ if (vlanid > 0) {
+ portProf.appendChild(getAddVlanDetails(doc, mode, Integer.toString(vlanid)));
+ }
+ }
+
+ // Command "vmware port-group".
+ Element vmware = doc.createElement("vmware");
+ Element portgroup = doc.createElement("port-group");
+ vmware.appendChild(portgroup);
+ portProf.appendChild(vmware);
+
+ // org %vdc%
+ // vservice node <Node Name> profile <Edge Security Profile Name in VNMC>
+ Element vdcValue = doc.createElement(s_paramvalue);
+ vdcValue.setAttribute("isKey", "true");
+ vdcValue.setTextContent(vdc);
+
+ Element org = doc.createElement("org");
+ org.appendChild(doc.createElement("orgname")).appendChild(vdcValue);
+ portProf.appendChild(org);
+
+ String asaNodeName = "ASA_" + vlanid;
+ Element vservice = doc.createElement("vservice");
+ vservice.appendChild(doc.createElement("node"))
+ .appendChild(doc.createElement(asaNodeName))
+ .appendChild(doc.createElement("profile"))
+ .appendChild(doc.createElement(espName));
+ portProf.appendChild(vservice);
+
+ // no shutdown.
+ Element no = doc.createElement("no");
+ Element shutdown = doc.createElement("shutdown");
+ no.appendChild(shutdown);
+ portProf.appendChild(no);
+
+ // Enable the port profile.
+ Element state = doc.createElement("state");
+ Element enabled = doc.createElement("enabled");
+ state.appendChild(enabled);
+ portProf.appendChild(state);
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element configPortProfileDetails(Document doc, String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) {
+
+ // In mode, exec_configure.
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Port profile name and type configuration.
+ Element portProfile = doc.createElement("port-profile");
+ modeConfigure.appendChild(portProfile);
+
+ // Port profile type.
+ Element portDetails = doc.createElement("name");
+ switch (type) {
+ case none:
+ portProfile.appendChild(portDetails);
+ break;
+ case ethernet: {
+ Element typetag = doc.createElement("type");
+ Element ethernettype = doc.createElement("ethernet");
+ portProfile.appendChild(typetag);
+ typetag.appendChild(ethernettype);
+ ethernettype.appendChild(portDetails);
+ }
+ break;
+ case vethernet: {
+ Element typetag = doc.createElement("type");
+ Element ethernettype = doc.createElement("vethernet");
+ portProfile.appendChild(typetag);
+ typetag.appendChild(ethernettype);
+ ethernettype.appendChild(portDetails);
+ }
+ break;
+ }
+
+ // Port profile name.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(name);
+ portDetails.appendChild(value);
+
+ // element for port prof mode.
+ Element portProf = doc.createElement(s_portprofmode);
+ portDetails.appendChild(portProf);
+
+ // Binding type.
+ if (binding != BindingType.none) {
+ portProf.appendChild(getBindingType(doc, binding));
+ }
+
+ if (mode != SwitchPortMode.none) {
+ // Switchport mode.
+ portProf.appendChild(getSwitchPortMode(doc, mode));
+ // Adding vlan details.
+ if (vlanid > 0) {
+ portProf.appendChild(getAddVlanDetails(doc, mode, Integer.toString(vlanid)));
+ }
+ }
+
+ // Command "vmware port-group".
+ Element vmware = doc.createElement("vmware");
+ Element portgroup = doc.createElement("port-group");
+ vmware.appendChild(portgroup);
+ portProf.appendChild(vmware);
+
+ // no shutdown.
+ Element no = doc.createElement("no");
+ Element shutdown = doc.createElement("shutdown");
+ no.appendChild(shutdown);
+ portProf.appendChild(no);
+
+ // Enable the port profile.
+ Element state = doc.createElement("state");
+ Element enabled = doc.createElement("enabled");
+ state.appendChild(enabled);
+ portProf.appendChild(state);
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element configPortProfileDetails(Document doc, String name, SwitchPortMode mode, List<Pair<VsmCommand.OperationType, String>> params) {
+
+ // In mode, exec_configure.
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Port profile name and type configuration.
+ Element portProfile = doc.createElement("port-profile");
+ modeConfigure.appendChild(portProfile);
+
+ // Port profile type.
+ Element portDetails = doc.createElement("name");
+ portProfile.appendChild(portDetails);
+
+ // Name of the profile to update.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(name);
+ portDetails.appendChild(value);
+
+ // element for port prof mode.
+ Element portProfMode = doc.createElement(s_portprofmode);
+ portDetails.appendChild(portProfMode);
+
+ for (Pair<VsmCommand.OperationType, String> item : params) {
+ if (item.first() == OperationType.addvlanid) {
+ // Set the access mode configuration or the list
+ // of allowed vlans on the trunking interface.
+ portProfMode.appendChild(getAddVlanDetails(doc, mode, item.second()));
+ } else if (item.first() == OperationType.removevlanid) {
+ portProfMode.appendChild(getDeleteVlanDetails(doc, mode, item.second()));
+ }
+ }
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element deletePortProfileDetails(Document doc, String name) {
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Command and name for the port profile to be deleted.
+ Element deletePortProfile = doc.createElement("no");
+ modeConfigure.appendChild(deletePortProfile);
+
+ Element portProfile = doc.createElement("port-profile");
+ deletePortProfile.appendChild(portProfile);
+
+ Element portDetails = doc.createElement("name");
+ portProfile.appendChild(portDetails);
+
+ // Name of the profile to delete.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(name);
+ portDetails.appendChild(value);
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element policyMapDetails(Document doc, String name, int averageRate, int maxRate, int burstRate) {
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Policy map details
+ Element policyMap = doc.createElement("policy-map");
+ modeConfigure.appendChild(policyMap);
+
+ Element policyDetails = doc.createElement("name");
+ policyMap.appendChild(policyDetails);
+
+ // Name of the policy to create/update.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(name);
+ policyDetails.appendChild(value);
+
+ Element policyMapMode = doc.createElement(s_policymapmode);
+ policyDetails.appendChild(policyMapMode);
+
+ // Create the default class to match all traffic.
+ Element classRoot = doc.createElement("class");
+ Element classDefault = doc.createElement("class-default");
+ policyMapMode.appendChild(classRoot);
+ classRoot.appendChild(classDefault);
+
+ Element classMode = doc.createElement(s_classtypemode);
+ classDefault.appendChild(classMode);
+
+ // Set the average, max and burst rate.
+ // TODO: Add handling for max and burst.
+ Element police = doc.createElement("police");
+ classMode.appendChild(police);
+
+ // Set the committed information rate and its value in mbps.
+ Element cir = doc.createElement("cir");
+ police.appendChild(cir);
+ Element cirValue = doc.createElement("cir-val");
+ cir.appendChild(cirValue);
+ Element value2 = doc.createElement(s_paramvalue);
+ Element mbps = doc.createElement("mbps");
+ value2.setTextContent(Integer.toString(averageRate));
+ cirValue.appendChild(value2);
+ cirValue.appendChild(mbps);
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element deletePolicyMapDetails(Document doc, String name) {
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Delete Policy map details
+ Element deletePolicyMap = doc.createElement("no");
+ Element policyMap = doc.createElement("policy-map");
+ deletePolicyMap.appendChild(policyMap);
+ modeConfigure.appendChild(deletePolicyMap);
+
+ Element policyDetails = doc.createElement("name");
+ policyMap.appendChild(policyDetails);
+
+ // Name of the policy to create/update.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(name);
+ policyDetails.appendChild(value);
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element serviceDetails(Document doc, String policyMap, String portProfile, boolean attach) {
+ // In mode, exec_configure.
+ Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+ Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+ configure.appendChild(modeConfigure);
+
+ // Port profile name and type configuration.
+ Element profile = doc.createElement("port-profile");
+ modeConfigure.appendChild(profile);
+
+ // Port profile type.
+ Element portDetails = doc.createElement("name");
+ profile.appendChild(portDetails);
+
+ // Name of the profile to update.
+ Element value = doc.createElement(s_paramvalue);
+ value.setAttribute("isKey", "true");
+ value.setTextContent(portProfile);
+ portDetails.appendChild(value);
+
+ // element for port prof mode.
+ Element portProfMode = doc.createElement(s_portprofmode);
+ portDetails.appendChild(portProfMode);
+
+ // Associate/Remove the policy for input.
+ if (attach) {
+ portProfMode.appendChild(getServicePolicyCmd(doc, policyMap, "input"));
+ } else {
+ Element detach = doc.createElement("no");
+ portProfMode.appendChild(detach);
+ detach.appendChild(getServicePolicyCmd(doc, policyMap, "input"));
+ }
+
+ // Associate/Remove the policy for output.
+ if (attach) {
+ portProfMode.appendChild(getServicePolicyCmd(doc, policyMap, "output"));
+ } else {
+ Element detach = doc.createElement("no");
+ portProfMode.appendChild(detach);
+ detach.appendChild(getServicePolicyCmd(doc, policyMap, "output"));
+ }
+
+ // Persist the configuration across reboots.
+ modeConfigure.appendChild(persistConfiguration(doc));
+
+ return configure;
+ }
+
+ private static Element persistConfiguration(Document doc) {
+ Element copy = doc.createElement("copy");
+ Element running = doc.createElement("running-config");
+ Element startup = doc.createElement("startup-config");
+ copy.appendChild(running);
+ running.appendChild(startup);
+ return copy;
+ }
+
+ private static Element getAddVlanDetails(Document doc, SwitchPortMode mode, String vlanid) {
+ Element switchport = doc.createElement("switchport");
+
+ // Details of the vlanid to add.
+ Element vlancreate = doc.createElement("vlan-id-create-delete");
+ Element value = doc.createElement(s_paramvalue);
+ value.setTextContent(vlanid);
+ vlancreate.appendChild(value);
+
+ // Handling is there only for 'access' and 'trunk allowed' mode command.
+ if (mode == SwitchPortMode.access) {
+ Element access = doc.createElement("access");
+ switchport.appendChild(access);
+
+ Element vlan = doc.createElement("vlan");
+ access.appendChild(vlan);
+
+ vlan.appendChild(vlancreate);
+ } else if (mode == SwitchPortMode.trunk) {
+ Element trunk = doc.createElement("trunk");
+ switchport.appendChild(trunk);
+
+ Element allowed = doc.createElement("allowed");
+ trunk.appendChild(allowed);
+
+ Element vlan = doc.createElement("vlan");
+ allowed.appendChild(vlan);
+
+ Element add = doc.createElement("add");
+ vlan.appendChild(add);
+
+ add.appendChild(vlancreate);
+ }
+
+ return switchport;
+ }
+
+ private static Node getDeleteVlanDetails(Document doc, SwitchPortMode mode, String vlanid) {
+ Node parentNode = null;
+ Element switchport = doc.createElement("switchport");
+
+ // Handling is there only for 'access' and 'trunk allowed' mode command.
+ if (mode == SwitchPortMode.access) {
+ Element no = doc.createElement("no");
+ no.appendChild(switchport);
+ parentNode = no;
+
+ Element access = doc.createElement("access");
+ switchport.appendChild(access);
+
+ Element vlan = doc.createElement("vlan");
+ access.appendChild(vlan);
+ } else if (mode == SwitchPortMode.trunk) {
+ parentNode = switchport;
+
+ Element trunk = doc.createElement("trunk");
+ switchport.appendChild(trunk);
+
+ Element allowed = doc.createElement("allowed");
+ trunk.appendChild(allowed);
+
+ Element vlan = doc.createElement("vlan");
+ allowed.appendChild(vlan);
+
+ Element remove = doc.createElement("remove");
+ vlan.appendChild(remove);
+
+ // Details of the vlanid to add.
+ Element vlancreate = doc.createElement("vlan-id-create-delete");
+ Element value = doc.createElement(s_paramvalue);
+ value.setTextContent(vlanid);
+ vlancreate.appendChild(value);
+
+ remove.appendChild(vlancreate);
+ }
+
+ return parentNode;
+ }
+
+ private static Element getBindingType(Document doc, BindingType binding) {
+ Element portBinding = doc.createElement("port-binding");
+
+ // We only have handling for access or trunk mode. Handling for private-vlan
+ // host/promiscuous command will have to be added.
+ if (binding == BindingType.portbindingstatic) {
+ Element type = doc.createElement("static");
+ portBinding.appendChild(type);
+ } else if (binding == BindingType.portbindingdynamic) {
+ Element type = doc.createElement("dynamic");
+ portBinding.appendChild(type);
+ } else if (binding == BindingType.portbindingephermal) {
+ Element type = doc.createElement("ephemeral");
+ portBinding.appendChild(type);
+ }
+
+ return portBinding;
+ }
+
+ private static Element getSwitchPortMode(Document doc, SwitchPortMode mode) {
+ Element switchport = doc.createElement("switchport");
+ Element accessmode = doc.createElement("mode");
+ switchport.appendChild(accessmode);
+
+ // We only have handling for access or trunk mode. Handling for private-vlan
+ // host/promiscuous command will have to be added.
+ if (mode == SwitchPortMode.access) {
+ Element access = doc.createElement("access");
+ accessmode.appendChild(access);
+ } else if (mode == SwitchPortMode.trunk) {
+ Element trunk = doc.createElement("trunk");
+ accessmode.appendChild(trunk);
+ }
+
+ return switchport;
+ }
+
+ private static Element getServicePolicyCmd(Document doc, String policyMap, String type) {
+ Element service = doc.createElement("service-policy");
+ Element input = doc.createElement(type);
+ service.appendChild(input);
+
+ Element name = doc.createElement("name");
+ input.appendChild(name);
+
+ Element policyValue = doc.createElement(s_paramvalue);
+ policyValue.setTextContent(policyMap);
+ name.appendChild(policyValue);
+
+ return service;
+ }
+
+ private static Document createDocument(DOMImplementation dom) {
+ Document doc = dom.createDocument(s_namespace, "nf:rpc", null);
+ doc.getDocumentElement().setAttribute("message-id", "101");
+ doc.getDocumentElement().setAttributeNS(s_ciscons, "portprofile", "true");
+ return doc;
+ }
+
+ private static String serialize(DOMImplementation domImpl, Document document) {
+ DOMImplementationLS ls = (DOMImplementationLS)domImpl;
+ LSSerializer lss = ls.createLSSerializer();
+ return lss.writeToString(document);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java
new file mode 100644
index 0000000..8c56b22
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.cisco.n1kv.vsm;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+public class VsmOkResponse extends VsmResponse {
+
+ VsmOkResponse(String response) {
+ super(response);
+ initialize();
+ }
+
+ @Override
+ protected void parse(Element root) {
+ NodeList list = root.getElementsByTagName("nf:rpc-error");
+ if (list.getLength() == 0) {
+ // No rpc-error tag; means response was ok.
+ assert (root.getElementsByTagName("nf:ok").getLength() > 0);
+ _responseOk = true;
+ } else {
+ parseError(list.item(0));
+ _responseOk = false;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java
new file mode 100644
index 0000000..c0ed6ee
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java
@@ -0,0 +1,84 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.cisco.n1kv.vsm;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class VsmPolicyMapResponse extends VsmResponse {
+ private static final Logger s_logger = Logger.getLogger(VsmPolicyMapResponse.class);
+ private static final String s_policyMapDetails = "__XML__OPT_Cmd_show_policy-map___readonly__";
+
+ private PolicyMap _policyMap = new PolicyMap();
+
+ VsmPolicyMapResponse(String response) {
+ super(response);
+ initialize();
+ }
+
+ public PolicyMap getPolicyMap() {
+ return _policyMap;
+ }
+
+ @Override
+ protected void parse(Element root) {
+ NodeList list = root.getElementsByTagName("nf:rpc-error");
+ if (list.getLength() == 0) {
+ // No rpc-error tag; means response was ok.
+ NodeList dataList = root.getElementsByTagName("nf:data");
+ if (dataList.getLength() > 0) {
+ parseData(dataList.item(0));
+ _responseOk = true;
+ }
+ } else {
+ super.parseError(list.item(0));
+ _responseOk = false;
+ }
+ }
+
+ protected void parseData(Node data) {
+ try {
+ NodeList list = ((Element)data).getElementsByTagName(s_policyMapDetails);
+ if (list.getLength() > 0) {
+ NodeList readOnlyList = ((Element)list.item(0)).getElementsByTagName("__readonly__");
+ Element readOnly = (Element)readOnlyList.item(0);
+
+ for (Node node = readOnly.getFirstChild(); node != null; node = node.getNextSibling()) {
+ String currentNode = node.getNodeName();
+ String value = node.getTextContent();
+ if ("pmap-name-out".equalsIgnoreCase(currentNode)) {
+ _policyMap.policyMapName = value;
+ } else if ("cir".equalsIgnoreCase(currentNode)) {
+ _policyMap.committedRate = Integer.parseInt(value.trim());
+ } else if ("bc".equalsIgnoreCase(currentNode)) {
+ _policyMap.burstRate = Integer.parseInt(value.trim());
+ } else if ("pir".equalsIgnoreCase(currentNode)) {
+ _policyMap.peakRate = Integer.parseInt(value.trim());
+ }
+ }
+ }
+ } catch (DOMException e) {
+ s_logger.error("Error parsing the response : " + e.toString());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java
new file mode 100644
index 0000000..0a3de18
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java
@@ -0,0 +1,166 @@
+//
+// 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 com.cloud.utils.cisco.n1kv.vsm;
+
+import java.util.StringTokenizer;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType;
+import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode;
+
+public class VsmPortProfileResponse extends VsmResponse {
+ private static final Logger s_logger = Logger.getLogger(VsmPortProfileResponse.class);
+ private static final String s_portProfileDetails = "__XML__OPT_Cmd_show_port_profile___readonly__";
+
+ private PortProfile _portProfile = new PortProfile();
+
+ VsmPortProfileResponse(String response) {
+ super(response);
+ initialize();
+ }
+
+ public PortProfile getPortProfile() {
+ return _portProfile;
+ }
+
+ @Override
+ protected void parse(Element root) {
+ NodeList list = root.getElementsByTagName("nf:rpc-error");
+ if (list.getLength() == 0) {
+ // No rpc-error tag; means response was ok.
+ NodeList dataList = root.getElementsByTagName("nf:data");
+ if (dataList.getLength() > 0) {
+ parseData(dataList.item(0));
+ _responseOk = true;
+ }
+ } else {
+ super.parseError(list.item(0));
+ _responseOk = false;
+ }
+ }
+
+ protected void parseData(Node data) {
+ try {
+ NodeList list = ((Element)data).getElementsByTagName(s_portProfileDetails);
+ if (list.getLength() > 0) {
+ NodeList readOnlyList = ((Element)list.item(0)).getElementsByTagName("__readonly__");
+ Element readOnly = (Element)readOnlyList.item(0);
+
+ for (Node node = readOnly.getFirstChild(); node != null; node = node.getNextSibling()) {
+ String currentNode = node.getNodeName();
+ String value = node.getTextContent();
+ if ("port_binding".equalsIgnoreCase(currentNode)) {
+ setPortBinding(value);
+ } else if ("profile_name".equalsIgnoreCase(currentNode)) {
+ // Set the port profile name.
+ _portProfile.profileName = value;
+ } else if ("profile_cfg".equalsIgnoreCase(currentNode)) {
+ setProfileConfiguration(value);
+ } else if ("type".equalsIgnoreCase(currentNode)) {
+ setPortType(value);
+ } else if ("status".equalsIgnoreCase(currentNode)) {
+ // Has the profile been enabled.
+ if (value.equalsIgnoreCase("1")) {
+ _portProfile.status = true;
+ }
+ } else if ("max_ports".equalsIgnoreCase(currentNode)) {
+ // Has the profile been enabled.
+ _portProfile.maxPorts = Integer.parseInt(value.trim());
+ }
+ }
+ }
+ } catch (DOMException e) {
+ s_logger.error("Error parsing the response : " + e.toString());
+ }
+ }
+
+ private void setProfileConfiguration(String value) {
+ StringTokenizer tokens = new StringTokenizer(value.trim());
+ if (tokens.hasMoreTokens()) {
+ String currentToken = tokens.nextToken();
+ if ("switchport".equalsIgnoreCase(currentToken)) {
+ parseProfileMode(tokens);
+ } else if ("service-policy".equalsIgnoreCase(currentToken)) {
+ String ioType = tokens.nextToken();
+ if ("input".equalsIgnoreCase(ioType)) {
+ _portProfile.inputPolicyMap = tokens.nextToken();
+ } else if ("output".equalsIgnoreCase(ioType)) {
+ _portProfile.outputPolicyMap = tokens.nextToken();
+ }
+ }
+ }
+ }
+
+ private void parseProfileMode(StringTokenizer tokens) {
+ if (tokens.hasMoreTokens()) {
+ String firstToken = tokens.nextToken();
+ if ("mode".equalsIgnoreCase(firstToken)) {
+ setPortMode(tokens.nextToken());
+ } else if ("access".equalsIgnoreCase(firstToken)) {
+ if (tokens.hasMoreTokens()) {
+ String secondToken = tokens.nextToken();
+ assert ("vlan".equalsIgnoreCase(secondToken));
+ if (tokens.hasMoreTokens()) {
+ _portProfile.vlan = tokens.nextToken();
+ }
+ }
+ }
+ }
+ }
+
+ private void setPortMode(String value) {
+ // Set the mode for port profile.
+ if ("access".equalsIgnoreCase(value)) {
+ _portProfile.mode = SwitchPortMode.access;
+ } else if ("trunk".equalsIgnoreCase(value)) {
+ _portProfile.mode = SwitchPortMode.trunk;
+ } else if ("privatevlanhost".equalsIgnoreCase(value)) {
+ _portProfile.mode = SwitchPortMode.privatevlanhost;
+ } else if ("privatevlanpromiscuous".equalsIgnoreCase(value)) {
+ _portProfile.mode = SwitchPortMode.privatevlanpromiscuous;
+ }
+ }
+
+ private void setPortBinding(String value) {
+ // Set the binding type for the port profile.
+ if ("static".equalsIgnoreCase(value)) {
+ _portProfile.binding = BindingType.portbindingstatic;
+ } else if ("dynamic".equalsIgnoreCase(value)) {
+ _portProfile.binding = BindingType.portbindingdynamic;
+ } else if ("ephermal".equalsIgnoreCase(value)) {
+ _portProfile.binding = BindingType.portbindingephermal;
+ }
+ }
+
+ private void setPortType(String value) {
+ // Set the type field (vethernet/ethernet).
+ if ("vethernet".equalsIgnoreCase(value)) {
+ _portProfile.type = PortProfileType.vethernet;
+ } else if ("ethernet".equalsIgnoreCase(value)) {
+ _portProfile.type = PortProfileType.ethernet;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java
new file mode 100644
index 0000000..d82b0dc
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java
@@ -0,0 +1,222 @@
+//
+// 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 com.cloud.utils.cisco.n1kv.vsm;
+
+import java.io.IOException;
+import java.io.StringReader;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.ls.DOMImplementationLS;
+import org.w3c.dom.ls.LSSerializer;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+public abstract class VsmResponse {
+
+ // Following error tags, error types and severity have been taken from RFC 4741.
+ public enum ErrorTag {
+ InUse, // in-use
+ InvalidValue, // invalid-value
+ TooBig, // too-big
+ MissingAttribute, // missing-attribute
+ BadAttribute, // bad-attribute
+ UnknownAttribute, // unknown-attribute
+ MissingElement, // missing-element
+ BadElement, // bad-element
+ UnknownElement, // unknown-element
+ UnknownNamespace, // unknown-namespace
+ AccessDenied, // access-denied
+ LockDenied, // lock-denied
+ ResourceDenied, // resource-denied
+ RollbackFailed, // rollback-failed
+ DataExists, // data-exists
+ DataMissing, // data-missing
+ OperationNotSupported, // operation-not-supported
+ OperationFailed, // operation-failed
+ PartialOperation, // partial-operation
+ }
+
+ public enum ErrorType {
+ transport, rpc, protocol, application;
+ }
+
+ public enum ErrorSeverity {
+ error, warning;
+ }
+
+ private static final Logger s_logger = Logger.getLogger(VsmResponse.class);
+
+ protected String _xmlResponse;
+ protected Document _docResponse;
+ protected boolean _responseOk;
+
+ protected ErrorTag _tag;
+ protected ErrorType _type;
+ protected ErrorSeverity _severity;
+ protected String _path;
+ protected String _message;
+ protected String _info;
+
+ VsmResponse(String response) {
+ _xmlResponse = response;
+ _responseOk = false;
+ _tag = ErrorTag.InUse;
+ _type = ErrorType.rpc;
+ _severity = ErrorSeverity.error;
+ _docResponse = null;
+ }
+
+ protected void initialize() {
+ try {
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setNamespaceAware(true);
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ _docResponse = docBuilder.parse(new InputSource(new StringReader(_xmlResponse)));
+ if (_docResponse != null) {
+ parse(_docResponse.getDocumentElement());
+ }
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error parsing the response : " + e.toString());
+ } catch (SAXException e) {
+ s_logger.error("Error parsing the response : " + e.toString());
+ } catch (IOException e) {
+ s_logger.error("Error parsing the response : " + e.toString());
+ }
+ }
+
+ public boolean isResponseOk() {
+ return _responseOk;
+ }
+
+ @Override
+ public String toString() {
+ StringBuffer error = new StringBuffer("");
+
+ error.append(" Severity: " + _severity).append(", Error code: " + _tag).append(", Error type: " + _type);
+
+ if (_message != null) {
+ error.append(", Error Message: " + _message);
+ }
+
+ if (_info != null) {
+ error.append(", Error info: " + _info);
+ }
+
+ if (_path != null) {
+ error.append(", Path: " + _path);
+ }
+
+ return error.toString();
+ }
+
+ protected abstract void parse(Element root);
+
+ protected void parseError(Node element) {
+ Element rpcError = (Element)element;
+
+ try {
+ assert (rpcError.getNodeName().equalsIgnoreCase("nf:rpc-error"));
+ for (Node node = rpcError.getFirstChild(); node != null; node = node.getNextSibling()) {
+ if (node.getNodeName().equalsIgnoreCase("nf:error-type")) {
+ _type = ErrorType.valueOf(node.getTextContent().trim());
+ } else if (node.getNodeName().equalsIgnoreCase("nf:error-tag")) {
+ _tag = getErrorTag(node.getTextContent().trim());
+ } else if (node.getNodeName().equalsIgnoreCase("nf:error-severity")) {
+ _severity = ErrorSeverity.valueOf(node.getTextContent().trim());
+ } else if (node.getNodeName().equalsIgnoreCase("nf:error-path")) {
+ _path = node.getTextContent();
+ } else if (node.getNodeName().equalsIgnoreCase("nf:error-message")) {
+ _message = node.getTextContent();
+ } else if (node.getNodeName().equalsIgnoreCase("nf:error-info")) {
+ _info = node.getTextContent();
+ }
+ }
+ } catch (DOMException e) {
+ s_logger.error("Error parsing the response : " + e.toString());
+ }
+ }
+
+ protected ErrorTag getErrorTag(String tagText) {
+ ErrorTag tag = ErrorTag.InUse;
+
+ if (tagText.equals("in-use")) {
+ tag = ErrorTag.InUse;
+ } else if (tagText.equals("invalid-value")) {
+ tag = ErrorTag.InvalidValue;
+ } else if (tagText.equals("too-big")) {
+ tag = ErrorTag.TooBig;
+ } else if (tagText.equals("missing-attribute")) {
+ tag = ErrorTag.MissingAttribute;
+ } else if (tagText.equals("bad-attribute")) {
+ tag = ErrorTag.BadAttribute;
+ } else if (tagText.equals("unknown-attribute")) {
+ tag = ErrorTag.UnknownAttribute;
+ } else if (tagText.equals("missing-element")) {
+ tag = ErrorTag.MissingElement;
+ } else if (tagText.equals("bad-element")) {
+ tag = ErrorTag.BadElement;
+ } else if (tagText.equals("unknown-element")) {
+ tag = ErrorTag.UnknownElement;
+ } else if (tagText.equals("unknown-namespace")) {
+ tag = ErrorTag.UnknownNamespace;
+ } else if (tagText.equals("access-denied")) {
+ tag = ErrorTag.AccessDenied;
+ } else if (tagText.equals("lock-denied")) {
+ tag = ErrorTag.LockDenied;
+ } else if (tagText.equals("resource-denied")) {
+ tag = ErrorTag.ResourceDenied;
+ } else if (tagText.equals("rollback-failed")) {
+ tag = ErrorTag.RollbackFailed;
+ } else if (tagText.equals("data-exists")) {
+ tag = ErrorTag.DataExists;
+ } else if (tagText.equals("data-missing")) {
+ tag = ErrorTag.DataMissing;
+ } else if (tagText.equals("operation-not-supported")) {
+ tag = ErrorTag.OperationNotSupported;
+ } else if (tagText.equals("operation-failed")) {
+ tag = ErrorTag.OperationFailed;
+ } else if (tagText.equals("partial-operation")) {
+ tag = ErrorTag.PartialOperation;
+ }
+
+ return tag;
+ }
+
+ // Helper routine to check for the response received.
+ protected void printResponse() {
+ try {
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ DOMImplementationLS ls = (DOMImplementationLS)docBuilder.getDOMImplementation();
+ LSSerializer lss = ls.createLSSerializer();
+ System.out.println(lss.writeToString(_docResponse));
+ } catch (ParserConfigurationException e) {
+ s_logger.error("Error parsing the repsonse : " + e.toString());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/Adapter.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/Adapter.java b/utils/src/main/java/com/cloud/utils/component/Adapter.java
new file mode 100644
index 0000000..d50b8d9
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/Adapter.java
@@ -0,0 +1,27 @@
+//
+// 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 com.cloud.utils.component;
+
+/**
+ * Adapter defines methods for pluggable code within the Cloud Stack. An
+ * Adapters are a departure from regular structured programming.
+ */
+public interface Adapter extends ComponentLifecycle {
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/AdapterBase.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/AdapterBase.java b/utils/src/main/java/com/cloud/utils/component/AdapterBase.java
new file mode 100644
index 0000000..703b532
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/AdapterBase.java
@@ -0,0 +1,40 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.util.List;
+
+// Typical Adapter implementation.
+public class AdapterBase extends ComponentLifecycleBase implements Adapter, ComponentMethodInterceptable {
+
+ public AdapterBase() {
+ super();
+ // set default run level for adapter components
+ setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT);
+ }
+
+ public static <T extends Adapter> T getAdapterByName(List<T> adapters, String name) {
+ for (T adapter : adapters) {
+ if (adapter.getName() != null && adapter.getName().equalsIgnoreCase(name))
+ return adapter;
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/AdapterList.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/AdapterList.java b/utils/src/main/java/com/cloud/utils/component/AdapterList.java
new file mode 100644
index 0000000..dad3391
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/AdapterList.java
@@ -0,0 +1,37 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.component;
+
+import java.util.List;
+
+public class AdapterList<T extends Adapter> {
+ protected List<T> adapters;
+
+ public AdapterList() {
+ }
+
+ public List<T> getAdapters() {
+ return adapters;
+ }
+
+ public void setAdapters(List<T> adapters) {
+ this.adapters = adapters;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentContext.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentContext.java b/utils/src/main/java/com/cloud/utils/component/ComponentContext.java
new file mode 100644
index 0000000..8948b27
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentContext.java
@@ -0,0 +1,282 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+import org.springframework.aop.framework.Advised;
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.annotation.Primary;
+
+import com.cloud.utils.mgmt.JmxUtil;
+import com.cloud.utils.mgmt.ManagementBean;
+
+/**
+ *
+ * ComponentContext.setApplication() and ComponentContext.getApplication()
+ * are not recommended to be used outside, they exist to help wire Spring Framework
+ *
+ */
+@SuppressWarnings("unchecked")
+public class ComponentContext implements ApplicationContextAware {
+ private static final Logger s_logger = Logger.getLogger(ComponentContext.class);
+
+ private static ApplicationContext s_appContext;
+ private static Map<Class<?>, ApplicationContext> s_appContextDelegates;
+ private static boolean s_initializeBeans = true;
+
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) {
+ s_logger.info("Setup Spring Application context");
+ s_appContext = applicationContext;
+ }
+
+ public static ApplicationContext getApplicationContext() {
+ return s_appContext;
+ }
+
+ public static void initComponentsLifeCycle() {
+ if (!s_initializeBeans)
+ return;
+
+ AutowireCapableBeanFactory beanFactory = s_appContext.getAutowireCapableBeanFactory();
+
+ Map<String, ComponentMethodInterceptable> interceptableComponents = getApplicationContext().getBeansOfType(ComponentMethodInterceptable.class);
+ for (Map.Entry<String, ComponentMethodInterceptable> entry : interceptableComponents.entrySet()) {
+ Object bean = getTargetObject(entry.getValue());
+ beanFactory.configureBean(bean, entry.getKey());
+ }
+
+ Map<String, ComponentLifecycle> lifecycleComponents = getApplicationContext().getBeansOfType(ComponentLifecycle.class);
+
+ Map<String, ComponentLifecycle>[] classifiedComponents = new Map[ComponentLifecycle.MAX_RUN_LEVELS];
+ for (int i = 0; i < ComponentLifecycle.MAX_RUN_LEVELS; i++) {
+ classifiedComponents[i] = new HashMap<String, ComponentLifecycle>();
+ }
+
+ for (Map.Entry<String, ComponentLifecycle> entry : lifecycleComponents.entrySet()) {
+ classifiedComponents[entry.getValue().getRunLevel()].put(entry.getKey(), entry.getValue());
+ }
+
+ // Run the SystemIntegrityCheckers first
+ Map<String, SystemIntegrityChecker> integrityCheckers = getApplicationContext().getBeansOfType(SystemIntegrityChecker.class);
+ for (Entry<String, SystemIntegrityChecker> entry : integrityCheckers.entrySet()) {
+ s_logger.info("Running SystemIntegrityChecker " + entry.getKey());
+ try {
+ entry.getValue().check();
+ } catch (Throwable e) {
+ s_logger.error("System integrity check failed. Refuse to startup", e);
+ System.exit(1);
+ }
+ }
+
+ // configuration phase
+ Map<String, String> avoidMap = new HashMap<String, String>();
+ for (int i = 0; i < ComponentLifecycle.MAX_RUN_LEVELS; i++) {
+ for (Map.Entry<String, ComponentLifecycle> entry : classifiedComponents[i].entrySet()) {
+ ComponentLifecycle component = entry.getValue();
+ String implClassName = ComponentContext.getTargetClass(component).getName();
+ s_logger.info("Configuring " + implClassName);
+
+ if (avoidMap.containsKey(implClassName)) {
+ s_logger.info("Skip configuration of " + implClassName + " as it is already configured");
+ continue;
+ }
+
+ try {
+ component.configure(component.getName(), component.getConfigParams());
+ } catch (ConfigurationException e) {
+ s_logger.error("Unhandled exception", e);
+ throw new RuntimeException("Unable to configure " + implClassName, e);
+ }
+
+ avoidMap.put(implClassName, implClassName);
+ }
+ }
+
+ // starting phase
+ avoidMap.clear();
+ for (int i = 0; i < ComponentLifecycle.MAX_RUN_LEVELS; i++) {
+ for (Map.Entry<String, ComponentLifecycle> entry : classifiedComponents[i].entrySet()) {
+ ComponentLifecycle component = entry.getValue();
+ String implClassName = ComponentContext.getTargetClass(component).getName();
+ s_logger.info("Starting " + implClassName);
+
+ if (avoidMap.containsKey(implClassName)) {
+ s_logger.info("Skip configuration of " + implClassName + " as it is already configured");
+ continue;
+ }
+
+ try {
+ component.start();
+
+ if (getTargetObject(component) instanceof ManagementBean)
+ registerMBean((ManagementBean)getTargetObject(component));
+ } catch (Exception e) {
+ s_logger.error("Unhandled exception", e);
+ throw new RuntimeException("Unable to start " + implClassName, e);
+ }
+
+ avoidMap.put(implClassName, implClassName);
+ }
+ }
+ }
+
+ static void registerMBean(ManagementBean mbean) {
+ try {
+ JmxUtil.registerMBean(mbean);
+ } catch (MalformedObjectNameException e) {
+ s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
+ } catch (InstanceAlreadyExistsException e) {
+ s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
+ } catch (MBeanRegistrationException e) {
+ s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
+ } catch (NotCompliantMBeanException e) {
+ s_logger.warn("Unable to register MBean: " + mbean.getName(), e);
+ }
+ s_logger.info("Registered MBean: " + mbean.getName());
+ }
+
+ public static <T> T getComponent(String name) {
+ assert (s_appContext != null);
+ return (T)s_appContext.getBean(name);
+ }
+
+ public static <T> T getComponent(Class<T> beanType) {
+ assert (s_appContext != null);
+ Map<String, T> matchedTypes = getComponentsOfType(beanType);
+ if (matchedTypes.size() > 0) {
+ for (Map.Entry<String, T> entry : matchedTypes.entrySet()) {
+ Primary primary = getTargetClass(entry.getValue()).getAnnotation(Primary.class);
+ if (primary != null)
+ return entry.getValue();
+ }
+
+ if (matchedTypes.size() > 1) {
+ s_logger.warn("Unable to uniquely locate bean type " + beanType.getName());
+ for (Map.Entry<String, T> entry : matchedTypes.entrySet()) {
+ s_logger.warn("Candidate " + getTargetClass(entry.getValue()).getName());
+ }
+ }
+
+ return (T)matchedTypes.values().toArray()[0];
+ }
+
+ throw new NoSuchBeanDefinitionException(beanType.getName());
+ }
+
+ public static <T> Map<String, T> getComponentsOfType(Class<T> beanType) {
+ return s_appContext.getBeansOfType(beanType);
+ }
+
+ public static Class<?> getTargetClass(Object instance) {
+ while (instance instanceof Advised) {
+ try {
+ instance = ((Advised)instance).getTargetSource().getTarget();
+ } catch (Exception e) {
+ return instance.getClass();
+ }
+ }
+ return instance.getClass();
+ }
+
+ public static <T> T getTargetObject(Object instance) {
+ while (instance instanceof Advised) {
+ try {
+ instance = ((Advised)instance).getTargetSource().getTarget();
+ } catch (Exception e) {
+ return (T)instance;
+ }
+ }
+
+ return (T)instance;
+ }
+
+ public static <T> T inject(Class<T> clz) {
+ T instance;
+ try {
+ instance = clz.newInstance();
+ return inject(instance);
+ } catch (InstantiationException e) {
+ s_logger.error("Unhandled InstantiationException", e);
+ throw new RuntimeException("Unable to instantiate object of class " + clz.getName() + ", make sure it has public constructor");
+ } catch (IllegalAccessException e) {
+ s_logger.error("Unhandled IllegalAccessException", e);
+ throw new RuntimeException("Unable to instantiate object of class " + clz.getName() + ", make sure it has public constructor");
+ }
+ }
+
+ public static <T> T inject(Object instance) {
+ // autowire dynamically loaded object
+ AutowireCapableBeanFactory beanFactory = getApplicationContext(instance).getAutowireCapableBeanFactory();
+ beanFactory.autowireBean(instance);
+ return (T)instance;
+ }
+
+ private static ApplicationContext getApplicationContext(Object instance) {
+ ApplicationContext result = null;
+
+ synchronized (s_appContextDelegates) {
+ if (instance != null && s_appContextDelegates != null) {
+ result = s_appContextDelegates.get(instance.getClass());
+ }
+ }
+
+ return result == null ? s_appContext : result;
+ }
+
+ public static synchronized void addDelegateContext(Class<?> clazz, ApplicationContext context) {
+ if (s_appContextDelegates == null) {
+ s_appContextDelegates = new HashMap<Class<?>, ApplicationContext>();
+ }
+
+ s_appContextDelegates.put(clazz, context);
+ }
+
+ public static synchronized void removeDelegateContext(Class<?> clazz) {
+ if (s_appContextDelegates != null) {
+ s_appContextDelegates.remove(clazz);
+ }
+ }
+
+ public boolean isInitializeBeans() {
+ return s_initializeBeans;
+ }
+
+ public void setInitializeBeans(boolean initializeBeans) {
+ initInitializeBeans(initializeBeans);
+ }
+
+ private static synchronized void initInitializeBeans(boolean initializeBeans) {
+ s_initializeBeans = initializeBeans;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/com/cloud/utils/component/ComponentInstantiationPostProcessor.java
----------------------------------------------------------------------
diff --git a/utils/src/main/java/com/cloud/utils/component/ComponentInstantiationPostProcessor.java b/utils/src/main/java/com/cloud/utils/component/ComponentInstantiationPostProcessor.java
new file mode 100644
index 0000000..6704371
--- /dev/null
+++ b/utils/src/main/java/com/cloud/utils/component/ComponentInstantiationPostProcessor.java
@@ -0,0 +1,149 @@
+//
+// 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 com.cloud.utils.component;
+
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import net.sf.cglib.proxy.Callback;
+import net.sf.cglib.proxy.CallbackFilter;
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodInterceptor;
+import net.sf.cglib.proxy.MethodProxy;
+import net.sf.cglib.proxy.NoOp;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.PropertyValues;
+import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
+
+import com.cloud.utils.Pair;
+
+public class ComponentInstantiationPostProcessor implements InstantiationAwareBeanPostProcessor {
+ private static final Logger s_logger = Logger.getLogger(ComponentInstantiationPostProcessor.class);
+
+ private List<ComponentMethodInterceptor> _interceptors = new ArrayList<ComponentMethodInterceptor>();
+ private Callback[] _callbacks;
+ private CallbackFilter _callbackFilter;
+
+ public ComponentInstantiationPostProcessor() {
+ _callbacks = new Callback[2];
+ _callbacks[0] = NoOp.INSTANCE;
+ _callbacks[1] = new InterceptorDispatcher();
+
+ _callbackFilter = new InterceptorFilter();
+ }
+
+ public List<ComponentMethodInterceptor> getInterceptors() {
+ return _interceptors;
+ }
+
+ public void setInterceptors(List<ComponentMethodInterceptor> interceptors) {
+ _interceptors = interceptors;
+ }
+
+ private Callback[] getCallbacks() {
+ return _callbacks;
+ }
+
+ private CallbackFilter getCallbackFilter() {
+ return _callbackFilter;
+ }
+
+ @Override
+ public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
+ return bean;
+ }
+
+ @Override
+ public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
+ return bean;
+ }
+
+ @Override
+ public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
+ if (_interceptors != null && _interceptors.size() > 0) {
+ if (ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) {
+ Enhancer enhancer = new Enhancer();
+ enhancer.setSuperclass(beanClass);
+ enhancer.setCallbacks(getCallbacks());
+ enhancer.setCallbackFilter(getCallbackFilter());
+ enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE);
+
+ Object bean = enhancer.create();
+ return bean;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
+ return true;
+ }
+
+ @Override
+ public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
+ return pvs;
+ }
+
+ protected class InterceptorDispatcher implements MethodInterceptor {
+ @Override
+ public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
+ ArrayList<Pair<ComponentMethodInterceptor, Object>> interceptors = new ArrayList<Pair<ComponentMethodInterceptor, Object>>();
+
+ for (ComponentMethodInterceptor interceptor : getInterceptors()) {
+ if (interceptor.needToIntercept(method)) {
+ Object objReturnedInInterceptStart = interceptor.interceptStart(method, target);
+ interceptors.add(new Pair<ComponentMethodInterceptor, Object>(interceptor, objReturnedInInterceptStart));
+ }
+ }
+ boolean success = false;
+ try {
+ Object obj = methodProxy.invokeSuper(target, args);
+ success = true;
+ return obj;
+ } finally {
+ for (Pair<ComponentMethodInterceptor, Object> interceptor : interceptors) {
+ if (success) {
+ interceptor.first().interceptComplete(method, target, interceptor.second());
+ } else {
+ interceptor.first().interceptException(method, target, interceptor.second());
+ }
+ }
+ }
+ }
+ }
+
+ protected class InterceptorFilter implements CallbackFilter {
+ @Override
+ public int accept(Method method) {
+ for (ComponentMethodInterceptor interceptor : getInterceptors()) {
+
+ if (interceptor.needToIntercept(method)) {
+ return 1;
+ }
+ }
+ return 0;
+ }
+ }
+}