From 510972abde3b5435ed2a4d02fc4f59a1f6dabefe Mon Sep 17 00:00:00 2001 From: Antonio Fornie Date: Wed, 5 Feb 2014 10:01:06 +0100 Subject: [PATCH] Nvp and rest refactoring and more tests Signed-off-by: Hugo Trippaers --- .../network/nicira/AccessConfiguration.java | 90 +-- .../src/com/cloud/network/nicira/Acl.java | 1 - .../network/nicira/BaseNiciraEntity.java | 85 ++ ...Config.java => BaseNiciraNamedEntity.java} | 31 +- .../cloud/network/nicira/LogicalRouter.java | 71 ++ .../network/nicira/LogicalRouterPort.java | 41 +- .../cloud/network/nicira/LogicalSwitch.java | 68 +- .../network/nicira/LogicalSwitchPort.java | 50 +- .../cloud/network/nicira/NiciraNvpApi.java | 751 +++++++----------- ...gleDefaultRouteImplicitRoutingConfig.java} | 6 +- .../cloud/network/nicira/VifAttachment.java | 35 +- .../network/resource/NiciraNvpResource.java | 20 +- .../network/element/NiciraNvpElementTest.java | 42 +- .../guru/NiciraNvpGuestNetworkGuruTest.java | 154 ++-- .../com/cloud/network/nicira/NatRuleTest.java | 12 +- .../cloud/network/nicira/NiciraNvpApiIT.java | 200 ++++- .../network/nicira/NiciraNvpApiTest.java | 664 ++++++---------- .../cloud/network/nicira/NiciraTagTest.java | 8 +- .../resource/NiciraNvpResourceTest.java | 258 +++--- pom.xml | 6 + utils/pom.xml | 27 + .../BasicEncodedRESTValidationStrategy.java | 47 ++ .../utils/rest/CloudstackRESTException.java | 36 + .../utils/rest/RESTServiceConnector.java | 377 +++++++++ .../utils/rest/RESTValidationStrategy.java | 146 ++++ .../utils/rest/RESTServiceConnectorTest.java | 373 +++++++++ 26 files changed, 2211 insertions(+), 1388 deletions(-) create mode 100644 plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java rename plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/{LogicalRouterConfig.java => BaseNiciraNamedEntity.java} (62%) create mode 100644 plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java rename plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/{SingleDefaultRouteImplictRoutingConfig.java => SingleDefaultRouteImplicitRoutingConfig.java} (82%) create mode 100644 utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java create mode 100644 utils/src/com/cloud/utils/rest/CloudstackRESTException.java create mode 100644 utils/src/com/cloud/utils/rest/RESTServiceConnector.java create mode 100644 utils/src/com/cloud/utils/rest/RESTValidationStrategy.java create mode 100644 utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.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 index 487f14b3b8d..b5291dc3627 100644 --- 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 @@ -19,32 +19,12 @@ package com.cloud.network.nicira; -import java.io.Serializable; import java.util.List; -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 AccessConfiguration extends BaseNiciraNamedEntity { -@SuppressWarnings("serial") -public abstract class AccessConfiguration implements Serializable { - - protected String displayName; protected List logicalPortEgressRules; protected List logicalPortIngressRules; - protected List tags; - protected String uuid; - protected String href; - protected String schema; - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(final String displayName) { - this.displayName = displayName; - } public List getLogicalPortEgressRules() { return logicalPortEgressRules; @@ -61,72 +41,4 @@ public abstract class AccessConfiguration implements Seria public void setLogicalPortIngressRules(final List logicalPortIngressRules) { this.logicalPortIngressRules = logicalPortIngressRules; } - - 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; - } - - public List getTags() { - return tags; - } - - public void setTags(final List tags) { - this.tags = tags; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 31) - .append(displayName).append(logicalPortEgressRules) - .append(logicalPortIngressRules).append(tags) - .append(uuid).append(href).append(schema) - .toHashCode(); - } - - @Override - @SuppressWarnings("unchecked") - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(this.getClass().isInstance(obj))) { - return false; - } - final AccessConfiguration another = - (AccessConfiguration) obj; - return new EqualsBuilder() - .append(displayName, another.displayName) - .append(uuid, another.uuid) - .append(href, another.href) - .append(schema, another.schema) - .isEquals(); - } } 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 index 976177fdff8..870124ed603 100644 --- 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 @@ -19,6 +19,5 @@ package com.cloud.network.nicira; -@SuppressWarnings("serial") public class Acl extends AccessConfiguration { } 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 new file mode 100644 index 00000000000..afcd2333959 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/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(); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java similarity index 62% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java rename to plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java index b6eaa8f277a..0e21ddb74c4 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java @@ -21,45 +21,24 @@ package com.cloud.network.nicira; import java.util.List; -/** - * - */ -public class LogicalRouterConfig { - private String displayName; - private RoutingConfig routingConfig; - private final String type = "LogicalRouterConfig"; - private String uuid; - private List tags; +public abstract class BaseNiciraNamedEntity extends BaseNiciraEntity { - public RoutingConfig getRoutingConfig() { - return routingConfig; - } - - public void setRoutingConfig(RoutingConfig routingConfig) { - this.routingConfig = routingConfig; - } + protected String displayName; + protected List tags; public String getDisplayName() { return displayName; } - public void setDisplayName(String displayName) { + public void setDisplayName(final String displayName) { this.displayName = displayName; } - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - public List getTags() { return tags; } - public void setTags(List tags) { + public void setTags(final List tags) { this.tags = tags; } } 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 new file mode 100644 index 00000000000..edc93512229 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/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; + } +} 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 index 8ffe0546875..d9ee09ad6f8 100644 --- 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 @@ -21,24 +21,18 @@ package com.cloud.network.nicira; import java.util.List; -/** - * - */ -public class LogicalRouterPort { - private String displayName; - private List tags; +public class LogicalRouterPort extends BaseNiciraNamedEntity { private Integer portno; private boolean adminStatusEnabled; private List ipAddresses; private String macAddress; private final String type = "LogicalRouterPortConfig"; - private String uuid; public int getPortno() { return portno; } - public void setPortno(int portno) { + public void setPortno(final int portno) { this.portno = portno; } @@ -46,7 +40,7 @@ public class LogicalRouterPort { return adminStatusEnabled; } - public void setAdminStatusEnabled(boolean adminStatusEnabled) { + public void setAdminStatusEnabled(final boolean adminStatusEnabled) { this.adminStatusEnabled = adminStatusEnabled; } @@ -54,7 +48,7 @@ public class LogicalRouterPort { return ipAddresses; } - public void setIpAddresses(List ipAddresses) { + public void setIpAddresses(final List ipAddresses) { this.ipAddresses = ipAddresses; } @@ -62,32 +56,7 @@ public class LogicalRouterPort { return macAddress; } - public void setMacAddress(String macAddress) { + public void setMacAddress(final String macAddress) { this.macAddress = macAddress; } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - } \ No newline at end of file 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 index 23793549912..b527d94107d 100644 --- 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 @@ -21,29 +21,20 @@ package com.cloud.network.nicira; import java.util.List; -public class LogicalSwitch { - private String displayName; +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 tags; private List transportZones; - private String type; - private String uuid; - private String href; - private String schema; - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + private String replicationMode; public boolean isPortIsolationEnabled() { return portIsolationEnabled; } - public void setPortIsolationEnabled(boolean portIsolationEnabled) { + public void setPortIsolationEnabled(final boolean portIsolationEnabled) { this.portIsolationEnabled = portIsolationEnabled; } @@ -51,48 +42,19 @@ public class LogicalSwitch { return type; } - public void setType(String type) { - this.type = type; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getHref() { - return href; - } - - public void setHref(String href) { - this.href = href; - } - - public String getSchema() { - return schema; - } - - public void setSchema(String schema) { - this.schema = schema; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - public List getTransportZones() { return transportZones; } - public void setTransportZones(List transportZones) { + public void setTransportZones(final List transportZones) { this.transportZones = transportZones; } + public String getReplicationMode() { + return replicationMode; + } + + public void setReplicationMode(final String replicationMode) { + this.replicationMode = replicationMode; + } } 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 index 3565fbe8dbe..5e074235a74 100644 --- 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 @@ -21,16 +21,13 @@ package com.cloud.network.nicira; import java.util.List; -public class LogicalSwitchPort { - private String displayName; - private List tags; +public class LogicalSwitchPort extends BaseNiciraNamedEntity { private Integer portno; private boolean adminStatusEnabled; private String queueUuid; private List securityProfiles; private List mirrorTargets; - private String type; - private String uuid; + private final String type = "LogicalSwitchPortConfig"; public LogicalSwitchPort() { super(); @@ -43,27 +40,11 @@ public class LogicalSwitchPort { this.adminStatusEnabled = adminStatusEnabled; } - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - public Integer getPortno() { return portno; } - public void setPortno(Integer portno) { + public void setPortno(final Integer portno) { this.portno = portno; } @@ -71,7 +52,7 @@ public class LogicalSwitchPort { return adminStatusEnabled; } - public void setAdminStatusEnabled(boolean adminStatusEnabled) { + public void setAdminStatusEnabled(final boolean adminStatusEnabled) { this.adminStatusEnabled = adminStatusEnabled; } @@ -79,7 +60,7 @@ public class LogicalSwitchPort { return queueUuid; } - public void setQueueUuid(String queueUuid) { + public void setQueueUuid(final String queueUuid) { this.queueUuid = queueUuid; } @@ -87,7 +68,7 @@ public class LogicalSwitchPort { return securityProfiles; } - public void setSecurityProfiles(List securityProfiles) { + public void setSecurityProfiles(final List securityProfiles) { this.securityProfiles = securityProfiles; } @@ -95,24 +76,7 @@ public class LogicalSwitchPort { return mirrorTargets; } - public void setMirrorTargets(List mirrorTargets) { + public void setMirrorTargets(final List mirrorTargets) { this.mirrorTargets = mirrorTargets; } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - } 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 index 83d00752665..3861d6392e6 100644 --- 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 @@ -18,55 +18,14 @@ // package com.cloud.network.nicira; - -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.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.UUID; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -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 com.google.gson.FieldNamingPolicy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; @@ -74,33 +33,24 @@ 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"; - 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; + 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 int HTTPS_PORT = 443; - private static final Logger s_logger = Logger.getLogger(NiciraNvpApi.class); - private final static String protocol = "https"; - private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); + private static final String LOGIN_URL = "/ws.v1/login"; - private String host; - private String adminuser; - private String adminpass; - - private final HttpClient client; - private String nvpVersion; - - private final Gson gson; + protected RESTServiceConnector restConnector; protected final static Map prefixMap; @@ -112,115 +62,174 @@ public class NiciraNvpApi { prefixMap = new HashMap(); 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(); listTypeMap.put(SecurityProfile.class, new TypeToken>() { }.getType()); listTypeMap.put(Acl.class, new TypeToken>() { }.getType()); + listTypeMap.put(LogicalSwitch.class, new TypeToken>() { + }.getType()); + listTypeMap.put(LogicalRouter.class, new TypeToken>() { + }.getType()); defaultListParams = new HashMap(); defaultListParams.put("fields", "*"); } - /* This factory method is protected so we can extend this - * in the unittests. - */ - protected HttpClient createHttpClient() { - return new HttpClient(s_httpClientManager); - } - - protected HttpMethod createMethod(final String type, final String uri) throws NiciraNvpApiException { - String url; - try { - url = new URL(protocol, host, uri).toString(); - } catch (final MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("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 NiciraNvpApiException("Requesting unknown method type"); - } - } - public NiciraNvpApi() { - client = createHttpClient(); - client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); + final List> classList = new ArrayList>(); + classList.add(NatRule.class); + classList.add(RoutingConfig.class); + final List> deserializerList = new ArrayList>(); + deserializerList.add(new NatRuleAdapter()); + deserializerList.add(new RoutingConfigAdapter()); - 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); - } + restConnector = new RESTServiceConnector(new RESTValidationStrategy(LOGIN_URL), classList, deserializerList); + } - gson = new GsonBuilder().registerTypeAdapter(NatRule.class, new NatRuleAdapter()).setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + 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) { - host = address; + restConnector.setControllerAddress(address); } public void setAdminCredentials(final String username, final String password) { - adminuser = username; - adminpass = password; + restConnector.setAdminCredentials(username, password); } /** - * Logs into the Nicira API. The cookie is stored in the _authcookie variable. - *

- * The method returns false if the login failed or the connection could not be made. + * POST * + * @param entity + * @return + * @throws NiciraNvpApiException */ - protected void login() throws NiciraNvpApiException { - String url; - - if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); - } + protected 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 createWithUri(final T entity, final String uri) throws NiciraNvpApiException { + T createdEntity; try { - url = new URL(protocol, host, "/ws.v1/login").toString(); - } catch (final MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("Unable to build Nicira API URL", e); + createdEntity = restConnector.executeCreateObject(entity, new TypeToken() { + }.getType(), uri, Collections. emptyMap()); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); } - final PostMethod pm = new PostMethod(url); - pm.addParameter("username", adminuser); - pm.addParameter("password", adminpass); + return createdEntity; + } + /** + * GET list of items + * + * @return + * @throws NiciraNvpApiException + */ + protected NiciraNvpList find(final Class clazz) throws NiciraNvpApiException { + return find(null, clazz); + } + + /** + * GET list of items + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList find(final String uuid, final Class clazz) throws NiciraNvpApiException { + final String uri = prefixMap.get(clazz); + Map params = defaultListParams; + if (uuid != null) { + params = new HashMap(defaultListParams); + params.put("uuid", uuid); + } + + NiciraNvpList entities; try { - client.executeMethod(pm); - } catch (final HttpException e) { - throw new NiciraNvpApiException("Nicira NVP API login failed ", e); - } catch (final IOException e) { - throw new NiciraNvpApiException("Nicira NVP API login failed ", e); - } finally { - pm.releaseConnection(); + entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); } - if (pm.getStatusCode() != HttpStatus.SC_OK) { - s_logger.error("Nicira NVP API login failed : " + pm.getStatusText()); - throw new NiciraNvpApiException("Nicira NVP API login failed " + pm.getStatusText()); + if (entities == null) { + throw new NiciraNvpApiException("Unexpected response from API"); } - // Extract the version for later use - if (pm.getResponseHeader("Server") != null) { - nvpVersion = pm.getResponseHeader("Server").getValue(); - s_logger.debug("NVP Controller reports version " + nvpVersion); - } + return entities; + } - // Success; the cookie required for login is kept in _client + /** + * PUT item given a UUID as key and an item object + * with the new data + * + * @param item + * @param uuid + * @throws NiciraNvpApiException + */ + public 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 void updateWithUri(final T item, final String uri) + throws NiciraNvpApiException { + try { + restConnector.executeUpdateObject(item, uri, Collections. emptyMap()); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + /** + * DELETE Security Profile given a UUID as key + * + * @param securityProfileUuid + * @throws NiciraNvpApiException + */ + public void delete(final String uuid, final Class 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 void deleteWithUri(final String uri) + throws NiciraNvpApiException { + try { + restConnector.executeDeleteObject(uri); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } } /** @@ -341,111 +350,68 @@ public class NiciraNvpApi { delete(aclUuid, Acl.class); } - /** - * POST - * - * @param entity - * @return - * @throws NiciraNvpApiException - */ - protected T create(final T entity) throws NiciraNvpApiException { - final String uri = prefixMap.get(entity.getClass()); - final T createdEntity = executeCreateObject(entity, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); - - return createdEntity; + public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException { + return create(logicalSwitch); } /** - * GET list of items + * GET list of {@link LogicalSwitch} * * @return * @throws NiciraNvpApiException */ - protected NiciraNvpList find(final Class clazz) throws NiciraNvpApiException { - return find(null, clazz); + public NiciraNvpList findLogicalSwitch() throws NiciraNvpApiException { + return findLogicalSwitch(null); } /** - * GET list of items + * GET list of {@link LogicalSwitch} filtered by UUID * * @param uuid * @return * @throws NiciraNvpApiException */ - public NiciraNvpList find(final String uuid, final Class clazz) throws NiciraNvpApiException { - final String uri = prefixMap.get(clazz); - Map params = defaultListParams; - if (uuid != null) { - params = new HashMap(defaultListParams); - params.put("uuid", uuid); - } - - final NiciraNvpList entities = executeRetrieveObject(listTypeMap.get(clazz), uri, params); - - if (entities == null) { - throw new NiciraNvpApiException("Unexpected response from API"); - } - - return entities; + public NiciraNvpList findLogicalSwitch(final String uuid) throws NiciraNvpApiException { + return find(uuid, LogicalSwitch.class); } /** - * PUT item given a UUID as key and an item object + * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch} * with the new data * - * @param item - * @param uuid + * @param logicalSwitch + * @param logicalSwitchUuid * @throws NiciraNvpApiException */ - public void update(final T item, - final String uuid) + public void updateLogicalSwitch(final LogicalSwitch logicalSwitch, + final String logicalSwitchUuid) throws NiciraNvpApiException { - final String uri = prefixMap.get(item.getClass()) + "/" + uuid; - executeUpdateObject(item, uri, Collections. emptyMap()); - } - - /** - * DELETE Security Profile given a UUID as key - * - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - public void delete(final String uuid, final Class clazz) - throws NiciraNvpApiException { - final String uri = prefixMap.get(clazz) + "/" + uuid; - executeDeleteObject(uri); - } - - public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX; - final LogicalSwitch createdLogicalSwitch = executeCreateObject(logicalSwitch, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); - - return createdLogicalSwitch; + update(logicalSwitch, logicalSwitchUuid); } public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + uuid; - executeDeleteObject(uri); + delete(uuid, LogicalSwitch.class); } public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; - final LogicalSwitchPort createdLogicalSwitchPort = executeCreateObject(logicalSwitchPort, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); - - return createdLogicalSwitchPort; + return createWithUri(logicalSwitchPort, uri); } - public void modifyLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException { + 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"; - executeUpdateObject(attachment, uri, Collections. emptyMap()); + updateWithUri(attachment, uri); } public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid; - executeDeleteObject(uri); + deleteWithUri(uri); } public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException { @@ -454,8 +420,13 @@ public class NiciraNvpApi { params.put("attachment_vif_uuid", vifAttachmentUuid); params.put("fields", "uuid"); - final NiciraNvpList lspl = executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); + NiciraNvpList lspl; + try { + lspl = restConnector.executeRetrieveObject(new TypeToken>() { + }.getType(), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } if (lspl == null || lspl.getResultCount() != 1) { throw new NiciraNvpApiException("Unexpected response from API"); @@ -467,8 +438,13 @@ public class NiciraNvpApi { public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { final String uri = "/ws.v1/control-cluster/status"; - final ControlClusterStatus ccs = executeRetrieveObject(new TypeToken() { - }.getType(), uri, null); + ControlClusterStatus ccs; + try { + ccs = restConnector.executeRetrieveObject(new TypeToken() { + }.getType(), uri, null); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } return ccs; } @@ -479,8 +455,13 @@ public class NiciraNvpApi { params.put("uuid", logicalSwitchPortUuid); params.put("fields", "uuid"); - final NiciraNvpList lspl = executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); + NiciraNvpList lspl; + try { + lspl = restConnector.executeRetrieveObject(new TypeToken>() { + }.getType(), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } if (lspl == null) { throw new NiciraNvpApiException("Unexpected response from API"); @@ -489,64 +470,101 @@ public class NiciraNvpApi { return lspl; } - public LogicalRouterConfig createLogicalRouter(final LogicalRouterConfig logicalRouterConfig) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX; + public NiciraNvpList findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; + final Map params = new HashMap(); + params.put("uuid", logicalRouterPortUuid); + params.put("fields", "uuid"); - final LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); + NiciraNvpList lrpl; + try { + lrpl = restConnector.executeRetrieveObject(new TypeToken>() { + }.getType(), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } - return lrc; + 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 findLogicalRouter() throws NiciraNvpApiException { + return findLogicalRouter(null); + } + + /** + * GET list of {@link LogicalRouter} filtered by UUID + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList 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; - - executeDeleteObject(uri); + deleteWithUri(uri); } public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; - - final LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); - return lrp; + return createWithUri(logicalRouterPort, uri); } public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; - - executeDeleteObject(uri); + deleteWithUri(uri); } - public void modifyLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { + public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); - - executeUpdateObject(logicalRouterPort, uri, Collections. emptyMap()); + updateWithUri(logicalRouterPort, uri); } - public void modifyLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) + public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; - executeUpdateObject(attachment, uri, Collections. emptyMap()); + updateWithUri(attachment, uri); } public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat"; - - return executeCreateObject(natRule, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); + return createWithUri(natRule, uri); } - public void modifyLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { + public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); - - executeUpdateObject(natRule, uri, Collections. emptyMap()); + updateWithUri(natRule, uri); } public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException { final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); - - executeDeleteObject(uri); + deleteWithUri(uri); } public NiciraNvpList findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, @@ -557,21 +575,12 @@ public class NiciraNvpApi { params.put("attachment_vlan", "0"); params.put("fields", "*"); - return executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); - } - - public LogicalRouterConfig findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid; - - return executeRetrieveObject(new TypeToken() { - }.getType(), uri, Collections. emptyMap()); - } - - public void updateLogicalRouterPortConfig(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid(); - - executeUpdateObject(logicalRouterPort, uri, Collections. emptyMap()); + try { + return restConnector.executeRetrieveObject(new TypeToken>() { + }.getType(), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } } public NiciraNvpList findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException { @@ -579,8 +588,12 @@ public class NiciraNvpApi { final Map params = new HashMap(); params.put("fields", "*"); - return executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); + try { + return restConnector.executeRetrieveObject(new TypeToken>() { + }.getType(), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } } public NiciraNvpList findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid) @@ -590,231 +603,11 @@ public class NiciraNvpApi { params.put("fields", "*"); params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); - return executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); - } - - protected void executeUpdateObject(final T newObject, final String uri, final Map parameters) throws NiciraNvpApiException { - if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); - } - - 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 NiciraNvpApiException("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 NiciraNvpApiException("Failed to update object : " + errorMessage); - } - pm.releaseConnection(); - } - - @SuppressWarnings("unchecked") - protected T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map parameters) - throws NiciraNvpApiException { - if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); - } - - 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 NiciraNvpApiException("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 NiciraNvpApiException("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 NiciraNvpApiException("Failed to decode json response body", e); - } finally { - pm.releaseConnection(); - } - - return result; - } - - protected void executeDeleteObject(final String uri) throws NiciraNvpApiException { - if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); - } - - 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 NiciraNvpApiException("Failed to delete object : " + errorMessage); - } - dm.releaseConnection(); - } - - @SuppressWarnings("unchecked") - protected T executeRetrieveObject(final Type returnObjectType, final String uri, final Map parameters) throws NiciraNvpApiException { - if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { - throw new NiciraNvpApiException("Hostname/credentials are null or empty"); - } - - final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri); - gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); - if (parameters != null && !parameters.isEmpty()) { - final List nameValuePairs = new ArrayList(parameters.size()); - for (final Entry 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 NiciraNvpApiException("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); + return restConnector.executeRetrieveObject(new TypeToken>() { + }.getType(), uri, params); + } catch (final CloudstackRESTException e) { throw new NiciraNvpApiException(e); - } finally { - gm.releaseConnection(); - } - return returnValue; - } - - protected void executeMethod(final HttpMethodBase method) throws NiciraNvpApiException { - try { - client.executeMethod(method); - if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - method.releaseConnection(); - // login and try again - login(); - client.executeMethod(method); - } - } catch (final HttpException e) { - s_logger.error("HttpException caught while trying to connect to the Nicira NVP Controller", e); - method.releaseConnection(); - throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); - } catch (final IOException e) { - s_logger.error("IOException caught while trying to connect to the Nicira NVP Controller", e); - method.releaseConnection(); - throw new NiciraNvpApiException("API call to Nicira NVP Controller 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(); - } - - /* The Nicira controller uses 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 = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - ssf = sc.getSocketFactory(); - } 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 { - return ssf.createSocket(host, port); - } - - @Override - public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException { - return ssf.createSocket(address, port, localAddress, localPort); - } - - @Override - public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { - return ssf.createSocket(socket, host, port, autoClose); - } - - @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) { - return createSocket(host, port, localAddress, localPort); - } else { - final Socket s = ssf.createSocket(); - s.bind(new InetSocketAddress(localAddress, localPort)); - s.connect(new InetSocketAddress(host, port), timeout); - return s; - } } } @@ -837,6 +630,24 @@ public class NiciraNvpApi { throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\""); } + } + public static class RoutingConfigAdapter implements JsonDeserializer { + + @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 ("SingleDefaultRouteImplicitRoutingConfig".equals(routingConfigType)) { + return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class); + } + + throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\""); + } } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java similarity index 82% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java rename to plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java index 05335791b95..ea5df2cd1fd 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java @@ -22,11 +22,11 @@ package com.cloud.network.nicira; /** * */ -public class SingleDefaultRouteImplictRoutingConfig extends RoutingConfig { +public class SingleDefaultRouteImplicitRoutingConfig extends RoutingConfig { public RouterNextHop defaultRouteNextHop; public final String type = "SingleDefaultRouteImplicitRoutingConfig"; - public SingleDefaultRouteImplictRoutingConfig(RouterNextHop routerNextHop) { + public SingleDefaultRouteImplicitRoutingConfig(final RouterNextHop routerNextHop) { defaultRouteNextHop = routerNextHop; } @@ -34,7 +34,7 @@ public class SingleDefaultRouteImplictRoutingConfig extends RoutingConfig { return defaultRouteNextHop; } - public void setDefaultRouteNextHop(RouterNextHop defaultRouteNextHop) { + public void setDefaultRouteNextHop(final RouterNextHop defaultRouteNextHop) { this.defaultRouteNextHop = defaultRouteNextHop; } } 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 index 87765be12a2..fe7d93adead 100644 --- 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 @@ -19,6 +19,11 @@ 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; @@ -34,7 +39,7 @@ public class VifAttachment extends Attachment { return vifUuid; } - public void setVifUuid(String vifUuid) { + public void setVifUuid(final String vifUuid) { this.vifUuid = vifUuid; } @@ -42,4 +47,32 @@ public class VifAttachment extends Attachment { 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(); + } } 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 index c228b08d5ee..ec95ea5a1b1 100644 --- 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 @@ -66,7 +66,7 @@ import com.cloud.host.Host.Type; import com.cloud.network.nicira.ControlClusterStatus; import com.cloud.network.nicira.DestinationNatRule; import com.cloud.network.nicira.L3GatewayAttachment; -import com.cloud.network.nicira.LogicalRouterConfig; +import com.cloud.network.nicira.LogicalRouter; import com.cloud.network.nicira.LogicalRouterPort; import com.cloud.network.nicira.LogicalSwitch; import com.cloud.network.nicira.LogicalSwitchPort; @@ -78,7 +78,7 @@ import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.nicira.NiciraNvpTag; import com.cloud.network.nicira.PatchAttachment; import com.cloud.network.nicira.RouterNextHop; -import com.cloud.network.nicira.SingleDefaultRouteImplictRoutingConfig; +import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig; import com.cloud.network.nicira.SourceNatRule; import com.cloud.network.nicira.TransportZoneBinding; import com.cloud.network.nicira.VifAttachment; @@ -294,7 +294,7 @@ public class NiciraNvpResource implements ServerResource { LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true); LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort); try { - niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); + niciraNvpApi.updateLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); } catch (NiciraNvpApiException ex) { s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport"); niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid()); @@ -334,7 +334,7 @@ public class NiciraNvpResource implements ServerResource { List tags = new ArrayList(); tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName())); - niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid)); + niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid)); return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid); } catch (NiciraNvpApiException e) { if (numRetries > 0) { @@ -383,10 +383,10 @@ public class NiciraNvpResource implements ServerResource { try { // Create the Router - LogicalRouterConfig lrc = new LogicalRouterConfig(); + LogicalRouter lrc = new LogicalRouter(); lrc.setDisplayName(truncate(routerName, NAME_MAX_LEN)); lrc.setTags(tags); - lrc.setRoutingConfig(new SingleDefaultRouteImplictRoutingConfig(new RouterNextHop(publicNetworkNextHopIp))); + lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp))); lrc = niciraNvpApi.createLogicalRouter(lrc); // store the switchport for rollback @@ -408,7 +408,7 @@ public class NiciraNvpResource implements ServerResource { if (cmd.getVlanId() != 0) { attachment.setVlanId(cmd.getVlanId()); } - niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); + niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); // Create the inside port for the router LogicalRouterPort lrpi = new LogicalRouterPort(); @@ -425,10 +425,10 @@ public class NiciraNvpResource implements ServerResource { lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp); // Attach the inside router port to the lswitch port with a PatchAttachment - niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid())); + niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid())); // Attach the inside lswitch port to the router with a PatchAttachment - niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid())); + niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid())); // Setup the source nat rule SourceNatRule snr = new SourceNatRule(); @@ -484,7 +484,7 @@ public class NiciraNvpResource implements ServerResource { } LogicalRouterPort lrp = ports.getResults().get(0); lrp.setIpAddresses(cmd.getPublicCidrs()); - niciraNvpApi.modifyLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); + niciraNvpApi.updateLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + " ip addresses on logical router uuid " + cmd.getLogicalRouterUuid()); 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 index 822c8c7ee93..bf8ce18491d 100644 --- 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 @@ -104,7 +104,7 @@ public class NiciraNvpElementTest { @Test public void canHandleTest() { - Network net = mock(Network.class); + final Network net = mock(Network.class); when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(net.getId()).thenReturn(NETWORK_ID); @@ -134,43 +134,43 @@ public class NiciraNvpElementTest { @Test public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - Network network = mock(Network.class); + final Network network = mock(Network.class); when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(network.getId()).thenReturn(NETWORK_ID); - NetworkOffering offering = mock(NetworkOffering.class); + 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); - Domain dom = mock(Domain.class); + final Domain dom = mock(Domain.class); when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); + final Account acc = mock(Account.class); when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext context = mock(ReservationContext.class); + final ReservationContext context = mock(ReservationContext.class); when(context.getDomain()).thenReturn(dom); when(context.getAccount()).thenReturn(acc); } @Test public void applyIpTest() throws ResourceUnavailableException { - Network network = mock(Network.class); + final Network network = mock(Network.class); when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(network.getId()).thenReturn(NETWORK_ID); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); - List ipAddresses = new ArrayList(); - PublicIpAddress pipReleased = mock(PublicIpAddress.class); - PublicIpAddress pipAllocated = mock(PublicIpAddress.class); - Ip ipReleased = new Ip("42.10.10.10"); - Ip ipAllocated = new Ip("10.10.10.10"); + final List ipAddresses = new ArrayList(); + 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"); @@ -180,25 +180,25 @@ public class NiciraNvpElementTest { ipAddresses.add(pipAllocated); ipAddresses.add(pipReleased); - Set services = new HashSet(); + final Set services = new HashSet(); services.add(Service.SourceNat); services.add(Service.StaticNat); services.add(Service.PortForwarding); - List deviceList = new ArrayList(); - NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class); - NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class); + final List deviceList = new ArrayList(); + 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); - HostVO hvo = mock(HostVO.class); + 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); - ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class); + final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class); when(answer.getResult()).thenReturn(true); when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer); @@ -206,8 +206,8 @@ public class NiciraNvpElementTest { verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher() { @Override - public boolean matches(Object argument) { - ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument; + public boolean matches(final Object argument) { + final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument; if (command.getPublicCidrs().size() == 1) return true; return false; 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 index db8637ccfb6..fb103e8aaac 100644 --- 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 @@ -99,7 +99,7 @@ public class NiciraNvpGuestNetworkGuruTest { guru.agentMgr = agentmgr; guru.networkDao = netdao; - DataCenterVO dc = mock(DataCenterVO.class); + final DataCenterVO dc = mock(DataCenterVO.class); when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); @@ -108,12 +108,12 @@ public class NiciraNvpGuestNetworkGuruTest { @Test public void testCanHandle() { - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getId()).thenReturn(NETWORK_ID); @@ -142,34 +142,34 @@ public class NiciraNvpGuestNetworkGuruTest { @Test public void testDesign() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(device.getId()).thenReturn(1L); - NetworkOffering offering = mock(NetworkOffering.class); + 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); - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); - Network designednetwork = guru.design(offering, plan, network, account); + final Network designednetwork = guru.design(offering, plan, network, account); assertTrue(designednetwork != null); assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); } @Test public void testDesignNoElementOnPhysicalNetwork() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); @@ -177,22 +177,22 @@ public class NiciraNvpGuestNetworkGuruTest { mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections. emptyList()); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); - Network designednetwork = guru.design(offering, plan, network, account); + final Network designednetwork = guru.design(offering, plan, network, account); assertTrue(designednetwork == null); } @Test public void testDesignNoIsolationMethodSTT() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); @@ -200,57 +200,57 @@ public class NiciraNvpGuestNetworkGuruTest { mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections. emptyList()); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); - Network designednetwork = guru.design(offering, plan, network, account); + final Network designednetwork = guru.design(offering, plan, network, account); assertTrue(designednetwork == null); } @Test public void testDesignNoConnectivityInOffering() { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(device.getId()).thenReturn(1L); - NetworkOffering offering = mock(NetworkOffering.class); + 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); - DeploymentPlan plan = mock(DeploymentPlan.class); - Network network = mock(Network.class); - Account account = mock(Account.class); + final DeploymentPlan plan = mock(DeploymentPlan.class); + final Network network = mock(Network.class); + final Account account = mock(Account.class); - Network designednetwork = guru.design(offering, plan, network, account); + final Network designednetwork = guru.design(offering, plan, network, account); assertTrue(designednetwork == null); } @Test public void testImplement() throws InsufficientVirtualNetworkCapcityException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(device.getId()).thenReturn(1L); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); @@ -259,53 +259,53 @@ public class NiciraNvpGuestNetworkGuruTest { mock(DeploymentPlan.class); - NetworkVO network = mock(NetworkVO.class); + final NetworkVO network = mock(NetworkVO.class); when(network.getName()).thenReturn("testnetwork"); when(network.getState()).thenReturn(State.Implementing); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - DeployDestination dest = mock(DeployDestination.class); + final DeployDestination dest = mock(DeployDestination.class); - DataCenter dc = mock(DataCenter.class); + final DataCenter dc = mock(DataCenter.class); when(dest.getDataCenter()).thenReturn(dc); - HostVO niciraHost = mock(HostVO.class); + 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); - Domain dom = mock(Domain.class); + final Domain dom = mock(Domain.class); when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); + final Account acc = mock(Account.class); when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); + final ReservationContext res = mock(ReservationContext.class); when(res.getDomain()).thenReturn(dom); when(res.getAccount()).thenReturn(acc); - CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + 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); - Network implementednetwork = guru.implement(network, offering, dest, res); + 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 InsufficientVirtualNetworkCapcityException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(device.getId()).thenReturn(1L); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); @@ -314,39 +314,39 @@ public class NiciraNvpGuestNetworkGuruTest { mock(DeploymentPlan.class); - NetworkVO network = mock(NetworkVO.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); - DeployDestination dest = mock(DeployDestination.class); + final DeployDestination dest = mock(DeployDestination.class); - DataCenter dc = mock(DataCenter.class); + final DataCenter dc = mock(DataCenter.class); when(dest.getDataCenter()).thenReturn(dc); - HostVO niciraHost = mock(HostVO.class); + 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); - Domain dom = mock(Domain.class); + final Domain dom = mock(Domain.class); when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); + final Account acc = mock(Account.class); when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); + final ReservationContext res = mock(ReservationContext.class); when(res.getDomain()).thenReturn(dom); when(res.getAccount()).thenReturn(acc); - CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + 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); - Network implementednetwork = guru.implement(network, offering, dest, res); + 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")); @@ -355,16 +355,16 @@ public class NiciraNvpGuestNetworkGuruTest { @Test public void testImplementURIException() throws InsufficientVirtualNetworkCapcityException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(device.getId()).thenReturn(1L); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); @@ -373,53 +373,53 @@ public class NiciraNvpGuestNetworkGuruTest { mock(DeploymentPlan.class); - NetworkVO network = mock(NetworkVO.class); + final NetworkVO network = mock(NetworkVO.class); when(network.getName()).thenReturn("testnetwork"); when(network.getState()).thenReturn(State.Implementing); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - DeployDestination dest = mock(DeployDestination.class); + final DeployDestination dest = mock(DeployDestination.class); - DataCenter dc = mock(DataCenter.class); + final DataCenter dc = mock(DataCenter.class); when(dest.getDataCenter()).thenReturn(dc); - HostVO niciraHost = mock(HostVO.class); + 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); - Domain dom = mock(Domain.class); + final Domain dom = mock(Domain.class); when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); + final Account acc = mock(Account.class); when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); + final ReservationContext res = mock(ReservationContext.class); when(res.getDomain()).thenReturn(dom); when(res.getAccount()).thenReturn(acc); - CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + 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); - Network implementednetwork = guru.implement(network, offering, dest, res); + 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 InsufficientVirtualNetworkCapcityException, URISyntaxException { - PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + 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); - NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(device.getId()).thenReturn(1L); - NetworkOffering offering = mock(NetworkOffering.class); + final NetworkOffering offering = mock(NetworkOffering.class); when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getGuestType()).thenReturn(GuestType.Isolated); @@ -428,7 +428,7 @@ public class NiciraNvpGuestNetworkGuruTest { mock(DeploymentPlan.class); - NetworkVO network = mock(NetworkVO.class); + final NetworkVO network = mock(NetworkVO.class); when(network.getName()).thenReturn("testnetwork"); when(network.getState()).thenReturn(State.Implementing); when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); @@ -436,31 +436,31 @@ public class NiciraNvpGuestNetworkGuruTest { when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); when(netdao.findById(NETWORK_ID)).thenReturn(network); - DeployDestination dest = mock(DeployDestination.class); + final DeployDestination dest = mock(DeployDestination.class); - DataCenter dc = mock(DataCenter.class); + final DataCenter dc = mock(DataCenter.class); when(dest.getDataCenter()).thenReturn(dc); - HostVO niciraHost = mock(HostVO.class); + 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); - Domain dom = mock(Domain.class); + final Domain dom = mock(Domain.class); when(dom.getName()).thenReturn("domain"); - Account acc = mock(Account.class); + final Account acc = mock(Account.class); when(acc.getAccountName()).thenReturn("accountname"); - ReservationContext res = mock(ReservationContext.class); + final ReservationContext res = mock(ReservationContext.class); when(res.getDomain()).thenReturn(dom); when(res.getAccount()).thenReturn(acc); - DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); + final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); when(answer.getResult()).thenReturn(true); when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - NetworkProfile implementednetwork = mock(NetworkProfile.class); + 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); 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 index 84b28fb8da8..d4c65969ec0 100644 --- 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 @@ -31,22 +31,22 @@ public class NatRuleTest { @Test public void testNatRuleEncoding() { - Gson gson = - new GsonBuilder().registerTypeAdapter(NatRule.class, new com.cloud.network.nicira.NiciraNvpApi.NatRuleAdapter()) + final Gson gson = + new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); - DestinationNatRule rn1 = new DestinationNatRule(); + final DestinationNatRule rn1 = new DestinationNatRule(); rn1.setToDestinationIpAddress("10.10.10.10"); rn1.setToDestinationPort(80); - Match mr1 = new Match(); + final Match mr1 = new Match(); mr1.setSourceIpAddresses("11.11.11.11/24"); mr1.setEthertype("IPv4"); mr1.setProtocol(6); rn1.setMatch(mr1); - String jsonString = gson.toJson(rn1); - NatRule dnr = gson.fromJson(jsonString, NatRule.class); + final String jsonString = gson.toJson(rn1); + final NatRule dnr = gson.fromJson(jsonString, NatRule.class); assertTrue(dnr instanceof DestinationNatRule); assertTrue(rn1.equals(dnr)); 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 index 7f8f471595a..ec4ce092700 100644 --- 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 @@ -19,14 +19,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.Assert; import org.junit.Before; import org.junit.Test; @@ -84,22 +85,22 @@ public class NiciraNvpApiIT { scInList = iProfile; } } - Assert.assertEquals("Read a Security Profile different from the one just created and updated", + 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()); - Assert.assertEquals("Read a Security Profile different from the one just created and updated", + assertEquals("Read a Security Profile different from the one just created and updated", sProfile, profiles.getResults().get(0)); - Assert.assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", + 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 creating Security Profile", false); + assertTrue("Errors in Security Profile CRUD", false); } } @@ -145,22 +146,203 @@ public class NiciraNvpApiIT { scInList = iAcl; } } - Assert.assertEquals("Read a ACL different from the one just created and updated", + 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()); - Assert.assertEquals("Read a ACL different from the one just created and updated", + assertEquals("Read a ACL different from the one just created and updated", acl, acls.getResults().get(0)); - Assert.assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", + 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 creating ACL", false); + 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()); + 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 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 tags = new ArrayList(); + 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 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 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 tags = new ArrayList(); + 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 ipAddresses = new ArrayList(); + // 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 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); + } + } 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 index 13d970c1cbc..fe41545d669 100644 --- 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 @@ -19,457 +19,289 @@ package com.cloud.network.nicira; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; -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.commons.httpclient.NameValuePair; -import org.apache.http.HttpStatus; -import org.junit.Before; import org.junit.Test; +import com.google.gson.Gson; +import com.google.gson.JsonParseException; + 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 DISPLAY_NAME = "myTestName"; - protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; - protected static final String SEC_PROFILE_JSON_RESPONSE = - "{\"uuid\" : \"aaaa\"," - + "\"display_name\" : \"myTestName\"," - + "\"href\" : \"myTestHref\"," - + "\"schema\" : \"myTestSchema\"}"; +// 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 DISPLAY_NAME = "myTestName"; +// protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; +// 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() { +// @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 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","*") +// }; +// +// // Execute +// final NiciraNvpList actualProfiles = api.findSecurityProfile(UUID); +// +// // 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 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); +// } - 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() { - @Override - protected HttpClient createHttpClient() { - return client; - } - - @Override - protected HttpMethod createMethod(final String newType, final String newUri) { - type = newType; - uri = newUri; - return method; - } - }; - api.setAdminCredentials("admin", "adminpass"); - api.setControllerAddress("localhost"); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteLoginWithoutHostname() throws NiciraNvpApiException { - api.setControllerAddress(null); - api.login(); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteLoginWithoutCredentials() throws NiciraNvpApiException { - api.setAdminCredentials(null, null); - api.login(); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteUpdateObjectWithoutHostname() throws NiciraNvpApiException { - api.setControllerAddress(null); - api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteUpdateObjectWithoutCredentials() throws NiciraNvpApiException { - api.setAdminCredentials(null, null); - api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteCreateObjectWithoutHostname() throws NiciraNvpApiException { - api.setControllerAddress(null); - api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteCreateObjectWithoutCredentials() throws NiciraNvpApiException { - api.setAdminCredentials(null, null); - api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteDeleteObjectWithoutHostname() throws NiciraNvpApiException { - api.setControllerAddress(null); - api.executeDeleteObject("/"); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteDeleteObjectWithoutCredentials() throws NiciraNvpApiException { - api.setAdminCredentials(null, null); - api.executeDeleteObject("/"); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteRetrieveObjectWithoutHostname() throws NiciraNvpApiException { - api.setControllerAddress(null); - api.executeRetrieveObject(String.class, "/", Collections. emptyMap()); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteRetrieveObjectWithoutCredentials() throws NiciraNvpApiException { - api.setAdminCredentials(null, null); - api.executeDeleteObject("/"); - } - - @Test - public void executeMethodTest() throws NiciraNvpApiException { - final GetMethod gm = mock(GetMethod.class); - - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); - api.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() - */ - @Test(expected = NiciraNvpApiException.class) - public void executeMethodTestWithLogin() throws NiciraNvpApiException, 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); - api.executeMethod(gm); - verify(gm, times(1)).getStatusCode(); - } - - @Test - public void testExecuteCreateObject() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - method = mock(PostMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); - when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); - ls = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - assertTrue(UUID.equals(ls.getUuid())); - verify(method, times(1)).releaseConnection(); - - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteCreateObjectFailure() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - 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 = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteCreateObjectException() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); - 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 = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test - public void testExecuteUpdateObject() throws NiciraNvpApiException, IOException { - final LogicalSwitch ls = new LogicalSwitch(); - method = mock(PutMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - api.executeUpdateObject(ls, "/", Collections. emptyMap()); - verify(method, times(1)).releaseConnection(); - verify(client, times(1)).executeMethod(method); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteUpdateObjectFailure() throws NiciraNvpApiException, IOException { - final LogicalSwitch ls = new LogicalSwitch(); - 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 { - api.executeUpdateObject(ls, "/", Collections. emptyMap()); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteUpdateObjectException() throws NiciraNvpApiException, IOException { - final LogicalSwitch ls = new LogicalSwitch(); - method = mock(PutMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException()); - try { - api.executeUpdateObject(ls, "/", Collections. emptyMap()); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test - public void testExecuteDeleteObject() throws NiciraNvpApiException, IOException { - method = mock(DeleteMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - api.executeDeleteObject("/"); - verify(method, times(1)).releaseConnection(); - verify(client, times(1)).executeMethod(method); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteDeleteObjectFailure() throws NiciraNvpApiException, 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 { - api.executeDeleteObject("/"); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteDeleteObjectException() throws NiciraNvpApiException, IOException { - method = mock(DeleteMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); - try { - api.executeDeleteObject("/"); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test - public void testExecuteRetrieveObject() throws NiciraNvpApiException, IOException { - method = mock(GetMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); - api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); - verify(method, times(1)).releaseConnection(); - verify(client, times(1)).executeMethod(method); - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteRetrieveObjectFailure() throws NiciraNvpApiException, 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 { - api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test(expected = NiciraNvpApiException.class) - public void testExecuteRetrieveObjectException() throws NiciraNvpApiException, 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 { - api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); - } finally { - verify(method, times(1)).releaseConnection(); - } - } - - @Test - public void testFindSecurityProfile() throws NiciraNvpApiException, IOException { + @Test(expected = JsonParseException.class) + public void testRoutingConfigAdapterNoType() 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","*")}; + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); // Execute - final NiciraNvpList actualProfiles = api.findSecurityProfile(); + gson.fromJson("{}", RoutingConfig.class); - // 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); + // Assert: JsonParseException should be thrown } - @Test - public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException { + @Test(expected = JsonParseException.class) + public void testRoutingConfigAdapterWrongType() 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 NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); // Execute - final NiciraNvpList actualProfiles = api.findSecurityProfile(UUID); + gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class); - // 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 HTTP method for SecurityProfile creation REST service", - NiciraNvpApi.GET_METHOD_TYPE, type); + // Assert: JsonParseException should be thrown } - @Test - public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException { + @Test() + public void testRoutingConfigAdapter() 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); + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); // Execute - final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile); + final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig = + (SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class); - // 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); + // Assert: JsonParseException should be thrown + assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass()); } - @Test - public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException { + @Test(expected = JsonParseException.class) + public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException { // Prepare - final SecurityProfile inputSecProfile = new SecurityProfile(); - method = mock(PutMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); // Execute - api.updateSecurityProfile(inputSecProfile, UUID); + gson.fromJson("{}", NatRule.class); - // 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); + // Assert: JsonParseException should be thrown } - @Test - public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException { + @Test(expected = JsonParseException.class) + public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException { // Prepare - method = mock(DeleteMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + final NiciraNvpApi api = new NiciraNvpApi(); + final Gson gson = api.restConnector.getGson(); // Execute - api.deleteSecurityProfile(UUID); + gson.fromJson("{type : \"WrongType\"}", NatRule.class); - // 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); + // 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()); + } + } 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 index 58dcedc6a89..7a31264f360 100644 --- 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 @@ -26,21 +26,21 @@ import org.junit.Test; public class NiciraTagTest { @Test public void testCreateTag() { - NiciraNvpTag tag = new NiciraNvpTag("scope", "tag"); + 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() { - NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); + 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() { - NiciraNvpTag tag = new NiciraNvpTag(); + final NiciraNvpTag tag = new NiciraNvpTag(); tag.setScope("scope"); tag.setTag("tag"); assertEquals("scope part set", "scope", tag.getScope()); @@ -49,7 +49,7 @@ public class NiciraTagTest { @Test public void testSetLongTag() { - NiciraNvpTag tag = new NiciraNvpTag(); + final NiciraNvpTag tag = new NiciraNvpTag(); tag.setScope("scope"); tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); assertEquals("scope part set", "scope", tag.getScope()); 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 index 2717c3125d8..23fe82a392e 100644 --- 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 @@ -76,7 +76,7 @@ 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.LogicalRouterConfig; +import com.cloud.network.nicira.LogicalRouter; import com.cloud.network.nicira.LogicalRouterPort; import com.cloud.network.nicira.LogicalSwitch; import com.cloud.network.nicira.LogicalSwitchPort; @@ -132,7 +132,7 @@ public class NiciraNvpResourceTest { public void testInitialization() throws ConfigurationException { resource.configure("NiciraNvpResource", parameters); - StartupCommand[] sc = resource.initialize(); + 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())); @@ -143,11 +143,11 @@ public class NiciraNvpResourceTest { public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - ControlClusterStatus ccs = mock(ControlClusterStatus.class); + final ControlClusterStatus ccs = mock(ControlClusterStatus.class); when(ccs.getClusterStatus()).thenReturn("stable"); when(nvpApi.getControlClusterStatus()).thenReturn(ccs); - PingCommand ping = resource.getCurrentStatus(42); + final PingCommand ping = resource.getCurrentStatus(42); assertTrue(ping != null); assertTrue(ping.getHostId() == 42); assertTrue(ping.getHostType() == Host.Type.L2Networking); @@ -157,11 +157,11 @@ public class NiciraNvpResourceTest { public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - ControlClusterStatus ccs = mock(ControlClusterStatus.class); + final ControlClusterStatus ccs = mock(ControlClusterStatus.class); when(ccs.getClusterStatus()).thenReturn("unstable"); when(nvpApi.getControlClusterStatus()).thenReturn(ccs); - PingCommand ping = resource.getCurrentStatus(42); + final PingCommand ping = resource.getCurrentStatus(42); assertTrue(ping == null); } @@ -169,11 +169,11 @@ public class NiciraNvpResourceTest { public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - ControlClusterStatus ccs = mock(ControlClusterStatus.class); + final ControlClusterStatus ccs = mock(ControlClusterStatus.class); when(ccs.getClusterStatus()).thenReturn("unstable"); when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException()); - PingCommand ping = resource.getCurrentStatus(42); + final PingCommand ping = resource.getCurrentStatus(42); assertTrue(ping == null); } @@ -181,12 +181,12 @@ public class NiciraNvpResourceTest { public void testRetries() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalSwitch ls = mock(LogicalSwitch.class); + 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); - CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); - 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()); } @@ -194,12 +194,12 @@ public class NiciraNvpResourceTest { public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalSwitch ls = mock(LogicalSwitch.class); + final LogicalSwitch ls = mock(LogicalSwitch.class); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls); - CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); - 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())); } @@ -208,12 +208,12 @@ public class NiciraNvpResourceTest { public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalSwitch ls = mock(LogicalSwitch.class); + final LogicalSwitch ls = mock(LogicalSwitch.class); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); - 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()); } @@ -221,8 +221,8 @@ public class NiciraNvpResourceTest { public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); + final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); + final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); assertTrue(dlsa.getResult()); } @@ -232,8 +232,8 @@ public class NiciraNvpResourceTest { doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any()); - DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); + final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); + final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); assertFalse(dlsa.getResult()); } @@ -241,12 +241,12 @@ public class NiciraNvpResourceTest { public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); when(lsp.getUuid()).thenReturn("eeee"); when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp); - CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); + final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); assertTrue(clspa.getResult()); assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); @@ -256,12 +256,12 @@ public class NiciraNvpResourceTest { public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); when(lsp.getUuid()).thenReturn("eeee"); when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); + final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); assertFalse(clspa.getResult()); } @@ -269,13 +269,13 @@ public class NiciraNvpResourceTest { public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + 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).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); + doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); - CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); + 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()); } @@ -285,7 +285,7 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", parameters); doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any()); - DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb")); + final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb")); assertFalse(dlspa.getResult()); } @@ -293,8 +293,8 @@ public class NiciraNvpResourceTest { public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); - UpdateLogicalSwitchPortAnswer dlspa = + 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()); } @@ -304,11 +304,12 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", parameters); @SuppressWarnings("unchecked") + final NiciraNvpList lspl = mock(NiciraNvpList.class); when(lspl.getResultCount()).thenReturn(1); when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); assertTrue(flspa.getResult()); } @@ -317,11 +318,12 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", parameters); @SuppressWarnings("unchecked") + final NiciraNvpList lspl = mock(NiciraNvpList.class); when(lspl.getResultCount()).thenReturn(0); when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); assertFalse(flspa.getResult()); } @@ -331,7 +333,7 @@ public class NiciraNvpResourceTest { when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); - FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); assertFalse(flspa.getResult()); } @@ -339,17 +341,17 @@ public class NiciraNvpResourceTest { public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); - LogicalRouterPort lrp = mock(LogicalRouterPort.class); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + 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((LogicalRouterConfig)any())).thenReturn(lrc); + 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); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + 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())); @@ -360,9 +362,9 @@ public class NiciraNvpResourceTest { public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + 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()); } @@ -371,12 +373,12 @@ public class NiciraNvpResourceTest { public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + final LogicalRouter lrc = mock(LogicalRouter.class); when(lrc.getUuid()).thenReturn("ccccc"); - when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc); when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException()); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + 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")); @@ -386,18 +388,18 @@ public class NiciraNvpResourceTest { public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); - LogicalRouterPort lrp = mock(LogicalRouterPort.class); - LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + 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((LogicalRouterConfig)any())).thenReturn(lrc); + 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()); - CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + 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")); @@ -409,7 +411,7 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", parameters); doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa")); - DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); + final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); assertFalse(dlspa.getResult()); } @@ -417,16 +419,17 @@ public class NiciraNvpResourceTest { public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); + final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); @SuppressWarnings("unchecked") + final NiciraNvpList list = mock(NiciraNvpList.class); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); - doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalRouterPort((String)any(), (LogicalRouterPort)any()); + doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any()); when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list); - ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd); assertFalse(answer.getResult()); } @@ -440,31 +443,32 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); // Mock the api create calls - NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + 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]); - 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() { @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule)argument; + 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; } @@ -485,33 +489,34 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + 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 storedRules = mock(NiciraNvpList.class); when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - 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() { @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule)argument; + 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; } @@ -532,15 +537,15 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + 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); @@ -549,18 +554,19 @@ public class NiciraNvpResourceTest { // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - 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() { @Override - public boolean matches(Object argument) { - UUID uuid = (UUID)argument; + public boolean matches(final Object argument) { + final UUID uuid = (UUID)argument; if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { return true; } @@ -578,26 +584,27 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + 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 storedRules = mock(NiciraNvpList.class); when(storedRules.getResultCount()).thenReturn(0); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - 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())); @@ -612,31 +619,32 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); // Mock the api create calls - 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]); - 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() { @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule)argument; + 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; } @@ -657,33 +665,34 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - 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]); // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - 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() { @Override - public boolean matches(Object argument) { - NatRule rule = (NatRule)argument; + 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; } @@ -704,15 +713,15 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - 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); @@ -721,18 +730,19 @@ public class NiciraNvpResourceTest { // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - 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() { @Override - public boolean matches(Object argument) { - UUID uuid = (UUID)argument; + public boolean matches(final Object argument) { + final UUID uuid = (UUID)argument; if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { return true; } @@ -750,26 +760,27 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - 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()); // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(storedRules.getResultCount()).thenReturn(0); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - 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())); @@ -784,25 +795,26 @@ public class NiciraNvpResourceTest { */ // Mock the command - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false); - List rules = new ArrayList(); + 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 rules = new ArrayList(); rules.add(rule); when(cmd.getRules()).thenReturn(rules); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api find call @SuppressWarnings("unchecked") + final NiciraNvpList storedRules = mock(NiciraNvpList.class); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); // Mock the api create calls - 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]); - 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()); @@ -811,16 +823,16 @@ public class NiciraNvpResourceTest { @Test public void testGenerateStaticNatRulePair() { - NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + 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())); - 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")); - 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")); @@ -828,18 +840,18 @@ public class NiciraNvpResourceTest { @Test public void testGeneratePortForwardingRulePair() { - 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())); - 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); - 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")); diff --git a/pom.xml b/pom.xml index cf6e96025be..d9bd2de331c 100644 --- a/pom.xml +++ b/pom.xml @@ -36,6 +36,7 @@ 1.7 UTF-8 + UTF-8 1.2.16 1.1 @@ -499,6 +500,11 @@ + + org.apache.maven.plugins + maven-site-plugin + 3.3 + org.apache.maven.plugins maven-checkstyle-plugin diff --git a/utils/pom.xml b/utils/pom.xml index f63d7c40e9d..f3b8f5fbabc 100755 --- a/utils/pom.xml +++ b/utils/pom.xml @@ -141,6 +141,10 @@ commons-net 3.3 + + com.google.code.gson + gson + @@ -173,4 +177,27 @@ + + + + integration + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + + + diff --git a/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java new file mode 100644 index 00000000000..e522852ba5e --- /dev/null +++ b/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java @@ -0,0 +1,47 @@ +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; + } + +} diff --git a/utils/src/com/cloud/utils/rest/CloudstackRESTException.java b/utils/src/com/cloud/utils/rest/CloudstackRESTException.java new file mode 100644 index 00000000000..8d745985a21 --- /dev/null +++ b/utils/src/com/cloud/utils/rest/CloudstackRESTException.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.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); + } + +} diff --git a/utils/src/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/com/cloud/utils/rest/RESTServiceConnector.java new file mode 100644 index 00000000000..7cc2e896270 --- /dev/null +++ b/utils/src/com/cloud/utils/rest/RESTServiceConnector.java @@ -0,0 +1,377 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.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.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +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 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 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> classList, final List> 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 void executeUpdateObject(final T newObject, final String uri, final Map 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 executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map 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 executeRetrieveObject(final Type returnObjectType, final String uri, final Map 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 nameValuePairs = new ArrayList(parameters.size()); + for (final Entry 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 = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + ssf = sc.getSocketFactory(); + } 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 { + return ssf.createSocket(host, port); + } + + @Override + public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException { + return ssf.createSocket(address, port, localAddress, localPort); + } + + @Override + public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { + return ssf.createSocket(socket, host, port, autoClose); + } + + @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) { + return createSocket(host, port, localAddress, localPort); + } else { + final Socket s = ssf.createSocket(); + s.bind(new InetSocketAddress(localAddress, localPort)); + s.connect(new InetSocketAddress(host, port), timeout); + return s; + } + } + } + +} diff --git a/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java new file mode 100644 index 00000000000..cb25614ddec --- /dev/null +++ b/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java @@ -0,0 +1,146 @@ +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 _authcookie variable. + *

+ * 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 + } + +} diff --git a/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java new file mode 100644 index 00000000000..d406f94c123 --- /dev/null +++ b/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java @@ -0,0 +1,373 @@ +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 java.util.List; + +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 UUID2 = "bbbb"; + 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 DISPLAY_NAME = "myTestName"; + protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; + 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}"; + + 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. emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteUpdateObjectWithoutCredentials() throws CloudstackRESTException { + method = mock(PutMethod.class); + connector.setAdminCredentials(null, null); + connector.executeUpdateObject(new String(), "/", Collections. emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteCreateObjectWithoutHostname() throws CloudstackRESTException { + method = mock(PostMethod.class); + connector.setControllerAddress(null); + connector.executeCreateObject(new String(), String.class, "/", Collections. 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. 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. emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteRetrieveObjectWithoutCredentials() throws CloudstackRESTException { + method = mock(GetMethod.class); + connector.setAdminCredentials(null, null); + connector.executeRetrieveObject(String.class, "/", Collections. 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(); + } + + /* Bit of a roundabout way to ensure that login is called after an un authorized result + * It not possible to properly mock login() + */ + @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(); + } + + @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. 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. 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. 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. 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. 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. 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. 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. 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. 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