diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml index 352155deb1a..e74a5ae85e1 100644 --- a/plugins/network-elements/nicira-nvp/pom.xml +++ b/plugins/network-elements/nicira-nvp/pom.xml @@ -18,7 +18,8 @@ under the License. --> - + 4.0.0 cloud-plugin-network-nvp Apache CloudStack Plugin - Network Nicira NVP @@ -29,10 +30,29 @@ ../../pom.xml + + + org.apache.cloudstack + cloud-utils + 4.6.0-SNAPSHOT + test-jar + test + + + + src/main/java + src/test/java + target/classes + target/test-classes + + + src/main/resources + + - test/resources + src/test/resources true diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java deleted file mode 100644 index 810453cfbf7..00000000000 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java +++ /dev/null @@ -1,658 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.network.nicira; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.reflect.TypeToken; - -import com.cloud.utils.rest.CloudstackRESTException; -import com.cloud.utils.rest.RESTServiceConnector; -import com.cloud.utils.rest.RESTValidationStrategy; - -@SuppressWarnings("rawtypes") -public class NiciraNvpApi { - protected static final String GET_METHOD_TYPE = "get"; - protected static final String DELETE_METHOD_TYPE = "delete"; - protected static final String PUT_METHOD_TYPE = "put"; - protected static final String POST_METHOD_TYPE = "post"; - - protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile"; - protected static final String ACL_URI_PREFIX = "/ws.v1/acl"; - private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch"; - private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter"; - private static final String LOGIN_URL = "/ws.v1/login"; - - protected RESTServiceConnector restConnector; - - protected final static Map prefixMap; - - protected final static Map listTypeMap; - - protected final static Map defaultListParams; - - static { - 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", "*"); - } - - public NiciraNvpApi() { - 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()); - - restConnector = new RESTServiceConnector(new RESTValidationStrategy(LOGIN_URL), classList, deserializerList); - } - - public NiciraNvpApi(final String address, final String username, final String password) { - this(); - restConnector.setControllerAddress(address); - restConnector.setAdminCredentials(username, password); - } - - public void setControllerAddress(final String address) { - restConnector.setControllerAddress(address); - } - - public void setAdminCredentials(final String username, final String password) { - restConnector.setAdminCredentials(username, password); - } - - /** - * POST - * - * @param entity - * @return - * @throws NiciraNvpApiException - */ - protected T 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 { - createdEntity = restConnector.executeCreateObject(entity, new TypeToken() { - }.getType(), uri, Collections. emptyMap()); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e); - } - - 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 { - entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e); - } - - if (entities == null) { - throw new NiciraNvpApiException("Unexpected response from API"); - } - - return entities; - } - - /** - * PUT item given a UUID as key and an item object - * with the new data - * - * @param item - * @param uuid - * @throws NiciraNvpApiException - */ - public 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); - } - } - - /** - * POST {@link SecurityProfile} - * - * @param securityProfile - * @return - * @throws NiciraNvpApiException - */ - public SecurityProfile createSecurityProfile(final SecurityProfile securityProfile) throws NiciraNvpApiException { - return create(securityProfile); - } - - /** - * GET list of {@link SecurityProfile} - * - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList findSecurityProfile() throws NiciraNvpApiException { - return findSecurityProfile(null); - } - - /** - * GET list of {@link SecurityProfile} filtered by UUID - * - * We could have invoked the service: - * SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid - * but it is not working currently - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList findSecurityProfile(final String uuid) throws NiciraNvpApiException { - return find(uuid, SecurityProfile.class); - } - - /** - * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile} - * with the new data - * - * @param securityProfile - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - public void updateSecurityProfile(final SecurityProfile securityProfile, - final String securityProfileUuid) - throws NiciraNvpApiException { - update(securityProfile, securityProfileUuid); - } - - /** - * DELETE Security Profile given a UUID as key - * - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - public void deleteSecurityProfile(final String securityProfileUuid) - throws NiciraNvpApiException { - delete(securityProfileUuid, SecurityProfile.class); - } - - - /** - * POST {@link Acl} - * - * @param acl - * @return - * @throws NiciraNvpApiException - */ - public Acl createAcl(final Acl acl) throws NiciraNvpApiException { - return create(acl); - } - - /** - * GET list of {@link Acl} - * - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList findAcl() throws NiciraNvpApiException { - return findAcl(null); - } - - /** - * GET list of {@link Acl} filtered by UUID - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList findAcl(final String uuid) throws NiciraNvpApiException { - return find(uuid, Acl.class); - } - - /** - * PUT {@link Acl} given a UUID as key and a {@link Acl} - * with the new data - * - * @param acl - * @param aclUuid - * @throws NiciraNvpApiException - */ - public void updateAcl(final Acl acl, - final String aclUuid) - throws NiciraNvpApiException { - update(acl, aclUuid); - } - - /** - * DELETE Acl given a UUID as key - * - * @param acl - * @throws NiciraNvpApiException - */ - public void deleteAcl(final String aclUuid) throws NiciraNvpApiException { - delete(aclUuid, Acl.class); - } - - public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException { - return create(logicalSwitch); - } - - /** - * GET list of {@link LogicalSwitch} - * - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList findLogicalSwitch() throws NiciraNvpApiException { - return findLogicalSwitch(null); - } - - /** - * GET list of {@link LogicalSwitch} filtered by UUID - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList findLogicalSwitch(final String uuid) throws NiciraNvpApiException { - return find(uuid, LogicalSwitch.class); - } - - /** - * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch} - * with the new data - * - * @param logicalSwitch - * @param logicalSwitchUuid - * @throws NiciraNvpApiException - */ - public void updateLogicalSwitch(final LogicalSwitch logicalSwitch, - final String logicalSwitchUuid) - throws NiciraNvpApiException { - update(logicalSwitch, logicalSwitchUuid); - } - - public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException { - delete(uuid, LogicalSwitch.class); - } - - public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; - return createWithUri(logicalSwitchPort, uri); - } - - public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPort.getUuid(); - updateWithUri(logicalSwitchPort, uri); - } - - public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, - final Attachment attachment) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment"; - updateWithUri(attachment, uri); - } - - public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid; - deleteWithUri(uri); - } - - public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; - final Map params = new HashMap(); - params.put("attachment_vif_uuid", vifAttachmentUuid); - params.put("fields", "uuid"); - - 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"); - } - - final LogicalSwitchPort lsp = lspl.getResults().get(0); - return lsp.getUuid(); - } - - public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { - final String uri = "/ws.v1/control-cluster/status"; - ControlClusterStatus ccs; - try { - ccs = restConnector.executeRetrieveObject(new TypeToken() { - }.getType(), uri, null); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e); - } - - return ccs; - } - - public NiciraNvpList findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { - final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; - final Map params = new HashMap(); - params.put("uuid", logicalSwitchPortUuid); - params.put("fields", "uuid"); - - 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"); - } - - return lspl; - } - - 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"); - - NiciraNvpList lrpl; - try { - lrpl = restConnector.executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e); - } - - if (lrpl == null) { - throw new NiciraNvpApiException("Unexpected response from API"); - } - - return lrpl; - } - - public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException { - return create(logicalRouter); - } - - /** - * GET list of {@link LogicalRouter} - * - * @return - * @throws NiciraNvpApiException - */ - public NiciraNvpList 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; - deleteWithUri(uri); - } - - public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; - return createWithUri(logicalRouterPort, uri); - } - - public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; - deleteWithUri(uri); - } - - public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); - updateWithUri(logicalRouterPort, uri); - } - - public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) - throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; - updateWithUri(attachment, uri); - } - - public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat"; - return createWithUri(natRule, uri); - } - - public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); - updateWithUri(natRule, uri); - } - - public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); - deleteWithUri(uri); - } - - public NiciraNvpList findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, - final long vlanId) throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; - final Map params = new HashMap(); - params.put("attachment_gwsvc_uuid", gatewayServiceUuid); - params.put("attachment_vlan", "0"); - params.put("fields", "*"); - - 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 { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat"; - final Map params = new HashMap(); - params.put("fields", "*"); - - 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) - throws NiciraNvpApiException { - final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; - final Map params = new HashMap(); - params.put("fields", "*"); - params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); - - try { - return restConnector.executeRetrieveObject(new TypeToken>() { - }.getType(), uri, params); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e); - } - } - - public static class NatRuleAdapter implements JsonDeserializer { - - @Override - public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { - final JsonObject jsonObject = jsonElement.getAsJsonObject(); - - if (!jsonObject.has("type")) { - throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object"); - } - - final String natRuleType = jsonObject.get("type").getAsString(); - if ("SourceNatRule".equals(natRuleType)) { - return context.deserialize(jsonElement, SourceNatRule.class); - } else if ("DestinationNatRule".equals(natRuleType)) { - return context.deserialize(jsonElement, DestinationNatRule.class); - } - - throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\""); - } - } - - public static class RoutingConfigAdapter implements JsonDeserializer { - - private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig"; - private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig"; - - @Override - public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { - final JsonObject jsonObject = jsonElement.getAsJsonObject(); - - if (!jsonObject.has("type")) { - throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object"); - } - - final String routingConfigType = jsonObject.get("type").getAsString(); - if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) { - return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class); - } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) { - return context.deserialize(jsonElement, RoutingTableRoutingConfig.class); - } - - throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\""); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/FindLogicalSwitchPortCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/StartupNiciraNvpCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/StartupNiciraNvpCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDao.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpDaoImpl.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDao.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java similarity index 74% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java index 640d8a50715..975ebd19aa0 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java @@ -98,14 +98,14 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { public NiciraNvpGuestNetworkGuru() { super(); - _isolationMethods = new IsolationMethod[] {IsolationMethod.STT, IsolationMethod.VXLAN}; + _isolationMethods = new IsolationMethod[] { IsolationMethod.STT, IsolationMethod.VXLAN }; } @Override protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) { // This guru handles only Guest Isolated network that supports Source nat service - if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated && - isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) { + if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated + && isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) { return true; } else { s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced); @@ -116,14 +116,14 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { @Override public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final Account owner) { // Check of the isolation type of the related physical network is supported - PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId()); - DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + final PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId()); + final DataCenter dc = _dcDao.findById(plan.getDataCenterId()); if (!canHandle(offering, dc.getNetworkType(), physnet)) { s_logger.debug("Refusing to design this network"); return null; } - List devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId()); + final List devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId()); if (devices.isEmpty()) { s_logger.error("No NiciraNvp Controller on physical network " + physnet.getName()); return null; @@ -131,11 +131,10 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId()); s_logger.debug("Physical isolation type is supported, asking GuestNetworkGuru to design this network"); - NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner); + final NetworkVO networkObject = (NetworkVO) super.design(offering, plan, userSpecified, owner); if (networkObject == null) { return null; } - // Override the broadcast domain type networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch); return networkObject; @@ -143,12 +142,11 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { @Override public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context) - throws InsufficientVirtualNetworkCapacityException { - assert (network.getState() == State.Implementing) : "Why are we implementing " + network; + throws InsufficientVirtualNetworkCapacityException { + assert network.getState() == State.Implementing : "Why are we implementing " + network; - long dcId = dest.getDataCenter().getId(); + final long dcId = dest.getDataCenter().getId(); - //get physical network id Long physicalNetworkId = network.getPhysicalNetworkId(); // physical network id can be null in Guest Network in Basic zone, so locate the physical network @@ -156,9 +154,8 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { physicalNetworkId = networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType()); } - NetworkVO implemented = - new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated, - network.getDataCenterId(), physicalNetworkId, offering.getRedundantRouter()); + final NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), + State.Allocated, network.getDataCenterId(), physicalNetworkId, offering.getRedundantRouter()); if (network.getGateway() != null) { implemented.setGateway(network.getGateway()); @@ -171,26 +168,26 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { // Name is either the given name or the uuid String name = network.getName(); if (name == null || name.isEmpty()) { - name = ((NetworkVO)network).getUuid(); + name = ((NetworkVO) network).getUuid(); } if (name.length() > MAX_NAME_LENGTH) { - name = name.substring(0, MAX_NAME_LENGTH - 1); // max length 40 + name = name.substring(0, MAX_NAME_LENGTH - 1); } - List devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId); + final List devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId); if (devices.isEmpty()) { s_logger.error("No NiciraNvp Controller on physical network " + physicalNetworkId); return null; } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); + final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); hostDao.loadDetails(niciraNvpHost); - String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid"); - String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype"); + final String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid"); + final String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype"); - CreateLogicalSwitchCommand cmd = - new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-" + context.getAccount().getAccountName()); - CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); + final CreateLogicalSwitchCommand cmd = new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-" + + context.getAccount().getAccountName()); + final CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd); if (answer == null || !answer.getResult()) { s_logger.error("CreateLogicalSwitchCommand failed"); @@ -201,7 +198,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { implemented.setBroadcastUri(new URI("lswitch", answer.getLogicalSwitchUuid(), null)); implemented.setBroadcastDomainType(BroadcastDomainType.Lswitch); s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString()); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { s_logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e); return null; } @@ -211,35 +208,33 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { @Override public void reserve(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { - // TODO Auto-generated method stub + throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { super.reserve(nic, network, vm, dest, context); } @Override public boolean release(final NicProfile nic, final VirtualMachineProfile vm, final String reservationId) { - // TODO Auto-generated method stub return super.release(nic, vm, reservationId); } @Override public void shutdown(final NetworkProfile profile, final NetworkOffering offering) { - NetworkVO networkObject = networkDao.findById(profile.getId()); + final NetworkVO networkObject = networkDao.findById(profile.getId()); if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch || networkObject.getBroadcastUri() == null) { s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText()); return; } - List devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId()); + final List devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId()); if (devices.isEmpty()) { s_logger.error("No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId()); return; } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); + final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri())); - DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); + final DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri())); + final DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd); if (answer == null || !answer.getResult()) { s_logger.error("DeleteLogicalSwitchCommand failed"); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraEntity.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/BaseNiciraNamedEntity.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java new file mode 100644 index 00000000000..1314498211b --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java @@ -0,0 +1,50 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.util.concurrent.atomic.AtomicInteger; + +public class ExecutionCounter { + + private final int executionLimit; + private final AtomicInteger executionCount = new AtomicInteger(0); + + public ExecutionCounter(final int executionLimit) { + this.executionLimit = executionLimit; + } + + public ExecutionCounter resetExecutionCounter() { + executionCount.set(0); + return this; + } + + public boolean hasReachedExecutionLimit() { + return executionCount.get() >= executionLimit; + } + + public ExecutionCounter incrementExecutionCounter() { + executionCount.incrementAndGet(); + return this; + } + + public int getValue() { + return executionCount.get(); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouter.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java new file mode 100644 index 00000000000..7ea2f5b23bd --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java @@ -0,0 +1,49 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.lang.reflect.Type; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +public class NatRuleAdapter implements JsonDeserializer { + + @Override + public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { + final JsonObject jsonObject = jsonElement.getAsJsonObject(); + + if (!jsonObject.has("type")) { + throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object"); + } + + final String natRuleType = jsonObject.get("type").getAsString(); + if ("SourceNatRule".equals(natRuleType)) { + return context.deserialize(jsonElement, SourceNatRule.class); + } else if ("DestinationNatRule".equals(natRuleType)) { + return context.deserialize(jsonElement, DestinationNatRule.class); + } + + throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\""); + } +} \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java new file mode 100644 index 00000000000..31adf9d3e2d --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +public class NiciraConstants { + + public static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile"; + public static final String ACL_URI_PREFIX = "/ws.v1/acl"; + public static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch"; + public static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter"; + public static final String LOGIN_URL = "/ws.v1/login"; + public static final String CONTROL_CLUSTER_STATUS_URL = "/ws.v1/control-cluster/status"; + + public static final String ATTACHMENT_PATH_SEGMENT = "/attachment"; + public static final String NAT_PATH_SEGMENT = "/nat"; + public static final String LPORT_PATH_SEGMENT = "/lport"; + + public static final String ATTACHMENT_VIF_UUID_QUERY_PARAMETER_NAME = "attachment_vif_uuid"; + public static final String ATTACHMENT_VLAN_PARAMETER = "attachment_vlan"; + public static final String ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER = "attachment_gwsvc_uuid"; + public static final String WILDCARD_QUERY_PARAMETER = "*"; + public static final String UUID_QUERY_PARAMETER = "uuid"; + public static final String FIELDS_QUERY_PARAMETER = "fields"; + +} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java new file mode 100644 index 00000000000..093d90da1ae --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java @@ -0,0 +1,627 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.lang.reflect.Type; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; + +import com.cloud.utils.rest.CloudstackRESTException; +import com.cloud.utils.rest.RESTServiceConnector; +import com.google.common.base.Optional; +import com.google.gson.JsonDeserializer; +import com.google.gson.reflect.TypeToken; + +@SuppressWarnings("rawtypes") +public class NiciraNvpApi { + + private static final Optional ABSENT = Optional.absent(); + + private static final String SWITCH_URI_PREFIX = NiciraConstants.SWITCH_URI_PREFIX; + private static final String ROUTER_URI_PREFIX = NiciraConstants.ROUTER_URI_PREFIX; + + private static final String ATTACHMENT_PATH_SEGMENT = NiciraConstants.ATTACHMENT_PATH_SEGMENT; + private static final String NAT_PATH_SEGMENT = NiciraConstants.NAT_PATH_SEGMENT; + private static final String LPORT_PATH_SEGMENT = NiciraConstants.LPORT_PATH_SEGMENT; + + private static final String ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER = NiciraConstants.ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER; + private static final String WILDCARD_QUERY_PARAMETER = NiciraConstants.WILDCARD_QUERY_PARAMETER; + private static final String UUID_QUERY_PARAMETER = NiciraConstants.UUID_QUERY_PARAMETER; + private static final String FIELDS_QUERY_PARAMETER = NiciraConstants.FIELDS_QUERY_PARAMETER; + + private static final int DEFAULT_MAX_RETRIES = 5; + + private final RESTServiceConnector restConnector; + + protected final static Map prefixMap; + + protected final static Map listTypeMap; + + protected final static Map defaultListParams; + + static { + prefixMap = new HashMap(); + prefixMap.put(SecurityProfile.class, NiciraConstants.SEC_PROFILE_URI_PREFIX); + prefixMap.put(Acl.class, NiciraConstants.ACL_URI_PREFIX); + prefixMap.put(LogicalSwitch.class, SWITCH_URI_PREFIX); + prefixMap.put(LogicalRouter.class, ROUTER_URI_PREFIX); + + 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_QUERY_PARAMETER, WILDCARD_QUERY_PARAMETER); + } + + private NiciraNvpApi(final Builder builder) { + final Map, JsonDeserializer> classToDeserializerMap = new HashMap<>(); + classToDeserializerMap.put(NatRule.class, new NatRuleAdapter()); + classToDeserializerMap.put(RoutingConfig.class, new RoutingConfigAdapter()); + + final NiciraRestClient niciraRestClient = NiciraRestClient.create() + .client(builder.httpClient) + .clientContext(builder.httpClientContext) + .hostname(builder.host) + .username(builder.username) + .password(builder.password) + .loginUrl(NiciraConstants.LOGIN_URL) + .executionLimit(DEFAULT_MAX_RETRIES) + .build(); + restConnector = RESTServiceConnector.create() + .classToDeserializerMap(classToDeserializerMap) + .client(niciraRestClient) + .build(); + } + + public static Builder create() { + return new Builder(); + } + + /** + * POST + * + * @param entity + * @return + * @throws NiciraNvpApiException + */ + private T create(final T entity) throws NiciraNvpApiException { + final String uri = prefixMap.get(entity.getClass()); + return createWithUri(entity, uri); + } + + /** + * POST + * + * @param entity + * @return + * @throws NiciraNvpApiException + */ + private T createWithUri(final T entity, final String uri) throws NiciraNvpApiException { + T createdEntity; + try { + createdEntity = restConnector.executeCreateObject(entity, uri, Collections. emptyMap()); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + + return createdEntity; + } + + /** + * GET list of items + * + * @param uuid + * + * @return + * @throws NiciraNvpApiException + */ + private List find(final Optional uuid, final Class clazz) throws NiciraNvpApiException { + final String uri = prefixMap.get(clazz); + Map params = defaultListParams; + if (uuid.isPresent()) { + params = new HashMap(defaultListParams); + params.put(UUID_QUERY_PARAMETER, uuid.get()); + } + + NiciraNvpList entities; + try { + entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + + if (entities == null) { + throw new NiciraNvpApiException("Unexpected response from API"); + } + + return entities.getResults(); + } + + /** + * PUT item given a UUID as key and an item object with the new data + * + * @param item + * @param uuid + * @throws NiciraNvpApiException + */ + private 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 + */ + private 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 + */ + private 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 + */ + private void deleteWithUri(final String uri) throws NiciraNvpApiException { + try { + restConnector.executeDeleteObject(uri); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + /** + * POST {@link SecurityProfile} + * + * @param securityProfile + * @return + * @throws NiciraNvpApiException + */ + public SecurityProfile createSecurityProfile(final SecurityProfile securityProfile) throws NiciraNvpApiException { + return create(securityProfile); + } + + /** + * GET list of {@link SecurityProfile} + * + * @return + * @throws NiciraNvpApiException + */ + public List findSecurityProfile() throws NiciraNvpApiException { + return find(ABSENT, SecurityProfile.class); + } + + /** + * GET list of {@link SecurityProfile} filtered by UUID + * + * We could have invoked the service: SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid but it is not working currently + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public List findSecurityProfile(final String uuid) throws NiciraNvpApiException { + return find(Optional.fromNullable(uuid), SecurityProfile.class); + } + + /** + * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile} with the new data + * + * @param securityProfile + * @param securityProfileUuid + * @throws NiciraNvpApiException + */ + public void updateSecurityProfile(final SecurityProfile securityProfile, final String securityProfileUuid) throws NiciraNvpApiException { + update(securityProfile, securityProfileUuid); + } + + /** + * DELETE Security Profile given a UUID as key + * + * @param securityProfileUuid + * @throws NiciraNvpApiException + */ + public void deleteSecurityProfile(final String securityProfileUuid) throws NiciraNvpApiException { + delete(securityProfileUuid, SecurityProfile.class); + } + + /** + * POST {@link Acl} + * + * @param acl + * @return + * @throws NiciraNvpApiException + */ + public Acl createAcl(final Acl acl) throws NiciraNvpApiException { + return create(acl); + } + + /** + * GET list of {@link Acl} + * + * @return + * @throws NiciraNvpApiException + */ + public List findAcl() throws NiciraNvpApiException { + return findAcl(null); + } + + /** + * GET list of {@link Acl} filtered by UUID + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public List findAcl(final String uuid) throws NiciraNvpApiException { + return find(Optional.fromNullable(uuid), Acl.class); + } + + /** + * PUT {@link Acl} given a UUID as key and a {@link Acl} with the new data + * + * @param acl + * @param aclUuid + * @throws NiciraNvpApiException + */ + public void updateAcl(final Acl acl, final String aclUuid) throws NiciraNvpApiException { + update(acl, aclUuid); + } + + /** + * DELETE Acl given a UUID as key + * + * @param acl + * @throws NiciraNvpApiException + */ + public void deleteAcl(final String aclUuid) throws NiciraNvpApiException { + delete(aclUuid, Acl.class); + } + + public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException { + return create(logicalSwitch); + } + + /** + * GET list of {@link LogicalSwitch} + * + * @return + * @throws NiciraNvpApiException + */ + public List findLogicalSwitch() throws NiciraNvpApiException { + return findLogicalSwitch(null); + } + + /** + * GET list of {@link LogicalSwitch} filtered by UUID + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public List findLogicalSwitch(final String uuid) throws NiciraNvpApiException { + return find(Optional.fromNullable(uuid), LogicalSwitch.class); + } + + /** + * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch} with the new data + * + * @param logicalSwitch + * @param logicalSwitchUuid + * @throws NiciraNvpApiException + */ + public void updateLogicalSwitch(final LogicalSwitch logicalSwitch, final String logicalSwitchUuid) throws NiciraNvpApiException { + update(logicalSwitch, logicalSwitchUuid); + } + + public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException { + delete(uuid, LogicalSwitch.class); + } + + public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { + return createWithUri(logicalSwitchPort, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT)); + } + + public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { + updateWithUri(logicalSwitchPort, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPort.getUuid().toString())); + } + + public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException { + updateWithUri(attachment, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPortUuid) + ATTACHMENT_PATH_SEGMENT); + } + + public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { + deleteWithUri(buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPortUuid)); + } + + public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException { + final String uri = buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT); + final Map params = buildBasicParametersMap(UUID_QUERY_PARAMETER); + params.put(NiciraConstants.ATTACHMENT_VIF_UUID_QUERY_PARAMETER_NAME, vifAttachmentUuid); + + NiciraNvpList niciraList; + try { + final Type niciraListType = new TypeToken>() { + }.getType(); + niciraList = restConnector.executeRetrieveObject(niciraListType, uri, params); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + + final List lspl = niciraList.getResults(); + + final int listSize = lspl.size(); + if (listSize != 1) { + throw new NiciraNvpApiException("Expected 1 LogicalSwitchPort, but got " + listSize); + } + + final LogicalSwitchPort lsp = lspl.get(0); + return lsp.getUuid(); + } + + public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { + final String uri = NiciraConstants.CONTROL_CLUSTER_STATUS_URL; + try { + return restConnector.executeRetrieveObject(ControlClusterStatus.class, uri, new HashMap()); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + public List findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { + final String uri = buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT); + final Map params = buildBasicParametersMap(UUID_QUERY_PARAMETER); + params.put(UUID_QUERY_PARAMETER, logicalSwitchPortUuid); + + try { + final Type niciraListType = new TypeToken>() { + }.getType(); + return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + public List findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { + final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); + final Map params = buildBasicParametersMap(UUID_QUERY_PARAMETER); + params.put(UUID_QUERY_PARAMETER, logicalRouterPortUuid); + + try { + final Type niciraListType = new TypeToken>() { + }.getType(); + return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException { + return create(logicalRouter); + } + + /** + * GET list of {@link LogicalRouter} + * + * @return + * @throws NiciraNvpApiException + */ + public List findLogicalRouter() throws NiciraNvpApiException { + return findLogicalRouter(null); + } + + /** + * GET list of {@link LogicalRouter} filtered by UUID + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public List findLogicalRouter(final String uuid) throws NiciraNvpApiException { + return find(Optional.fromNullable(uuid), LogicalRouter.class); + } + + public LogicalRouter findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException { + return findLogicalRouter(logicalRouterUuid).get(0); + } + + public void updateLogicalRouter(final LogicalRouter logicalRouter, final String logicalRouterUuid) throws NiciraNvpApiException { + update(logicalRouter, logicalRouterUuid); + } + + public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException { + deleteWithUri(buildLogicalRouterUri(logicalRouterUuid)); + } + + public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { + return createWithUri(logicalRouterPort, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT)); + } + + public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { + deleteWithUri(buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPortUuid)); + } + + public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { + updateWithUri(logicalRouterPort, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPort.getUuid().toString())); + } + + public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) throws NiciraNvpApiException { + updateWithUri(attachment, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPortUuid) + ATTACHMENT_PATH_SEGMENT); + } + + public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { + return createWithUri(natRule, buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT)); + } + + public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { + updateWithUri(natRule, buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT, natRule.getUuid().toString())); + } + + public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException { + deleteWithUri(buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT, natRuleUuid.toString())); + } + + public List findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, final long vlanId) + throws NiciraNvpApiException { + final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); + final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); + params.put(ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER, gatewayServiceUuid); + params.put(NiciraConstants.ATTACHMENT_VLAN_PARAMETER, Long.toString(vlanId)); + + try { + final Type niciraListType = new TypeToken>() { + }.getType(); + return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + public List findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException { + final String uri = buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT); + final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); + + try { + final Type niciraListType = new TypeToken>() { + }.getType(); + return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + public List findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid) + throws NiciraNvpApiException { + final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); + final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); + params.put(ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER, l3GatewayServiceUuid); + + try { + final Type niciraListType = new TypeToken>() { + }.getType(); + return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); + } catch (final CloudstackRESTException e) { + throw new NiciraNvpApiException(e); + } + } + + private static Map buildBasicParametersMap(final String fieldsQueryValue) { + final Map params = new HashMap(); + params.put(FIELDS_QUERY_PARAMETER, fieldsQueryValue); + return params; + } + + private static String buildUri(final String uriPrefix, final String uuid) { + return uriPrefix + "/" + uuid; + } + + private static String buildLogicalSwitchUri(final String logicalSwitchUuid) { + return buildUri(SWITCH_URI_PREFIX, logicalSwitchUuid); + } + + private static String buildLogicalSwitchElementUri(final String logicalSwitchUuid, final String logicalElementType) { + return buildLogicalSwitchUri(logicalSwitchUuid) + logicalElementType; + } + + private static String buildLogicalSwitchElementUri(final String logicalSwitchUuid, final String logicalElementType, final String elementUuid) { + return buildLogicalSwitchElementUri(logicalSwitchUuid, logicalElementType) + "/" + elementUuid.toString(); + } + + private static String buildLogicalRouterUri(final String logicalRouterUuid) { + return buildUri(ROUTER_URI_PREFIX, logicalRouterUuid); + } + + private static String buildLogicalRouterElementUri(final String logicalRouterUuid, final String logicalElementType) { + return buildLogicalRouterUri(logicalRouterUuid) + logicalElementType; + } + + private static String buildLogicalRouterElementUri(final String logicalRouterUuid, final String logicalRouterElementType, final String elementUuid) { + return buildLogicalRouterElementUri(logicalRouterUuid, logicalRouterElementType) + "/" + elementUuid.toString(); + } + + public static class Builder { + private String host; + private String username; + private String password; + private CloseableHttpClient httpClient; + private HttpClientContext httpClientContext = HttpClientContext.create(); + + public Builder host(final String host) { + this.host = host; + return this; + } + + public Builder username(final String username) { + this.username = username; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder httpClient(final CloseableHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public Builder httpClientContext(final HttpClientContext httpClientContext) { + this.httpClientContext = httpClientContext; + return this; + } + + public NiciraNvpApi build() { + return new NiciraNvpApi(this); + } + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java new file mode 100644 index 00000000000..6ade3a53777 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java @@ -0,0 +1,202 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; + +import com.cloud.utils.rest.BasicRestClient; +import com.cloud.utils.rest.CloudstackRESTException; +import com.cloud.utils.rest.HttpConstants; +import com.cloud.utils.rest.HttpMethods; +import com.cloud.utils.rest.HttpStatusCodeHelper; +import com.cloud.utils.rest.HttpUriRequestBuilder; + +public class NiciraRestClient extends BasicRestClient { + + private static final Logger s_logger = Logger.getLogger(NiciraRestClient.class); + + private static final String CONTENT_TYPE = HttpConstants.CONTENT_TYPE; + private static final String TEXT_HTML_CONTENT_TYPE = HttpConstants.TEXT_HTML_CONTENT_TYPE; + + private static final int DEFAULT_BODY_RESP_MAX_LEN = 1024; + private static final int DEFAULT_EXECUTION_LIMIT = 5; + + private final ExecutionCounter counter; + private final int maxResponseErrorMesageLength; + private final int executionLimit; + + private final String username; + private final String password; + private final String loginUrl; + + private NiciraRestClient(final Builder builder) { + super(builder.client, builder.clientContext, builder.hostname); + executionLimit = builder.executionLimit; + counter = new ExecutionCounter(executionLimit); + maxResponseErrorMesageLength = builder.maxResponseErrorMesageLength; + username = builder.username; + password = builder.password; + loginUrl = builder.loginUrl; + } + + public static Builder create() { + return new Builder(); + } + + @Override + public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException { + return execute(request, 0); + } + + private CloseableHttpResponse execute(final HttpUriRequest request, final int previousStatusCode) throws CloudstackRESTException { + if (counter.hasReachedExecutionLimit()) { + throw new CloudstackRESTException("Reached max executions limit of " + executionLimit); + } + counter.incrementExecutionCounter(); + s_logger.debug("Executing " + request.getMethod() + " request [execution count = " + counter.getValue() + "]"); + final CloseableHttpResponse response = super.execute(request); + + final StatusLine statusLine = response.getStatusLine(); + final int statusCode = statusLine.getStatusCode(); + s_logger.debug("Status of last request: " + statusLine.toString()); + if (HttpStatusCodeHelper.isUnauthorized(statusCode)) { + return handleUnauthorizedResponse(request, previousStatusCode, response, statusCode); + } else if (HttpStatusCodeHelper.isSuccess(statusCode)) { + return handleSuccessResponse(response); + } else { + throw new CloudstackRESTException("Unexpecetd status code: " + statusCode); + } + } + + private CloseableHttpResponse handleUnauthorizedResponse(final HttpUriRequest request, final int previousStatusCode, final CloseableHttpResponse response, final int statusCode) + throws CloudstackRESTException { + super.closeResponse(response); + if (HttpStatusCodeHelper.isUnauthorized(previousStatusCode)) { + s_logger.error(responseToErrorMessage(response)); + throw new CloudstackRESTException("Two consecutive failed attempts to authenticate against REST server"); + } + final HttpUriRequest authenticateRequest = createAuthenticationRequest(); + final CloseableHttpResponse loginResponse = execute(authenticateRequest, statusCode); + final int loginStatusCode = loginResponse.getStatusLine().getStatusCode(); + super.closeResponse(loginResponse); + return execute(request, loginStatusCode); + } + + private CloseableHttpResponse handleSuccessResponse(final CloseableHttpResponse response) { + counter.resetExecutionCounter(); + return response; + } + + private HttpUriRequest createAuthenticationRequest() { + final Map parameters = new HashMap<>(); + parameters.put("username", username); + parameters.put("password", password); + return HttpUriRequestBuilder.create() + .method(HttpMethods.POST) + .methodParameters(parameters) + .path(loginUrl) + .build(); + } + + private String responseToErrorMessage(final CloseableHttpResponse response) { + String errorMessage = response.getStatusLine().toString(); + if (response.containsHeader(CONTENT_TYPE) && TEXT_HTML_CONTENT_TYPE.equals(response.getFirstHeader(CONTENT_TYPE).getValue())) { + try { + final HttpEntity entity = response.getEntity(); + final String respobnseBody = EntityUtils.toString(entity); + errorMessage = respobnseBody.subSequence(0, maxResponseErrorMesageLength).toString(); + } catch (final IOException e) { + s_logger.debug("Could not read repsonse body. Response: " + response, e); + } + } + + return errorMessage; + } + + protected static class Builder extends BasicRestClient.Builder { + private CloseableHttpClient client; + private HttpClientContext clientContext; + private String hostname; + private String username; + private String password; + private String loginUrl; + private int executionLimit = DEFAULT_EXECUTION_LIMIT; + private int maxResponseErrorMesageLength = DEFAULT_BODY_RESP_MAX_LEN; + + public Builder hostname(final String hostname) { + this.hostname = hostname; + return this; + } + + public Builder username(final String username) { + this.username = username; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder loginUrl(final String loginUrl) { + this.loginUrl = loginUrl; + return this; + } + + @Override + public Builder client(final CloseableHttpClient client) { + this.client = client; + return this; + } + + @Override + public Builder clientContext(final HttpClientContext clientContext) { + this.clientContext = clientContext; + return this; + } + + public Builder executionLimit(final int executionLimit) { + this.executionLimit = executionLimit; + return this; + } + + public Builder maxResponseErrorMesageLength(final int maxResponseErrorMesageLength) { + this.maxResponseErrorMesageLength = maxResponseErrorMesageLength; + return this; + } + + @Override + public NiciraRestClient build() { + return new NiciraRestClient(this); + } + + } +} \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java new file mode 100644 index 00000000000..ad94f6343d8 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java @@ -0,0 +1,52 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.lang.reflect.Type; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +public class RoutingConfigAdapter implements JsonDeserializer { + + private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig"; + private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig"; + + @Override + public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { + final JsonObject jsonObject = jsonElement.getAsJsonObject(); + + if (!jsonObject.has("type")) { + throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object"); + } + + final String routingConfigType = jsonObject.get("type").getAsString(); + if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) { + return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class); + } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) { + return context.deserialize(jsonElement, RoutingTableRoutingConfig.class); + } + + throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\""); + } +} \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingTableRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingTableRoutingConfig.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java similarity index 78% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java index df40db4eb0b..d6355b2a6cd 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java @@ -19,6 +19,9 @@ package com.cloud.network.resource; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.naming.ConfigurationException; @@ -42,6 +45,8 @@ import com.cloud.network.nicira.NiciraNvpApiException; import com.cloud.network.nicira.SourceNatRule; import com.cloud.network.utils.CommandRetryUtility; import com.cloud.resource.ServerResource; +import com.cloud.utils.rest.CloudstackRESTException; +import com.cloud.utils.rest.HttpClientHelper; public class NiciraNvpResource implements ServerResource { @@ -49,6 +54,7 @@ public class NiciraNvpResource implements ServerResource { public static final int NAME_MAX_LEN = 40; public static final int NUM_RETRIES = 2; + private static final int MAX_REDIRECTS = 5; private String name; private String guid; @@ -58,39 +64,47 @@ public class NiciraNvpResource implements ServerResource { private NiciraNvpUtilities niciraNvpUtilities; private CommandRetryUtility retryUtility; - protected NiciraNvpApi createNiciraNvpApi() { - return new NiciraNvpApi(); + protected NiciraNvpApi createNiciraNvpApi(final String host, final String username, final String password) throws CloudstackRESTException { + try { + return NiciraNvpApi.create().host(host).username(username).password(password).httpClient(HttpClientHelper.createHttpClient(MAX_REDIRECTS)).build(); + } catch (final KeyManagementException e) { + throw new CloudstackRESTException("Could not create HTTP client", e); + } catch (final NoSuchAlgorithmException e) { + throw new CloudstackRESTException("Could not create HTTP client", e); + } catch (final KeyStoreException e) { + throw new CloudstackRESTException("Could not create HTTP client", e); + } } @Override public boolean configure(final String ignoredName, final Map params) throws ConfigurationException { - name = (String)params.get("name"); + name = (String) params.get("name"); if (name == null) { throw new ConfigurationException("Unable to find name"); } - guid = (String)params.get("guid"); + guid = (String) params.get("guid"); if (guid == null) { throw new ConfigurationException("Unable to find the guid"); } - zoneId = (String)params.get("zoneId"); + zoneId = (String) params.get("zoneId"); if (zoneId == null) { throw new ConfigurationException("Unable to find zone"); } - final String ip = (String)params.get("ip"); + final String ip = (String) params.get("ip"); if (ip == null) { throw new ConfigurationException("Unable to find IP"); } - final String adminuser = (String)params.get("adminuser"); + final String adminuser = (String) params.get("adminuser"); if (adminuser == null) { throw new ConfigurationException("Unable to find admin username"); } - final String adminpass = (String)params.get("adminpass"); + final String adminpass = (String) params.get("adminpass"); if (adminpass == null) { throw new ConfigurationException("Unable to find admin password"); } @@ -99,9 +113,11 @@ public class NiciraNvpResource implements ServerResource { retryUtility = CommandRetryUtility.getInstance(); retryUtility.setServerResource(this); - niciraNvpApi = createNiciraNvpApi(); - niciraNvpApi.setControllerAddress(ip); - niciraNvpApi.setAdminCredentials(adminuser, adminpass); + try { + niciraNvpApi = createNiciraNvpApi(ip, adminuser, adminpass); + } catch (final CloudstackRESTException e) { + throw new ConfigurationException("Could not create a Nicira Nvp API client: " + e.getMessage()); + } return true; } @@ -149,7 +165,7 @@ public class NiciraNvpResource implements ServerResource { sc.setPrivateIpAddress(""); sc.setStorageIpAddress(""); sc.setVersion(NiciraNvpResource.class.getPackage().getImplementationVersion()); - return new StartupCommand[] {sc}; + return new StartupCommand[] { sc }; } @Override @@ -212,16 +228,16 @@ public class NiciraNvpResource implements ServerResource { natRuleStr.append(m.getDestinationPort()); natRuleStr.append(" ]) -->"); if ("SourceNatRule".equals(rule.getType())) { - natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMin()); + natRuleStr.append(((SourceNatRule) rule).getToSourceIpAddressMin()); natRuleStr.append("-"); - natRuleStr.append(((SourceNatRule)rule).getToSourceIpAddressMax()); + natRuleStr.append(((SourceNatRule) rule).getToSourceIpAddressMax()); natRuleStr.append(" ["); - natRuleStr.append(((SourceNatRule)rule).getToSourcePort()); + natRuleStr.append(((SourceNatRule) rule).getToSourcePort()); natRuleStr.append(" ])"); } else { - natRuleStr.append(((DestinationNatRule)rule).getToDestinationIpAddress()); + natRuleStr.append(((DestinationNatRule) rule).getToDestinationIpAddress()); natRuleStr.append(" ["); - natRuleStr.append(((DestinationNatRule)rule).getToDestinationPort()); + natRuleStr.append(((DestinationNatRule) rule).getToDestinationPort()); natRuleStr.append(" ])"); } return natRuleStr.toString(); @@ -247,25 +263,25 @@ public class NiciraNvpResource implements ServerResource { Match m = new Match(); m.setDestinationIpAddresses(outsideIp); rulepair[0].setMatch(m); - ((DestinationNatRule)rulepair[0]).setToDestinationIpAddress(insideIp); + ((DestinationNatRule) rulepair[0]).setToDestinationIpAddress(insideIp); // create matching snat rule m = new Match(); m.setSourceIpAddresses(insideIp); rulepair[1].setMatch(m); - ((SourceNatRule)rulepair[1]).setToSourceIpAddressMin(outsideIp); - ((SourceNatRule)rulepair[1]).setToSourceIpAddressMax(outsideIp); + ((SourceNatRule) rulepair[1]).setToSourceIpAddressMin(outsideIp); + ((SourceNatRule) rulepair[1]).setToSourceIpAddressMax(outsideIp); return rulepair; } public NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts, - final String protocol) { + final String protocol) { // Start with a basic static nat rule, then add port and protocol details final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp); - ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]); + ((DestinationNatRule) rulepair[0]).setToDestinationPort(insidePorts[0]); rulepair[0].getMatch().setDestinationPort(outsidePorts[0]); rulepair[0].setOrder(50); rulepair[0].getMatch().setEthertype("IPv4"); @@ -275,7 +291,7 @@ public class NiciraNvpResource implements ServerResource { rulepair[0].getMatch().setProtocol(17); } - ((SourceNatRule)rulepair[1]).setToSourcePort(outsidePorts[0]); + ((SourceNatRule) rulepair[1]).setToSourcePort(outsidePorts[0]); rulepair[1].getMatch().setSourcePort(insidePorts[0]); rulepair[1].setOrder(50); rulepair[1].getMatch().setEthertype("IPv4"); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java similarity index 93% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java index 89e7a6e02a4..ae0d4ba2702 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java @@ -21,6 +21,8 @@ package com.cloud.network.resource.wrapper; import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; +import java.util.List; + import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; @@ -30,13 +32,12 @@ import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.network.nicira.NatRule; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.resource.NiciraNvpResource; import com.cloud.network.utils.CommandRetryUtility; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; -@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class) +@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class) public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends CommandWrapper { private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigurePortForwardingRulesCommandWrapper.class); @@ -45,7 +46,7 @@ public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends C public Answer execute(final ConfigurePortForwardingRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) { final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); try { - final NiciraNvpList existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid()); + final List existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid()); // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule // Any other SourceNat rule should have a corresponding DestinationNat rule @@ -60,12 +61,13 @@ public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends C return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, false, "Nicira NVP doesn't support port ranges for port forwarding"); } - final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol()); + final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), + rule.getProtocol()); NatRule incoming = null; NatRule outgoing = null; - for (final NatRule storedRule : existingRules.getResults()) { + for (final NatRule storedRule : existingRules) { if (storedRule.equalsIgnoreUuid(rulepair[1])) { // The outgoing rule exists outgoing = storedRule; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java similarity index 84% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java index e5d2dcd012d..d584629a5e1 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java @@ -21,19 +21,20 @@ package com.cloud.network.resource.wrapper; import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; +import java.util.List; + import com.cloud.agent.api.Answer; import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; import com.cloud.network.nicira.LogicalRouterPort; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.resource.NiciraNvpResource; import com.cloud.network.utils.CommandRetryUtility; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; -@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class) +@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class) public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrapper { @Override @@ -41,16 +42,16 @@ public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrap final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); try { - final NiciraNvpList ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid()); - if (ports.getResultCount() != 1) { + final List ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid()); + if (ports.size() != 1) { return new ConfigurePublicIpsOnLogicalRouterAnswer(command, false, "No logical router ports found, unable to set ip addresses"); } - final LogicalRouterPort lrp = ports.getResults().get(0); + final LogicalRouterPort lrp = ports.get(0); lrp.setIpAddresses(command.getPublicCidrs()); niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp); return new ConfigurePublicIpsOnLogicalRouterAnswer(command, true, "Configured " + command.getPublicCidrs().size() + " ip addresses on logical router uuid " + - command.getLogicalRouterUuid()); + command.getLogicalRouterUuid()); } catch (final NiciraNvpApiException e) { final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); retryUtility.addRetry(command, NUM_RETRIES); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java similarity index 94% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java index 1ce3cebd743..ae597842bce 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java @@ -21,6 +21,8 @@ package com.cloud.network.resource.wrapper; import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; +import java.util.List; + import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; @@ -30,13 +32,12 @@ import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.network.nicira.NatRule; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.resource.NiciraNvpResource; import com.cloud.network.utils.CommandRetryUtility; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; -@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class) +@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class) public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends CommandWrapper { private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigureStaticNatRulesCommandWrapper.class); @@ -46,7 +47,7 @@ public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends Comman final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); try { - final NiciraNvpList existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid()); + final List existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid()); // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule // Any other SourceNat rule should have a corresponding DestinationNat rule @@ -58,7 +59,7 @@ public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends Comman NatRule incoming = null; NatRule outgoing = null; - for (final NatRule storedRule : existingRules.getResults()) { + for (final NatRule storedRule : existingRules) { if (storedRule.equalsIgnoreUuid(rulepair[1])) { // The outgoing rule exists outgoing = storedRule; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java similarity index 89% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java index 40d58fcaf4d..8c11427d945 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java +++ b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java @@ -21,19 +21,20 @@ package com.cloud.network.resource.wrapper; import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; +import java.util.List; + import com.cloud.agent.api.Answer; import com.cloud.agent.api.FindLogicalSwitchPortAnswer; import com.cloud.agent.api.FindLogicalSwitchPortCommand; import com.cloud.network.nicira.LogicalSwitchPort; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.resource.NiciraNvpResource; import com.cloud.network.utils.CommandRetryUtility; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; -@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class) +@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class) public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandWrapper { @Override @@ -44,8 +45,8 @@ public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandW final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); try { - final NiciraNvpList ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid); - if (ports.getResultCount() == 0) { + final List ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid); + if (ports.size() == 0) { return new FindLogicalSwitchPortAnswer(command, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null); } else { return new FindLogicalSwitchPortAnswer(command, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java similarity index 100% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java rename to plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties similarity index 100% rename from plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties rename to plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml similarity index 100% rename from plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml rename to plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java similarity index 100% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java similarity index 100% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java new file mode 100644 index 00000000000..18797dfc544 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java @@ -0,0 +1,55 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import org.junit.Test; + +public class ExecutionCounterTest { + + @Test + public void testIncrementCounter() throws Exception { + final ExecutionCounter executionCounter = new ExecutionCounter(-1); + + executionCounter.incrementExecutionCounter().incrementExecutionCounter(); + + assertThat(executionCounter.getValue(), equalTo(2)); + } + + @Test + public void testHasNotYetReachedTheExecutuionLimit() throws Exception { + final ExecutionCounter executionCounter = new ExecutionCounter(2); + + executionCounter.incrementExecutionCounter(); + + assertThat(executionCounter.hasReachedExecutionLimit(), equalTo(false)); + } + + @Test + public void testHasAlreadyReachedTheExecutuionLimit() throws Exception { + final ExecutionCounter executionCounter = new ExecutionCounter(2); + + executionCounter.incrementExecutionCounter().incrementExecutionCounter(); + + assertThat(executionCounter.hasReachedExecutionLimit(), equalTo(true)); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java new file mode 100644 index 00000000000..199a6feedd7 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java @@ -0,0 +1,60 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; + +import org.junit.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +public class NatRuleAdapterTest { + private final Gson gson = new GsonBuilder() + .registerTypeAdapter(NatRule.class, new NatRuleAdapter()) + .create(); + + @Test(expected = JsonParseException.class) + public void testNatRuleAdapterNoType() { + gson.fromJson("{}", NatRule.class); + } + + @Test(expected = JsonParseException.class) + public void testNatRuleAdapterWrongType() { + gson.fromJson("{type : \"WrongType\"}", NatRule.class); + } + + @Test() + public void testNatRuleAdapterWithSourceNatRule() { + final SourceNatRule sourceNatRule = (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class); + + assertThat(sourceNatRule, instanceOf(SourceNatRule.class)); + } + + @Test() + public void testNatRuleAdapterWithDestinationNatRule() { + final DestinationNatRule destinationNatRule = (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class); + + assertThat(destinationNatRule, instanceOf(DestinationNatRule.class)); + } + +} diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java similarity index 98% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java index d4c65969ec0..e4072bd82a9 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java @@ -32,7 +32,7 @@ public class NatRuleTest { @Test public void testNatRuleEncoding() { final Gson gson = - new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter()) + new GsonBuilder().registerTypeAdapter(NatRule.class, new NatRuleAdapter()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java similarity index 57% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java index 3bb4b9db7a3..a95a8d673cf 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java @@ -22,16 +22,15 @@ package com.cloud.network.nicira; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Properties; import java.util.UUID; import org.junit.Before; import org.junit.Test; import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.rest.HttpClientHelper; public class NiciraNvpApiIT { @@ -40,18 +39,23 @@ public class NiciraNvpApiIT { protected long timestamp = System.currentTimeMillis(); @Before - public void setup() throws IOException { - final Properties properties = PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties")); - api = new NiciraNvpApi(); - api.setControllerAddress(properties.getProperty("nvp.host")); - api.setAdminCredentials(properties.getProperty("nvp.admin.user"), - properties.getProperty("nvp.admin.pwd")); + public void setup() throws Exception { + PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties")); + final String host = System.getProperty("nvp.host"); + final String user = System.getProperty("nvp.admin.user"); + final String pass = System.getProperty("nvp.admin.pwd"); + api = NiciraNvpApi.create() + .host(host) + .username(user) + .password(pass) + .httpClient(HttpClientHelper.createHttpClient(5)) + .build(); } @Test - public void testCRUDSecurityProfile() throws NiciraNvpApiException { + public void testCRUDSecurityProfile() { SecurityProfile sProfile = new SecurityProfile(); - sProfile.setDisplayName("SecProfile"+timestamp); + sProfile.setDisplayName("SecProfile" + timestamp); final List egressRules = new ArrayList(); sProfile.setLogicalPortEgressRules(egressRules); @@ -73,27 +77,23 @@ public class NiciraNvpApiIT { sProfile = api.createSecurityProfile(sProfile); // We can now update the new entity - sProfile.setDisplayName("UpdatedSecProfile"+timestamp); + sProfile.setDisplayName("UpdatedSecProfile" + timestamp); api.updateSecurityProfile(sProfile, sProfile.getUuid()); // Read them all - NiciraNvpList profiles = api.findSecurityProfile(); + List profiles = api.findSecurityProfile(); SecurityProfile scInList = null; - for(final SecurityProfile iProfile : profiles.getResults()) { + for (final SecurityProfile iProfile : profiles) { if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) { scInList = iProfile; } } - assertEquals("Read a Security Profile different from the one just created and updated", - sProfile, scInList); + assertEquals("Read a Security Profile different from the one just created and updated", sProfile, scInList); // Read them filtered by uuid (get one) profiles = api.findSecurityProfile(sProfile.getUuid()); - assertEquals("Read a Security Profile different from the one just created and updated", - sProfile, - profiles.getResults().get(0)); - assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", - 1, profiles.getResults().size()); + assertEquals("Read a Security Profile different from the one just created and updated", sProfile, profiles.get(0)); + assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", 1, profiles.size()); // We can now delete the new entity api.deleteSecurityProfile(sProfile.getUuid()); @@ -104,25 +104,21 @@ public class NiciraNvpApiIT { } @Test - public void testCRUDAcl() throws NiciraNvpApiException { + public void testCRUDAcl() { Acl acl = new Acl(); - acl.setDisplayName("Acl"+timestamp); + acl.setDisplayName("Acl" + timestamp); // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type // Note that if the protocol is 1 (ICMP) then you cannot put ports final List egressRules = new ArrayList(); acl.setLogicalPortEgressRules(egressRules); - egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, - "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); - egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, - "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); + egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); + egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); final List ingressRules = new ArrayList(); acl.setLogicalPortIngressRules(ingressRules); - ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, - "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); - ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, - "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); + ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); + ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); final List tags = new ArrayList(); acl.setTags(tags); @@ -134,27 +130,23 @@ public class NiciraNvpApiIT { acl = api.createAcl(acl); // We can now update the new entity - acl.setDisplayName("UpdatedAcl"+timestamp); + acl.setDisplayName("UpdatedAcl" + timestamp); api.updateAcl(acl, acl.getUuid()); // Read them all - NiciraNvpList acls = api.findAcl(); + List acls = api.findAcl(); Acl scInList = null; - for(final Acl iAcl : acls.getResults()) { + for (final Acl iAcl : acls) { if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) { scInList = iAcl; } } - assertEquals("Read a ACL different from the one just created and updated", - acl, scInList); + assertEquals("Read a ACL different from the one just created and updated", acl, scInList); // Read them filtered by uuid (get one) acls = api.findAcl(acl.getUuid()); - assertEquals("Read a ACL different from the one just created and updated", - acl, - acls.getResults().get(0)); - assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", - 1, acls.getResults().size()); + assertEquals("Read a ACL different from the one just created and updated", acl, acls.get(0)); + assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", 1, acls.size()); // We can now delete the new entity api.deleteAcl(acl.getUuid()); @@ -165,9 +157,9 @@ public class NiciraNvpApiIT { } @Test - public void testCRUDLogicalSwitch() throws NiciraNvpApiException { + public void testCRUDLogicalSwitch() throws Exception { LogicalSwitch logicalSwitch = new LogicalSwitch(); - logicalSwitch.setDisplayName("LogicalSwitch"+timestamp); + logicalSwitch.setDisplayName("LogicalSwitch" + timestamp); logicalSwitch.setPortIsolationEnabled(true); logicalSwitch.setReplicationMode("service"); logicalSwitch.setTags(new ArrayList()); @@ -175,78 +167,65 @@ public class NiciraNvpApiIT { // In the creation we don't get to specify UUID, href or schema: they don't exist yet - try { - logicalSwitch = api.createLogicalSwitch(logicalSwitch); + logicalSwitch = api.createLogicalSwitch(logicalSwitch); - // We can now update the new entity - logicalSwitch.setDisplayName("UpdatedLogicalSwitch"+timestamp); - api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid()); + // We can now update the new entity + logicalSwitch.setDisplayName("UpdatedLogicalSwitch" + timestamp); + api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid()); - // Read them all - NiciraNvpList logicalSwitches = api.findLogicalSwitch(); - for(final LogicalSwitch iLogicalSwitch : logicalSwitches.getResults()) { - if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) { - assertEquals("Read a LogicalSwitch different from the one just created and updated", - logicalSwitch, iLogicalSwitch); - } + // Read them all + List logicalSwitches = api.findLogicalSwitch(); + for (final LogicalSwitch iLogicalSwitch : logicalSwitches) { + if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) { + assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, iLogicalSwitch); } - - // Read them filtered by uuid (get one) - logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid()); - assertEquals("Read a LogicalSwitch different from the one just created and updated", - logicalSwitch, - logicalSwitches.getResults().get(0)); - assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item", - 1, logicalSwitches.getResults().size()); - - // Before deleting the test LogicalSwitch, test its ports - final List 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); } + + // Read them filtered by uuid (get one) + logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid()); + assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, logicalSwitches.get(0)); + assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item", 1, logicalSwitches.size()); + + // 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 List logicalSwitchePorts = api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid()); + for (final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts) { + if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) { + assertEquals("Read a LogicalSwitchPort different from the one just created and updated", logicalSwitchPort, iLSwitchPort); + } + } + + // And finally test attachments + final String attachmentUuid = UUID.randomUUID().toString(); + final VifAttachment vifAttachment = new VifAttachment(attachmentUuid); + api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), vifAttachment); + + 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()); } @Test - public void testCRUDLogicalRouter() throws NiciraNvpApiException { + public void testCRUDLogicalRouter() { LogicalRouter logicalRouter = new LogicalRouter(); - logicalRouter.setDisplayName("LogicalRouter"+timestamp); + logicalRouter.setDisplayName("LogicalRouter" + timestamp); logicalRouter.setDistributed(true); logicalRouter.setNatSynchronizationEnabled(true); logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE); final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig( - new RouterNextHop("192.168.10.20")); + new RouterNextHop("192.168.10.20")); logicalRouter.setRoutingConfig(routingConfig); // In the creation we don't get to specify UUID, href or schema: they don't exist yet @@ -255,37 +234,32 @@ public class NiciraNvpApiIT { logicalRouter = api.createLogicalRouter(logicalRouter); // We can now update the new entity - logicalRouter.setDisplayName("UpdatedLogicalSwitch"+timestamp); + logicalRouter.setDisplayName("UpdatedLogicalSwitch" + timestamp); api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid()); // Read them all - NiciraNvpList logicalRouters = api.findLogicalRouter(); + List logicalRouters = api.findLogicalRouter(); LogicalRouter lsInList = null; - for(final LogicalRouter iLogicalRouter : logicalRouters.getResults()) { + for (final LogicalRouter iLogicalRouter : logicalRouters) { if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) { lsInList = iLogicalRouter; } } - assertEquals("Read a LogicalRouter different from the one just created and updated", - logicalRouter, lsInList); + assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, lsInList); // Read them filtered by uuid (get one) logicalRouters = api.findLogicalRouter(logicalRouter.getUuid()); - assertEquals("Read a LogicalRouter different from the one just created and updated", - logicalRouter, - logicalRouters.getResults().get(0)); - assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item", - 1, logicalRouters.getResults().size()); + assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, logicalRouters.get(0)); + assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item", 1, logicalRouters.size()); - assertEquals("", logicalRouters.getResults().get(0), - api.findOneLogicalRouterByUuid(logicalRouter.getUuid())); + assertEquals(logicalRouters.get(0), api.findOneLogicalRouterByUuid(logicalRouter.getUuid())); // Before deleting the test LogicalRouter, test its ports final List tags = new ArrayList(); tags.add(new NiciraNvpTag("cs_account", "OwnerName")); LogicalRouterPort logicalRouterPort = new LogicalRouterPort(); - logicalRouterPort.setDisplayName("LRouterPort"+timestamp); + logicalRouterPort.setDisplayName("LRouterPort" + timestamp); logicalRouterPort.setTags(tags); logicalRouterPort.setAdminStatusEnabled(true); logicalRouterPort.setPortno(1024); @@ -296,15 +270,13 @@ public class NiciraNvpApiIT { logicalRouterPort.setIpAddresses(ipAddresses); logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort); - logicalRouterPort.setDisplayName("UpdatedLRouterPort"+timestamp); + logicalRouterPort.setDisplayName("UpdatedLRouterPort" + timestamp); api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort); - final NiciraNvpList logicalRouterePorts = - api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid()); - for(final LogicalRouterPort iLRouterPort : logicalRouterePorts.getResults()) { + final List logicalRouterePorts = api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid()); + for (final LogicalRouterPort iLRouterPort : logicalRouterePorts) { if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) { - assertEquals("Read a LogicalRouterPort different from the one just created and updated", - logicalRouterPort, iLRouterPort); + assertEquals("Read a LogicalRouterPort different from the one just created and updated", logicalRouterPort, iLRouterPort); } } @@ -339,8 +311,8 @@ public class NiciraNvpApiIT { public void testGetControlClusterStatus() throws NiciraNvpApiException { final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus(); final String clusterStatus = controlClusterStatus.getClusterStatus(); - final boolean correctStatus = (clusterStatus.equalsIgnoreCase("stable") || - clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable")); + final boolean correctStatus = clusterStatus.equalsIgnoreCase("stable") || + clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"); assertTrue("Not recognizable cluster status", correctStatus); } diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java new file mode 100644 index 00000000000..79546a68472 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java @@ -0,0 +1,198 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.message.BasicStatusLine; +import org.hamcrest.Matchers; +import org.junit.Test; + +import com.cloud.utils.rest.HttpClientHelper; +import com.cloud.utils.rest.HttpUriRequestMethodMatcher; +import com.cloud.utils.rest.HttpUriRequestPathMatcher; +import com.cloud.utils.rest.HttpUriRequestQueryMatcher; + +public class NiciraNvpApiTest { + private static final StatusLine HTTP_200_REPSONSE = new BasicStatusLine(new ProtocolVersion("HTTPS", 1, 1), HttpStatus.SC_OK, "OK"); + private static final StatusLine HTTP_201_REPSONSE = new BasicStatusLine(new ProtocolVersion("HTTPS", 1, 1), HttpStatus.SC_CREATED, "Created"); + + protected static final String UUID = "aaaa"; + protected static final String UUID2 = "bbbb"; + protected static final String UUID_SEC_PROFILE_URI = NiciraConstants.SEC_PROFILE_URI_PREFIX + "/aaaa"; + protected static final String SCHEMA = "myTestSchema"; + protected static final String SCHEMA2 = "myTestSchema2"; + protected static final String HREF = "myTestHref"; + protected static final String HREF2 = "myTestHref2"; + protected static final String SEC_PROFILE_JSON_RESPONSE = + "{\"uuid\" : \"aaaa\"," + + "\"display_name\" : \"myTestName\"," + + "\"href\" : \"myTestHref\"," + + "\"schema\" : \"myTestSchema\"}"; + + 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}"; + + private static NiciraNvpApi buildApi(final CloseableHttpClient httpClient) { + return NiciraNvpApi.create() + .host("localhost") + .username("admin") + .password("adminpassword") + .httpClient(httpClient) + .build(); + } + + @Test + @SuppressWarnings("unchecked") + public void testFindSecurityProfile() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_200_REPSONSE); + when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_LIST_JSON_RESPONSE)); + final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); + doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); + final NiciraNvpApi api = buildApi(httpClient); + + final List actualProfiles = api.findSecurityProfile(); + + assertThat("Wrong number of results", actualProfiles, hasSize(2)); + assertThat("Wrong Uuid in the newly created SecurityProfile", actualProfiles, Matchers. contains( + hasProperty("uuid", equalTo(UUID)), + hasProperty("uuid", equalTo(UUID2)))); + assertThat("Wrong HREF in the newly created SecurityProfile", actualProfiles, Matchers. contains( + hasProperty("href", equalTo(HREF)), + hasProperty("href", equalTo(HREF2)))); + assertThat("Wrong Schema in the newly created SecurityProfile", actualProfiles, Matchers. contains( + hasProperty("schema", equalTo(SCHEMA)), + hasProperty("schema", equalTo(SCHEMA2)))); + verify(response, times(1)).close(); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQuery("fields=*"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); + } + + @Test + @SuppressWarnings("unchecked") + public void testFindSecurityProfileByUuid() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_200_REPSONSE); + when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_LIST_JSON_RESPONSE)); + final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); + doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); + final NiciraNvpApi api = buildApi(httpClient); + + final List actualProfiles = api.findSecurityProfile(UUID); + + assertThat("Wrong number of results", actualProfiles, hasSize(2)); + assertThat("Wrong Uuid in the newly created SecurityProfile", actualProfiles, Matchers. contains( + hasProperty("uuid", equalTo(UUID)), + hasProperty("uuid", equalTo(UUID2)))); + assertThat("Wrong HREF in the newly created SecurityProfile", actualProfiles, Matchers. contains( + hasProperty("href", equalTo(HREF)), + hasProperty("href", equalTo(HREF2)))); + assertThat("Wrong Schema in the newly created SecurityProfile", actualProfiles, Matchers. contains( + hasProperty("schema", equalTo(SCHEMA)), + hasProperty("schema", equalTo(SCHEMA2)))); + verify(response, times(1)).close(); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("uuid=" + UUID), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("fields=*"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); + } + + @Test + public void testCreateSecurityProfile() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); + when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); + final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); + doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); + final NiciraNvpApi api = buildApi(httpClient); + + final SecurityProfile actualSecProfile = api.createSecurityProfile(new SecurityProfile()); + + assertThat("Wrong Uuid in the newly created SecurityProfile", actualSecProfile, hasProperty("uuid", equalTo(UUID))); + assertThat("Wrong Href in the newly created SecurityProfile", actualSecProfile, hasProperty("href", equalTo(HREF))); + assertThat("Wrong Schema in the newly created SecurityProfile", actualSecProfile, hasProperty("schema", equalTo(SCHEMA))); + verify(response, times(1)).close(); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); + } + + @Test + public void testUpdateSecurityProfile() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); + when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); + final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); + doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); + final NiciraNvpApi api = buildApi(httpClient); + + api.updateSecurityProfile(new SecurityProfile(), UUID); + + verify(response, times(1)).close(); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX + "/" + UUID), any(HttpClientContext.class)); + } + + @Test + public void testDeleteSecurityProfile() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); + when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); + final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); + doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); + final NiciraNvpApi api = buildApi(httpClient); + + api.deleteSecurityProfile(UUID); + + verify(response, times(1)).close(); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("DELETE"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX + "/" + UUID), any(HttpClientContext.class)); + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java new file mode 100644 index 00000000000..7fcab8001bb --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java @@ -0,0 +1,172 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.sameInstance; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpHost; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.message.BasicStatusLine; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.cloud.utils.rest.CloudstackRESTException; +import com.cloud.utils.rest.HttpMethods; +import com.cloud.utils.rest.HttpRequestMatcher; +import com.cloud.utils.rest.HttpUriRequestBuilder; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(NiciraRestClient.class) +public class NiciraRestClientTest { + + private static final int HTTPS_PORT = 443; + + private static final String HTTPS = "HTTPS"; + private static final String LOGIN_PATH = "/login"; + private static final String LOCALHOST = "localhost"; + private static final String ADMIN = "admin"; + private static final String ADMIN_PASSWORD = "adminpassword"; + + private static final HttpHost HTTP_HOST = new HttpHost(LOCALHOST, HTTPS_PORT, HTTPS); + + private static final StatusLine HTTP_200_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 200, "OK"); + private static final StatusLine HTTP_401_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 401, "Unauthorized"); + + private static final Map loginParameters = new HashMap(); + private static HttpUriRequest request; + private static HttpUriRequest loginRequest; + private final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + private final CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class); + private HttpClientContext httpClientContext; + private NiciraRestClient client; + + @BeforeClass + public static void setupClass() { + loginParameters.put("username", ADMIN); + loginParameters.put("password", ADMIN_PASSWORD); + request = HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("/path") + .build(); + loginRequest = HttpUriRequestBuilder.create() + .method(HttpMethods.POST) + .methodParameters(loginParameters) + .path(LOGIN_PATH) + .build(); + } + + @Before + public void setup() { + httpClientContext = HttpClientContext.create(); + client = spy(NiciraRestClient.create() + .client(httpClient) + .clientContext(httpClientContext) + .hostname(LOCALHOST) + .username(ADMIN) + .password(ADMIN_PASSWORD) + .loginUrl(LOGIN_PATH) + .executionLimit(5) + .build()); + } + + @Test + public void testExecuteSuccessAtFirstAttempt() throws Exception { + when(mockResponse.getStatusLine()).thenReturn(HTTP_200_STATUSLINE); + when(httpClient.execute(eq(HTTP_HOST), eq(request), eq(httpClientContext))).thenReturn(mockResponse); + + final CloseableHttpResponse response = client.execute(request); + + assertThat(response, notNullValue()); + assertThat(response, sameInstance(mockResponse)); + verifyPrivate(client).invoke("execute", request, 0); + } + + @Test + public void testExecuteUnauthorizedThenSuccess() throws Exception { + when(mockResponse.getStatusLine()) + .thenReturn(HTTP_401_STATUSLINE) + .thenReturn(HTTP_200_STATUSLINE) + .thenReturn(HTTP_200_STATUSLINE); + when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext))) + .thenReturn(mockResponse) + .thenReturn(mockResponse); + when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext))) + .thenReturn(mockResponse); + + final CloseableHttpResponse response = client.execute(request); + + assertThat(response, notNullValue()); + assertThat(response, sameInstance(mockResponse)); + verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(request), eq(0)); + verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(loginRequest), eq(401)); + verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(request), eq(200)); + } + + @Test + public void testExecuteTwoConsecutiveUnauthorizedExecutions() throws Exception { + when(mockResponse.getStatusLine()) + .thenReturn(HTTP_401_STATUSLINE) + .thenReturn(HTTP_401_STATUSLINE); + when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext))) + .thenReturn(mockResponse); + when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext))) + .thenReturn(mockResponse); + final NiciraRestClient client = spy(NiciraRestClient.create() + .client(httpClient) + .clientContext(httpClientContext) + .hostname(LOCALHOST) + .username(ADMIN) + .password(ADMIN_PASSWORD) + .loginUrl(LOGIN_PATH) + .executionLimit(2) + .build()); + + try { + client.execute(request); + fail("Expected CloudstackRESTException exception"); + } catch (final CloudstackRESTException e) { + assertThat(e.getMessage(), not(isEmptyOrNullString())); + verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(request), eq(0)); + verifyPrivate(client).invoke("execute", HttpRequestMatcher.eq(loginRequest), eq(401)); + } + } +} diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java similarity index 100% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java new file mode 100644 index 00000000000..44269b23544 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java @@ -0,0 +1,57 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.notNullValue; + +import org.junit.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +public class RoutingConfigAdapterTest { + private final Gson gson = new GsonBuilder() + .registerTypeAdapter(RoutingConfig.class, new RoutingConfigAdapter()) + .create(); + + @Test(expected = JsonParseException.class) + public void testRoutingConfigAdapterNoType() { + gson.fromJson("{}", RoutingConfig.class); + } + + @Test(expected = JsonParseException.class) + public void testRoutingConfigAdapterWrongType() { + gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class); + } + + @Test() + public void testRoutingConfigAdapter() throws Exception { + final String jsonString = "{type : \"SingleDefaultRouteImplicitRoutingConfig\"}"; + + final SingleDefaultRouteImplicitRoutingConfig object = gson.fromJson(jsonString, SingleDefaultRouteImplicitRoutingConfig.class); + + assertThat(object, notNullValue()); + assertThat(object, instanceOf(SingleDefaultRouteImplicitRoutingConfig.class)); + } + +} diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java similarity index 96% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java index 7fe6287455d..beb40591305 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java @@ -45,7 +45,6 @@ import com.cloud.network.nicira.LogicalRouterPort; import com.cloud.network.nicira.LogicalSwitch; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.nicira.VifAttachment; public class NiciraNvpRequestWrapperTest { @@ -144,12 +143,8 @@ public class NiciraNvpRequestWrapperTest { final List listPorts = new ArrayList(); listPorts.add(port1); - final NiciraNvpList ports = new NiciraNvpList(); - ports.setResults(listPorts); - ports.setResultCount(1); - final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; + final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; final List publicCidrs = new ArrayList(); publicCidrs.add("10.1.1.0/24"); @@ -158,7 +153,7 @@ public class NiciraNvpRequestWrapperTest { when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); try { - when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(ports); + when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(listPorts); doNothing().when(niciraNvpApi).updateLogicalRouterPort(command.getLogicalRouterUuid(), port1); } catch (final NiciraNvpApiException e) { fail(e.getMessage()); @@ -177,7 +172,7 @@ public class NiciraNvpRequestWrapperTest { final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; + final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; final DeleteLogicalSwitchPortCommand command = new DeleteLogicalSwitchPortCommand(logicalSwitchUuid, logicalSwitchPortUuid); diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java similarity index 78% rename from plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java rename to plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java index ddf2993fdb8..c0dedd28445 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java +++ b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java @@ -83,7 +83,6 @@ import com.cloud.network.nicira.LogicalSwitchPort; import com.cloud.network.nicira.NatRule; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpList; import com.cloud.network.nicira.SourceNatRule; import com.cloud.network.utils.CommandRetryUtility; @@ -95,10 +94,10 @@ public class NiciraNvpResourceTest { private CommandRetryUtility retryUtility; @Before - public void setUp() throws ConfigurationException { + public void setUp() { resource = new NiciraNvpResource() { @Override - protected NiciraNvpApi createNiciraNvpApi() { + protected NiciraNvpApi createNiciraNvpApi(final String host, final String username, final String password) { return nvpApi; } }; @@ -120,20 +119,6 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", Collections. emptyMap()); } - @Test - public void resourceConfigure() throws ConfigurationException { - resource.configure("NiciraNvpResource", parameters); - - verify(nvpApi).setAdminCredentials("adminuser", "adminpass"); - verify(nvpApi).setControllerAddress("127.0.0.1"); - assertTrue("Incorrect resource name", "nvptestdevice".equals(resource.getName())); - - /* Pretty lame test, but here to assure this plugin fails - * if the type name ever changes from L2Networking - */ - assertTrue("Incorrect resource type", resource.getType() == Host.Type.L2Networking); - } - @Test public void testInitialization() throws ConfigurationException { resource.configure("NiciraNvpResource", parameters); @@ -189,10 +174,10 @@ public class NiciraNvpResourceTest { final LogicalSwitch ls = mock(LogicalSwitch.class); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); + when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); - final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); - final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc); + final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner"); + final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc); assertTrue(clsa.getResult()); } @@ -202,10 +187,10 @@ public class NiciraNvpResourceTest { final LogicalSwitch ls = mock(LogicalSwitch.class); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls); + when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenReturn(ls); - final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); - final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc); + final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner"); + final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc); assertTrue(clsa.getResult()); assertTrue("cccc".equals(clsa.getLogicalSwitchUuid())); } @@ -216,19 +201,19 @@ public class NiciraNvpResourceTest { final LogicalSwitch ls = mock(LogicalSwitch.class); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()); - final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); - final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc); + final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner"); + final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc); assertFalse(clsa.getResult()); } @Test - public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { + public void testDeleteLogicalSwitch() throws ConfigurationException { resource.configure("NiciraNvpResource", parameters); final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); + final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) resource.executeRequest(dlsc); assertTrue(dlsa.getResult()); } @@ -236,10 +221,10 @@ public class NiciraNvpResourceTest { public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any()); + doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String) any()); final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); + final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) resource.executeRequest(dlsc); assertFalse(dlsa.getResult()); } @@ -249,10 +234,10 @@ public class NiciraNvpResourceTest { final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); when(lsp.getUuid()).thenReturn("eeee"); - when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp); + when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); + final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc); assertTrue(clspa.getResult()); assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); @@ -264,10 +249,10 @@ public class NiciraNvpResourceTest { final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); when(lsp.getUuid()).thenReturn("eeee"); - when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenThrow(new NiciraNvpApiException()); final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); + final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc); assertFalse(clspa.getResult()); } @@ -277,21 +262,21 @@ public class NiciraNvpResourceTest { final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); when(lsp.getUuid()).thenReturn("eeee"); - when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp); - doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); + when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); + doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); + final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc); assertFalse(clspa.getResult()); - verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any()); + verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String) any(), (String) any()); } @Test public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any()); - final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb")); + doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String) any(), (String) any()); + final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer) resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb")); assertFalse(dlspa.getResult()); } @@ -299,9 +284,9 @@ public class NiciraNvpResourceTest { public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); + doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); final UpdateLogicalSwitchPortAnswer dlspa = - (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname")); + (UpdateLogicalSwitchPortAnswer) resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname")); assertFalse(dlspa.getResult()); } @@ -309,13 +294,10 @@ public class NiciraNvpResourceTest { public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - @SuppressWarnings("unchecked") - final - NiciraNvpList lspl = mock(NiciraNvpList.class); - when(lspl.getResultCount()).thenReturn(1); + final List lspl = Arrays.asList(new LogicalSwitchPort()); when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); assertTrue(flspa.getResult()); } @@ -324,12 +306,10 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", parameters); @SuppressWarnings("unchecked") - final - NiciraNvpList lspl = mock(NiciraNvpList.class); - when(lspl.getResultCount()).thenReturn(0); + final List lspl = Collections.EMPTY_LIST; when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); assertFalse(flspa.getResult()); } @@ -339,7 +319,7 @@ public class NiciraNvpResourceTest { when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); - final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); assertFalse(flspa.getResult()); } @@ -353,24 +333,24 @@ public class NiciraNvpResourceTest { when(lrc.getUuid()).thenReturn("ccccc"); when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); when(lsp.getUuid()).thenReturn("fffff"); - when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc); - when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); - when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); + when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc); + when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenReturn(lrp); + when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort) any())).thenReturn(lsp); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); assertTrue(clra.getResult()); assertTrue("ccccc".equals(clra.getLogicalRouterUuid())); - verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String)any(), (NatRule)any()); + verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String) any(), (NatRule) any()); } @Test public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenThrow(new NiciraNvpApiException()); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); assertFalse(clra.getResult()); } @@ -381,10 +361,10 @@ public class NiciraNvpResourceTest { final LogicalRouter lrc = mock(LogicalRouter.class); when(lrc.getUuid()).thenReturn("ccccc"); - when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc); - when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc); + when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenThrow(new NiciraNvpApiException()); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); assertFalse(clra.getResult()); verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); @@ -400,12 +380,12 @@ public class NiciraNvpResourceTest { when(lrc.getUuid()).thenReturn("ccccc"); when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); when(lsp.getUuid()).thenReturn("fffff"); - when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc); - when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); - when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); - when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc); + when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenReturn(lrp); + when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort) any())).thenReturn(lsp); + when(nvpApi.createLogicalRouterNatRule((String) any(), (NatRule) any())).thenThrow(new NiciraNvpApiException()); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); + final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); assertFalse(clra.getResult()); verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); @@ -417,7 +397,7 @@ public class NiciraNvpResourceTest { resource.configure("NiciraNvpResource", parameters); doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa")); - final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); + final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer) resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); assertFalse(dlspa.getResult()); } @@ -427,15 +407,14 @@ public class NiciraNvpResourceTest { final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); @SuppressWarnings("unchecked") - final - NiciraNvpList list = mock(NiciraNvpList.class); + final List list = Collections.EMPTY_LIST; when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list); - doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any()); + doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String) any(), (LogicalRouterPort) any()); - final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) resource.executeRequest(cmd); assertFalse(answer.getResult()); } @@ -450,7 +429,7 @@ public class NiciraNvpResourceTest { when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenThrow(new NiciraNvpApiException("retry 1")).thenThrow(new NiciraNvpApiException("retry 2")); - final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) resource.executeRequest(cmd); assertFalse(answer.getResult()); } @@ -458,9 +437,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -473,27 +451,26 @@ public class NiciraNvpResourceTest { // Mock the api find call @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); + final List storedRules = Collections.EMPTY_LIST; when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); // Mock the api create calls final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertTrue(a.getResult()); verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - final NatRule rule = (NatRule)argument; - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + final NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { return true; } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { return true; } return false; @@ -504,9 +481,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -521,27 +497,23 @@ public class NiciraNvpResourceTest { final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); // Mock the api find call - @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + final List storedRules = Arrays.asList(rulepair); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertTrue(a.getResult()); verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - final NatRule rule = (NatRule)argument; - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + final NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { return true; } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { return true; } return false; @@ -552,9 +524,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -571,23 +542,19 @@ public class NiciraNvpResourceTest { final UUID rule1Uuid = UUID.randomUUID(); rulepair[0].setUuid(rule0Uuid); rulepair[1].setUuid(rule1Uuid); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); // Mock the api find call - @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + final List storedRules = Arrays.asList(rulepair); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertTrue(a.getResult()); verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - final UUID uuid = (UUID)argument; + final UUID uuid = (UUID) argument; if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { return true; } @@ -599,9 +566,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -616,16 +582,14 @@ public class NiciraNvpResourceTest { final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); // Mock the api find call @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(0); + final List storedRules = Collections.EMPTY_LIST; when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertFalse(a.getResult()); verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); @@ -634,9 +598,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -649,27 +612,26 @@ public class NiciraNvpResourceTest { // Mock the api find call @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); + final List storedRules = Collections.EMPTY_LIST; when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); + final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertTrue(a.getResult()); verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - final NatRule rule = (NatRule)argument; - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + final NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { return true; } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { return true; } return false; @@ -680,9 +642,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -694,30 +655,26 @@ public class NiciraNvpResourceTest { when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); + final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); // Mock the api find call - @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + final List storedRules = Arrays.asList(rulepair); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertTrue(a.getResult()); verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - final NatRule rule = (NatRule)argument; - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { + final NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { return true; } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule)rule).getToSourceIpAddressMin().equals("11.11.11.11")) { + if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { return true; } return false; @@ -728,9 +685,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -742,28 +698,24 @@ public class NiciraNvpResourceTest { when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); + final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); final UUID rule0Uuid = UUID.randomUUID(); final UUID rule1Uuid = UUID.randomUUID(); rulepair[0].setUuid(rule0Uuid); rulepair[1].setUuid(rule1Uuid); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); // Mock the api find call - @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(2); - when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + final List storedRules = Arrays.asList(rulepair); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertTrue(a.getResult()); verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - final UUID uuid = (UUID)argument; + final UUID uuid = (UUID) argument; if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { return true; } @@ -775,9 +727,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -789,19 +740,17 @@ public class NiciraNvpResourceTest { when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); + final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); // Mock the api find call @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); - when(storedRules.getResultCount()).thenReturn(0); + final List storedRules = Collections.EMPTY_LIST; when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); assertFalse(a.getResult()); verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); @@ -810,9 +759,8 @@ public class NiciraNvpResourceTest { @Test public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException { resource.configure("NiciraNvpResource", parameters); - /* StaticNat - * Outside IP: 11.11.11.11 - * Inside IP: 10.10.10.10 + /* + * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 */ // Mock the command @@ -825,17 +773,16 @@ public class NiciraNvpResourceTest { // Mock the api find call @SuppressWarnings("unchecked") - final - NiciraNvpList storedRules = mock(NiciraNvpList.class); + final List storedRules = Collections.EMPTY_LIST; when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp"); + final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 80, 85 }, "11.11.11.11", new int[] { 80, 85 }, "tcp"); rulepair[0].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); + final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); // The expected result is false, Nicira does not support port ranges in DNAT assertFalse(a.getResult()); @@ -848,12 +795,12 @@ public class NiciraNvpResourceTest { assertTrue("DestinationNatRule".equals(rules[0].getType())); assertTrue("SourceNatRule".equals(rules[1].getType())); - final DestinationNatRule dnr = (DestinationNatRule)rules[0]; + final DestinationNatRule dnr = (DestinationNatRule) rules[0]; assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); assertTrue(dnr.getToDestinationPort() == null); assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); - final SourceNatRule snr = (SourceNatRule)rules[1]; + final SourceNatRule snr = (SourceNatRule) rules[1]; assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); assertTrue(snr.getToSourcePort() == null); assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); @@ -861,18 +808,18 @@ public class NiciraNvpResourceTest { @Test public void testGeneratePortForwardingRulePair() { - final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); + final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); assertTrue("DestinationNatRule".equals(rules[0].getType())); assertTrue("SourceNatRule".equals(rules[1].getType())); - final DestinationNatRule dnr = (DestinationNatRule)rules[0]; + final DestinationNatRule dnr = (DestinationNatRule) rules[0]; assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); assertTrue(dnr.getToDestinationPort() == 8080); assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); assertTrue(dnr.getMatch().getDestinationPort() == 80); assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6); - final SourceNatRule snr = (SourceNatRule)rules[1]; + final SourceNatRule snr = (SourceNatRule) rules[1]; assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); assertTrue(snr.getToSourcePort() == 80); assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); diff --git a/plugins/network-elements/nicira-nvp/test/resources/config.properties b/plugins/network-elements/nicira-nvp/src/test/resources/config.properties similarity index 100% rename from plugins/network-elements/nicira-nvp/test/resources/config.properties rename to plugins/network-elements/nicira-nvp/src/test/resources/config.properties diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java deleted file mode 100644 index 1435cc5f517..00000000000 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java +++ /dev/null @@ -1,339 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.network.nicira; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Matchers.any; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.params.HttpClientParams; -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import com.google.gson.Gson; -import com.google.gson.JsonParseException; -import com.cloud.utils.rest.RESTServiceConnector; -import com.cloud.utils.rest.RESTValidationStrategy; - -public class NiciraNvpApiTest { - protected static final String UUID = "aaaa"; - protected static final String UUID2 = "bbbb"; - protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa"; - protected static final String SCHEMA = "myTestSchema"; - protected static final String SCHEMA2 = "myTestSchema2"; - protected static final String HREF = "myTestHref"; - protected static final String HREF2 = "myTestHref2"; - protected static final String SEC_PROFILE_JSON_RESPONSE = - "{\"uuid\" : \"aaaa\"," - + "\"display_name\" : \"myTestName\"," - + "\"href\" : \"myTestHref\"," - + "\"schema\" : \"myTestSchema\"}"; - - protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\"," - + "\"display_name\" : \"myTestName\"," - + "\"href\" : \"myTestHref\"," - + "\"schema\" : \"myTestSchema\"}," - + "{ \"uuid\" : \"bbbb\"," - + "\"display_name\" : \"myTestName2\"," - + "\"href\" : \"myTestHref2\"," - + "\"schema\" : \"myTestSchema2\"}]," - + "\"result_count\": 2}"; - - NiciraNvpApi api; - HttpClient client = mock(HttpClient.class); - HttpMethod method; - String type; - String uri; - - @Before - public void setUp() { - final HttpClientParams hmp = mock(HttpClientParams.class); - when(client.getParams()).thenReturn(hmp); - api = new NiciraNvpApi(); - - api.restConnector = new RESTServiceConnector(new RESTValidationStrategy()) { - @Override - public HttpClient createHttpClient() { - return client; - } - - @Override - public HttpMethod createMethod(final String newType, final String newUri) { - type = newType; - uri = newUri; - return method; - } - }; - - api.setAdminCredentials("admin", "adminpass"); - api.setControllerAddress("localhost"); - } - - @Test - public void testFindSecurityProfile() throws NiciraNvpApiException, IOException { - // Prepare - method = mock(GetMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE); - final NameValuePair[] queryString = new NameValuePair[]{ - new NameValuePair("fields","*")}; - - // Execute - final NiciraNvpList actualProfiles = api.findSecurityProfile(); - - // Assert - verify(method, times(1)).releaseConnection(); - verify(method, times(1)).setQueryString(queryString); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - UUID, actualProfiles.getResults().get(0).getUuid()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - HREF, actualProfiles.getResults().get(0).getHref()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - SCHEMA, actualProfiles.getResults().get(0).getSchema()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - UUID2, actualProfiles.getResults().get(1).getUuid()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - HREF2, actualProfiles.getResults().get(1).getHref()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - SCHEMA2, actualProfiles.getResults().get(1).getSchema()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - 2, actualProfiles.getResultCount()); - assertEquals("Wrong URI for SecurityProfile creation REST service", - NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); - assertEquals("Wrong URI for SecurityProfile creation REST service", - NiciraNvpApi.GET_METHOD_TYPE, type); - } - - @Test - public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException { - // Prepare - method = mock(GetMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE); - final NameValuePair[] queryString = new NameValuePair[]{ - new NameValuePair("uuid", UUID), - new NameValuePair("fields","*") - }; - final List queryStringNvps = new ArrayList<>(); - doAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - final NameValuePair[] arguments = (NameValuePair[]) invocation.getArguments()[0]; - queryStringNvps.addAll(Arrays.asList(arguments)); - return null; - }}).when(method).setQueryString(any(NameValuePair[].class)); - - // Execute - final NiciraNvpList actualProfiles = api.findSecurityProfile(UUID); - - // Assert - verify(method, times(1)).releaseConnection(); - assertTrue(queryStringNvps.containsAll(Arrays.asList(queryString))); - assertEquals(queryString.length, queryStringNvps.size()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - UUID, actualProfiles.getResults().get(0).getUuid()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - HREF, actualProfiles.getResults().get(0).getHref()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - SCHEMA, actualProfiles.getResults().get(0).getSchema()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - UUID2, actualProfiles.getResults().get(1).getUuid()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - HREF2, actualProfiles.getResults().get(1).getHref()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - SCHEMA2, actualProfiles.getResults().get(1).getSchema()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - 2, actualProfiles.getResultCount()); - assertEquals("Wrong URI for SecurityProfile creation REST service", - NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); - assertEquals("Wrong HTTP method for SecurityProfile creation REST service", - NiciraNvpApi.GET_METHOD_TYPE, type); - } - - @Test - public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException { - // Prepare - final SecurityProfile inputSecProfile = new SecurityProfile(); - method = mock(PostMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); - when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE); - - // Execute - final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile); - - // Assert - verify(method, times(1)).releaseConnection(); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - UUID, actualSecProfile.getUuid()); - assertEquals("Wrong Uuid in the newly created SecurityProfile", - HREF, actualSecProfile.getHref()); - assertEquals("Wrong Schema in the newly created SecurityProfile", - SCHEMA, actualSecProfile.getSchema()); - assertEquals("Wrong URI for SecurityProfile creation REST service", - NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); - assertEquals("Wrong HTTP method for SecurityProfile creation REST service", - NiciraNvpApi.POST_METHOD_TYPE, type); - } - - @Test - public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException { - // Prepare - final SecurityProfile inputSecProfile = new SecurityProfile(); - method = mock(PutMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - - // Execute - api.updateSecurityProfile(inputSecProfile, UUID); - - // Assert - verify(method, times(1)).releaseConnection(); - assertEquals("Wrong URI for SecurityProfile creation REST service", - UUID_SEC_PROFILE_URI, uri); - assertEquals("Wrong HTTP method for SecurityProfile creation REST service", - NiciraNvpApi.PUT_METHOD_TYPE, type); - } - - @Test - public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException { - // Prepare - method = mock(DeleteMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - - // Execute - api.deleteSecurityProfile(UUID); - - // Assert - verify(method, times(1)).releaseConnection(); - assertEquals("Wrong URI for SecurityProfile deletion REST service", UUID_SEC_PROFILE_URI, uri); - assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", NiciraNvpApi.DELETE_METHOD_TYPE, type); - } - - @Test(expected = JsonParseException.class) - public void testRoutingConfigAdapterNoType() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - gson.fromJson("{}", RoutingConfig.class); - - // Assert: JsonParseException should be thrown - } - - @Test(expected = JsonParseException.class) - public void testRoutingConfigAdapterWrongType() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class); - - // Assert: JsonParseException should be thrown - } - - @Test() - public void testRoutingConfigAdapter() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig = - (SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class); - - // Assert: JsonParseException should be thrown - assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass()); - } - - @Test(expected = JsonParseException.class) - public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - gson.fromJson("{}", NatRule.class); - - // Assert: JsonParseException should be thrown - } - - @Test(expected = JsonParseException.class) - public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - gson.fromJson("{type : \"WrongType\"}", NatRule.class); - - // Assert: JsonParseException should be thrown - } - - @Test() - public void testRoutingConfigAdapterWithSourceNatRule() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - final SourceNatRule sourceNatRule = - (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class); - - // Assert: JsonParseException should be thrown - assertEquals("", SourceNatRule.class, sourceNatRule.getClass()); - } - - @Test() - public void testRoutingConfigAdapterWithDestinationNatRule() throws NiciraNvpApiException, IOException { - // Prepare - final NiciraNvpApi api = new NiciraNvpApi(); - final Gson gson = api.restConnector.getGson(); - - // Execute - final DestinationNatRule destinationNatRule = - (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class); - - // Assert: JsonParseException should be thrown - assertEquals("", DestinationNatRule.class, destinationNatRule.getClass()); - } - -} diff --git a/pom.xml b/pom.xml index f5f4e61a1c3..219402c18d8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,12 +1,23 @@ - + 4.0.0 @@ -32,7 +43,7 @@ jira https://issues.apache.org/jira/browse/CLOUDSTACK - + 3.0.4 @@ -66,7 +77,7 @@ 18.0 18.0 6.2.0-3.1 - 4.3.6 + 4.5 4.4 3.1 5.1.34 @@ -423,15 +434,9 @@ - - junit - junit - ${cs.junit.version} - test - org.hamcrest - hamcrest-library + hamcrest-all ${cs.hamcrest.version} test @@ -440,17 +445,35 @@ mockito-all ${cs.mockito.version} test + + + hamcrest-core + org.hamcrest + + - org.powermock - powermock-module-junit4 - ${cs.powermock.version} + junit + junit + ${cs.junit.version} + test + + + hamcrest-core + org.hamcrest + + - org.powermock - powermock-api-mockito - ${cs.powermock.version} - test + org.powermock + powermock-module-junit4 + ${cs.powermock.version} + + + org.powermock + powermock-api-mockito + ${cs.powermock.version} + test org.springframework @@ -485,13 +508,13 @@ org.apache.maven.plugins maven-checkstyle-plugin - - - cloudstack-checkstyle - none - false - - + + + cloudstack-checkstyle + none + false + + com.mycila @@ -570,9 +593,9 @@ true
LICENSE.header
- XML_STYLE -     DOUBLESLASH_STYLE -     SEMICOLON_STYLE + XML_STYLE + DOUBLESLASH_STYLE + SEMICOLON_STYLE false @@ -627,8 +650,8 @@
- + org.eclipse.m2e lifecycle-mapping @@ -646,7 +669,7 @@ - + @@ -659,7 +682,7 @@ - + @@ -682,12 +705,12 @@ gmaven-plugin [1.3,) - compile - testCompile + compile + testCompile - + @@ -841,7 +864,7 @@ tools/ngui/static/js/lib/* **/.checkstyle scripts/installer/windows/acs_license.rtf - **/*.md + **/*.md @@ -943,9 +966,9 @@
false - - cloud-pmd.xml - + + cloud-pmd.xml + @@ -962,7 +985,7 @@ maven-surefire-plugin 2.18.1 - -Djava.security.egd=file:/dev/./urandom + -Djava.security.egd=file:/dev/./urandom -noverify @@ -986,18 +1009,18 @@ - org.apache.maven.plugins - maven-javadoc-plugin - ${cs.javadoc.version} - - 128m - 1g - + org.apache.maven.plugins + maven-javadoc-plugin + ${cs.javadoc.version} + + 128m + 1g + - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.7 + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.7 org.codehaus.mojo @@ -1072,17 +1095,17 @@ org.apache.maven.plugins maven-checkstyle-plugin - - - cloudstack-checkstyle - none - true - - + + + cloudstack-checkstyle + none + true + +
- + enablefindbugs @@ -1090,17 +1113,17 @@ org.codehaus.mojo findbugs-maven-plugin - - - cloudstack-findbugs - process-classes - true - - + + + cloudstack-findbugs + process-classes + true + + - + buildw diff --git a/test/integration/smoke/test_nicira_controller.py b/test/integration/smoke/test_nicira_controller.py new file mode 100644 index 00000000000..229612d451d --- /dev/null +++ b/test/integration/smoke/test_nicira_controller.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import requests +from marvin.cloudstackTestCase import cloudstackTestCase +from marvin.lib.utils import cleanup_resources +from marvin.lib.base import ( + PhysicalNetwork, + NetworkOffering, + NiciraNvp, + ServiceOffering, + Network, + VirtualMachine +) +from marvin.lib.common import (get_domain, get_zone, get_template) +from nose.plugins.attrib import attr +from marvin.codes import (FAILED, PASS) +import time + +class TestNiciraContoller(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + test_case = super(TestNiciraContoller, cls) + + test_client = test_case.getClsTestClient() + cls.config = test_case.getClsConfig() + cls.api_client = test_client.getApiClient() + + cls.physical_networks = cls.config.zones[0].physical_networks + cls.nicira_hosts = cls.config.niciraNvp.hosts + + cls.physical_network_id = cls.get_nicira_enabled_physical_network_id(cls.physical_networks) + + cls.network_offerring_services = { + 'name': 'NiciraEnabledNetwork', + 'displaytext': 'NiciraEnabledNetwork', + 'guestiptype': 'Isolated', + 'supportedservices': 'SourceNat,Firewall,PortForwarding,Connectivity', + 'traffictype': 'GUEST', + 'availability': 'Optional', + 'serviceProviderList': { + 'SourceNat': 'VirtualRouter', + 'Firewall': 'VirtualRouter', + 'PortForwarding': 'VirtualRouter', + 'Connectivity': 'NiciraNvp' + } + } + + cls.network_offering = NetworkOffering.create(cls.api_client, cls.network_offerring_services) + cls.network_offering.update(cls.api_client, state='Enabled') + + cls.nicira_credentials = { + 'username': 'admin', + 'password': 'admin' + } + + cls.nicira_master_controller = cls.determine_master_controller( + cls.nicira_hosts, + cls.nicira_credentials + ) + + cls.transport_zone_uuid = cls.get_transport_zone_from_controller( + cls.nicira_master_controller, + cls.nicira_credentials + ) + + cls.domain = get_domain(cls.api_client) + cls.zone = get_zone(cls.api_client, test_client.getZoneForTests()) + + template = get_template( + cls.api_client, + cls.zone.id + ) + if template == FAILED: + raise Exception("get_template() failed to return template with description %s" % cls.services['ostype']) + + cls.vm_services = { + 'mode': cls.zone.networktype, + 'small': { + 'zoneid': cls.zone.id, + 'template': template.id, + 'displayname': 'testserver', + 'username': cls.config.zones[0].pods[0].clusters[0].hosts[0].username, + 'password': cls.config.zones[0].pods[0].clusters[0].hosts[0].password, + 'ssh_port': 22, + 'hypervisor': cls.config.zones[0].pods[0].clusters[0].hypervisor, + 'privateport': 22, + 'publicport': 22, + 'protocol': 'TCP', + }, + 'service_offerings': { + 'tiny': { + 'name': 'Tiny Instance', + 'displaytext': 'Tiny Instance', + 'cpunumber': 1, + 'cpuspeed': 100, + 'memory': 64, + } + } + } + + if cls.zone.localstorageenabled == True: + cls.vm_services['service_offerings']['tiny']['storagetype'] = 'local' + + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.vm_services['service_offerings']['tiny'] + ) + + cls.cleanup = [ + cls.network_offering, + cls.service_offering + ] + + + @classmethod + def tearDownClass(cls): + try: + cleanup_resources(cls.api_client, reversed(cls.cleanup)) + except Exception as e: + raise Exception("Warning: Exception during class cleanup : %s" % e) + + def setUp(self): + self.test_cleanup = [] + + def tearDown(self): + try: + cleanup_resources(self.api_client, reversed(self.test_cleanup)) + except Exception as e: + raise Exception("Warning: Exception during test cleanup : %s" % e) + + + @classmethod + def determine_master_controller(cls, hosts, credentials): + for host in hosts: + r1 = requests.post("https://%s/ws.v1/login" % host, credentials, verify=False) + r2 = requests.get("https://%s/ws.v1/control-cluster/status" % host, verify=False, cookies=r1.cookies) + status_code = r2.status_code + if status_code == 401: + continue + elif status_code == 200: + return host + raise Exception("None of the supplied hosts (%s) is a Nicira controller" % hosts) + + + @classmethod + def get_transport_zone_from_controller(cls, controller_host, credentials): + r1 = requests.post("https://%s/ws.v1/login" % controller_host, credentials, verify=False) + r2 = requests.get("https://%s/ws.v1/transport-zone" % controller_host, verify=False, cookies=r1.cookies) + status_code = r2.status_code + if status_code == 200: + list_transport_zone_response = r2.json() + result_count = list_transport_zone_response['result_count'] + if result_count == 0: + raise Exception('Nicira controller did not return any Transport Zones') + elif result_count > 1: + self.debug("Nicira controller returned %s Transport Zones, picking first one" % resultCount) + transport_zone_api_url = list_transport_zone_response['results'][0]['_href'] + r3 = requests.get( + "https://%s%s" % (controller_host, transport_zone_api_url), + verify=False, + cookies=r1.cookies + ) + return r3.json()['uuid'] + else: + raise Exception("Unexpected response from Nicira controller. Status code = %s, content = %s" % status_code) + + + @classmethod + def get_nicira_enabled_physical_network_id(cls, physical_networks): + nicira_physical_network_name = None + for physical_network in physical_networks: + for provider in physical_network.providers: + if provider.name == 'NiciraNvp': + nicira_physical_network_name = physical_network.name + if nicira_physical_network_name is None: + raise Exception('Did not find a Nicira enabled physical network in configuration') + return PhysicalNetwork.list(cls.api_client, name=nicira_physical_network_name)[0].id + + + def determine_slave_conroller(self, hosts, master_controller): + slaves = [ s for s in hosts if s != master_controller ] + if len(slaves) > 0: + return slaves[0] + else: + raise Exception("None of the supplied hosts (%s) is a Nicira slave" % hosts) + + @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") + def test_01_nicira_controller(self): + nicira_device = NiciraNvp.add( + self.api_client, + None, + self.physical_network_id, + hostname=self.nicira_master_controller, + username=self.nicira_credentials['username'], + password=self.nicira_credentials['password'], + transportzoneuuid=self.transport_zone_uuid) + self.test_cleanup.append(nicira_device) + + network_services = { + 'name' : 'nicira_enabled_network', + 'displaytext' : 'nicira_enabled_network', + 'zoneid' : self.zone.id, + 'networkoffering' : self.network_offering.id + } + network = Network.create( + self.api_client, + network_services, + accountid='admin', + domainid=self.domain.id, + ) + self.test_cleanup.append(network) + + virtual_machine = VirtualMachine.create( + self.api_client, + self.vm_services['small'], + accountid='admin', + domainid=self.domain.id, + serviceofferingid=self.service_offering.id, + networkids=[network.id], + mode=self.vm_services['mode'] + ) + self.test_cleanup.append(virtual_machine) + + list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) + self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) + + self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') + self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') + + vm_response = list_vm_response[0] + self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') + self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') + + @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") + def test_02_nicira_controller_redirect(self): + """ + Nicira clusters will redirect clients (in this case ACS) to the master node. + This test assumes that a Nicira cluster is present and configured properly, and + that it has at least two controller nodes. The test will check that ASC follows + redirects by: + - adding a Nicira Nvp device that points to one of the cluster's slave controllers, + - create a VM in a Nicira backed network + If all is well, no matter what controller is specified (slaves or master), the vm (and respective router VM) + should be created without issues. + """ + nicira_slave = self.determine_slave_conroller(self.nicira_hosts, self.nicira_master_controller) + self.debug("Nicira slave controller is: %s " % nicira_slave) + + nicira_device = NiciraNvp.add( + self.api_client, + None, + self.physical_network_id, + hostname=nicira_slave, + username=self.nicira_credentials['username'], + password=self.nicira_credentials['password'], + transportzoneuuid=self.transport_zone_uuid) + self.test_cleanup.append(nicira_device) + + network_services = { + 'name' : 'nicira_enabled_network', + 'displaytext' : 'nicira_enabled_network', + 'zoneid' : self.zone.id, + 'networkoffering' : self.network_offering.id + } + network = Network.create( + self.api_client, + network_services, + accountid='admin', + domainid=self.domain.id, + ) + self.test_cleanup.append(network) + + virtual_machine = VirtualMachine.create( + self.api_client, + self.vm_services['small'], + accountid='admin', + domainid=self.domain.id, + serviceofferingid=self.service_offering.id, + networkids=[network.id], + mode=self.vm_services['mode'] + ) + self.test_cleanup.append(virtual_machine) + + list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) + self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) + + self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') + self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') + + vm_response = list_vm_response[0] + self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') + self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') + diff --git a/tools/marvin/marvin/cloudstackTestCase.py b/tools/marvin/marvin/cloudstackTestCase.py index 5cb4a109286..692e817245a 100644 --- a/tools/marvin/marvin/cloudstackTestCase.py +++ b/tools/marvin/marvin/cloudstackTestCase.py @@ -52,3 +52,7 @@ class cloudstackTestCase(unittest.case.TestCase): @classmethod def getClsTestClient(cls): return cls.clstestclient + + @classmethod + def getClsConfig(cls): + return cls.config diff --git a/tools/marvin/marvin/deployDataCenter.py b/tools/marvin/marvin/deployDataCenter.py index 4fcd6967f62..3dd56672dde 100644 --- a/tools/marvin/marvin/deployDataCenter.py +++ b/tools/marvin/marvin/deployDataCenter.py @@ -534,7 +534,7 @@ class DeployDataCenters(object): netprov.physicalnetworkid = phynetwrk.id result = self.__apiClient.addNetworkServiceProvider(netprov) self.enableProvider(result.id) - elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp']: + elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp', 'NiciraNvp']: netprov = addNetworkServiceProvider.\ addNetworkServiceProviderCmd() netprov.name = provider.name @@ -548,55 +548,67 @@ class DeployDataCenters(object): self.__addToCleanUp( "NetworkServiceProvider", result.id) - for device in provider.devices: - if provider.name == 'Netscaler': - dev = addNetscalerLoadBalancer.\ - addNetscalerLoadBalancerCmd() - dev.username = device.username - dev.password = device.password - dev.networkdevicetype = device.networkdevicetype - dev.url = configGenerator.getDeviceUrl(device) - dev.physicalnetworkid = phynetwrk.id - ret = self.__apiClient.addNetscalerLoadBalancer( - dev) - if ret.id: + if provider.devices is not None: + for device in provider.devices: + if provider.name == 'Netscaler': + dev = addNetscalerLoadBalancer.\ + addNetscalerLoadBalancerCmd() + dev.username = device.username + dev.password = device.password + dev.networkdevicetype = device.networkdevicetype + dev.url = configGenerator.getDeviceUrl(device) + dev.physicalnetworkid = phynetwrk.id + ret = self.__apiClient.addNetscalerLoadBalancer( + dev) + if ret.id: + self.__tcRunLogger.\ + debug("==== AddNetScalerLB " + "Successful=====") + self.__addToCleanUp( + "NetscalerLoadBalancer", + ret.id) + elif provider.name == 'JuniperSRX': + dev = addSrxFirewall.addSrxFirewallCmd() + dev.username = device.username + dev.password = device.password + dev.networkdevicetype = device.networkdevicetype + dev.url = configGenerator.getDeviceUrl(device) + dev.physicalnetworkid = phynetwrk.id + ret = self.__apiClient.addSrxFirewall(dev) + if ret.id: + self.__tcRunLogger.\ + debug("==== AddSrx " + "Successful=====") + self.__addToCleanUp("SrxFirewall", ret.id) + elif provider.name == 'F5BigIp': + dev = addF5LoadBalancer.addF5LoadBalancerCmd() + dev.username = device.username + dev.password = device.password + dev.networkdevicetype = device.networkdevicetype + dev.url = configGenerator.getDeviceUrl(device) + dev.physicalnetworkid = phynetwrk.id + ret = self.__apiClient.addF5LoadBalancer(dev) + if ret.id: + self.__tcRunLogger.\ + debug("==== AddF5 " + "Successful=====") + self.__addToCleanUp("F5LoadBalancer", ret.id) + elif provider.name == 'NiciraNvp': + cmd = addNiciraNvpDevice.addNiciraNvpDeviceCmd() + cmd.hostname = device.hostname + cmd.username = device.username + cmd.password = device.password + cmd.transportzoneuuid = device.transportzoneuuid + cmd.physicalnetworkid = phynetwrk.id + ret = self.__apiClient.addNiciraNvpDevice(cmd) self.__tcRunLogger.\ - debug("==== AddNetScalerLB " - "Successful=====") - self.__addToCleanUp( - "NetscalerLoadBalancer", - ret.id) - elif provider.name == 'JuniperSRX': - dev = addSrxFirewall.addSrxFirewallCmd() - dev.username = device.username - dev.password = device.password - dev.networkdevicetype = device.networkdevicetype - dev.url = configGenerator.getDeviceUrl(device) - dev.physicalnetworkid = phynetwrk.id - ret = self.__apiClient.addSrxFirewall(dev) - if ret.id: - self.__tcRunLogger.\ - debug("==== AddSrx " - "Successful=====") - self.__addToCleanUp("SrxFirewall", ret.id) - elif provider.name == 'F5BigIp': - dev = addF5LoadBalancer.addF5LoadBalancerCmd() - dev.username = device.username - dev.password = device.password - dev.networkdevicetype = device.networkdevicetype - dev.url = configGenerator.getDeviceUrl(device) - dev.physicalnetworkid = phynetwrk.id - ret = self.__apiClient.addF5LoadBalancer(dev) - if ret.id: - self.__tcRunLogger.\ - debug("==== AddF5 " - "Successful=====") - self.__addToCleanUp("F5LoadBalancer", ret.id) - else: - raise InvalidParameterException( - "Device %s doesn't match " - "any know provider " - "type" % device) + debug("==== AddNiciraNvp Successful =====") + self.__addToCleanUp("NiciraNvp", ret.id) + else: + raise InvalidParameterException( + "Device %s doesn't match " + "any know provider " + "type" % device) self.enableProvider(result.id) except Exception as e: print "Exception Occurred: %s" % GetDetailExceptionInfo(e) @@ -1133,7 +1145,7 @@ if __name__ == "__main__": print "\n===Deploy Failed===" tc_run_logger.debug("\n===Deploy Failed==="); exit(1) - + if options.remove and os.path.isfile(options.remove) and options.input: ''' diff --git a/tools/marvin/marvin/lib/base.py b/tools/marvin/marvin/lib/base.py index aca7fd105de..54922c84ed3 100755 --- a/tools/marvin/marvin/lib/base.py +++ b/tools/marvin/marvin/lib/base.py @@ -3834,6 +3834,52 @@ class NetScaler: cmd.listall = True return(apiclient.listNetscalerLoadBalancers(cmd)) +class NiciraNvp: + + def __init__(self, items): + self.__dict__.update(items) + + @classmethod + def add(cls, apiclient, services, physicalnetworkid, + hostname=None, username=None, password=None, transportzoneuuid=None): + cmd = addNiciraNvpDevice.addNiciraNvpDeviceCmd() + cmd.physicalnetworkid = physicalnetworkid + if hostname: + cmd.hostname = hostname + else: + cmd.hostname = services['hostname'] + + if username: + cmd.username = username + else: + cmd.username = services['username'] + + if password: + cmd.password = password + else: + cmd.password = services['password'] + + if transportzoneuuid: + cmd.transportzoneuuid = transportzoneuuid + else: + cmd.transportzoneuuid = services['transportZoneUuid'] + + return NiciraNvp(apiclient.addNiciraNvpDevice(cmd).__dict__) + + def delete(self, apiclient): + cmd = deleteNiciraNvpDevice.deleteNiciraNvpDeviceCmd() + cmd.nvpdeviceid = self.nvpdeviceid + apiclient.deleteNiciraNvpDevice(cmd) + return + + @classmethod + def list(cls, apiclient, **kwargs): + cmd = listNiciraNvpDevices.listNiciraNvpDevicesCmd() + [setattr(cmd, k, v) for k, v in kwargs.items()] + if 'account' in kwargs.keys() and 'domainid' in kwargs.keys(): + cmd.listall = True + return(apiclient.listNiciraNvpDevices(cmd)) + class NetworkServiceProvider: """Manage network serivce providers for CloudStack""" diff --git a/utils/pom.xml b/utils/pom.xml index 937dc08f7e0..d01f6ffa125 100755 --- a/utils/pom.xml +++ b/utils/pom.xml @@ -18,7 +18,8 @@ under the License. --> - + 4.0.0 cloud-utils Apache CloudStack Utils @@ -96,8 +97,8 @@ ejb-api - com.googlecode.java-ipv6 - java-ipv6 + com.googlecode.java-ipv6 + java-ipv6 commons-configuration @@ -115,10 +116,10 @@ test - commons-io - commons-io - provided - ${cs.commons-io.version} + commons-io + commons-io + provided + ${cs.commons-io.version} org.reflections @@ -154,9 +155,9 @@ ${cs.opensaml.version} - commons-net - commons-net - 3.3 + commons-net + commons-net + 3.3 com.google.code.gson @@ -169,6 +170,20 @@ + src/main/java + src/test/java + target/classes + target/test-classes + + + src/main/resources + + + + + src/test/resources + + org.apache.maven.plugins @@ -191,15 +206,9 @@ com/cloud/utils/testcase/NioTest.java - + - - - certs - - - integration @@ -221,5 +230,4 @@ - diff --git a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java b/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java deleted file mode 100644 index b102dc44a2c..00000000000 --- a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java +++ /dev/null @@ -1,84 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.utils.log; - -import java.io.PrintWriter; -import java.util.ArrayList; - -import org.apache.log4j.spi.ThrowableRenderer; - -/** - * This renderer removes all the Cglib generated methods from the call - * - * Unfortunately, I had to copy out the EnhancedThrowableRenderer from - * the apach libraries because EnhancedThrowableRenderer is a final class. - * simply override doRender. Not sure what the developers are thinking there - * making it final. - * - * - * into log4j.xml. - * - */ -public class CglibThrowableRenderer implements ThrowableRenderer { - /** - * Construct new instance. - */ - public CglibThrowableRenderer() { - super(); - } - - @Override - public String[] doRender(final Throwable th) { - try { - ArrayList lines = new ArrayList(); - Throwable throwable = th; - lines.add(throwable.toString()); - int start = 0; - do { - StackTraceElement[] elements = throwable.getStackTrace(); - for (int i = 0; i < elements.length - start; i++) { - StackTraceElement element = elements[i]; - String filename = element.getFileName(); - String method = element.getMethodName(); - if ((filename != null && filename.equals("")) || (method != null && method.equals("invokeSuper"))) { - continue; - } - lines.add("\tat " + element.toString()); - } - if (start != 0) { - lines.add("\t... " + start + " more"); - } - throwable = throwable.getCause(); - if (throwable != null) { - lines.add("Caused by: " + throwable.toString()); - start = elements.length - 1; - } - } while (throwable != null); - return lines.toArray(new String[lines.size()]); - } catch (Exception ex) { - PrintWriter pw = new PrintWriter(System.err); - ex.printStackTrace(pw); - pw = new PrintWriter(System.out); - ex.printStackTrace(pw); - ex.printStackTrace(); - return null; - } - } -} diff --git a/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java deleted file mode 100644 index bf001cd8296..00000000000 --- a/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java +++ /dev/null @@ -1,66 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.utils.rest; - -import java.io.IOException; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethodBase; - -/** - * Base 64 encoded authorization strategy. This implementation as opposed to - * {@link RESTValidationStrategy} doesn't do a login after auth error, but instead - * includes the encoded credentials in each request, instead of a cookie. - */ -public class BasicEncodedRESTValidationStrategy extends RESTValidationStrategy { - - public BasicEncodedRESTValidationStrategy(final String host, final String adminuser, final String adminpass) { - super(); - this.host = host; - user = adminuser; - password = adminpass; - } - - public BasicEncodedRESTValidationStrategy() { - } - - @Override - public void executeMethod(final HttpMethodBase method, final HttpClient client, - final String protocol) - throws CloudstackRESTException, HttpException, IOException { - if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) { - throw new CloudstackRESTException("Hostname/credentials are null or empty"); - } - - final String encodedCredentials = encodeCredentials(); - method.setRequestHeader("Authorization", "Basic " + encodedCredentials); - client.executeMethod(method); - } - - private String encodeCredentials() { - final String authString = user + ":" + password; - final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); - final String authStringEnc = new String(authEncBytes); - return authStringEnc; - } - -} diff --git a/utils/src/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/com/cloud/utils/rest/RESTServiceConnector.java deleted file mode 100644 index 6ededcb9524..00000000000 --- a/utils/src/com/cloud/utils/rest/RESTServiceConnector.java +++ /dev/null @@ -1,395 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.utils.rest; - -import com.google.gson.FieldNamingPolicy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializer; -import com.google.gson.reflect.TypeToken; -import org.apache.cloudstack.utils.security.SSLUtils; -import org.apache.cloudstack.utils.security.SecureSSLSocketFactory; -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.httpclient.params.HttpConnectionParams; -import org.apache.commons.httpclient.protocol.Protocol; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; -import org.apache.log4j.Logger; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * This abstraction encapsulates client side code for REST service communication. It encapsulates - * access in a delegate validation strategy. There may different implementations extending - * {@link RESTValidationStrategy}, and any of them should mention the needed data to work. - * - * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide - * in the constructor a list of classes and a list of deserializers for these classes. These should - * be a correlated so that Nth deserializer is correctly mapped to Nth class. - */ -public class RESTServiceConnector { - private static final String HTTPS = "https"; - protected static final String GET_METHOD_TYPE = "get"; - protected static final String DELETE_METHOD_TYPE = "delete"; - protected static final String PUT_METHOD_TYPE = "put"; - protected static final String POST_METHOD_TYPE = "post"; - private static final String TEXT_HTML_CONTENT_TYPE = "text/html"; - private static final String JSON_CONTENT_TYPE = "application/json"; - private static final String CONTENT_TYPE = "Content-Type"; - private static final int BODY_RESP_MAX_LEN = 1024; - private static final int HTTPS_PORT = 443; - - private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class); - - protected final static String protocol = HTTPS; - - private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); - - protected RESTValidationStrategy validation; - - private final HttpClient client; - - private final Gson gson; - - - /** - * Getter that may be needed only for test purpose - * - * @return - */ - public Gson getGson() { - return gson; - } - - public RESTServiceConnector(final RESTValidationStrategy validationStrategy) { - this(validationStrategy, null, null); - } - - public RESTServiceConnector(final RESTValidationStrategy validationStrategy, final List> 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 = SSLUtils.getSSLContext(); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - ssf = new SecureSSLSocketFactory(sc); - } catch (final KeyManagementException e) { - throw new IOException(e); - } catch (final NoSuchAlgorithmException e) { - throw new IOException(e); - } - } - - @Override - public Socket createSocket(final String host, final int port) throws IOException { - SSLSocket socket = (SSLSocket) ssf.createSocket(host, port); - socket.setEnabledProtocols(SSLUtils.getSupportedProtocols(socket.getEnabledProtocols())); - return socket; - } - - @Override - public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException { - Socket socket = ssf.createSocket(address, port, localAddress, localPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - @Override - public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { - Socket s = ssf.createSocket(socket, host, port, autoClose); - if (s instanceof SSLSocket) { - ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols())); - } - return s; - } - - @Override - public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) - throws IOException, UnknownHostException, ConnectTimeoutException { - final int timeout = params.getConnectionTimeout(); - if (timeout == 0) { - Socket socket = createSocket(host, port, localAddress, localPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } else { - final Socket s = ssf.createSocket(); - if (s instanceof SSLSocket) { - ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols())); - } - s.bind(new InetSocketAddress(localAddress, localPort)); - s.connect(new InetSocketAddress(host, port), timeout); - return s; - } - } - } - -} diff --git a/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java deleted file mode 100644 index 77ac8d08e49..00000000000 --- a/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java +++ /dev/null @@ -1,165 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.utils.rest; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.log4j.Logger; - -/** - * Basic authentication strategy. This strategy needs user and password for authentication. - * - * A login URL is needed which will be used for login and getting the cookie to be - * used in next requests. If an executeMethod request fails due to authorization it will try - * to login, get the cookie and repeat the attempt to execute the method. - */ -public class RESTValidationStrategy { - - private static final Logger s_logger = Logger.getLogger(RESTValidationStrategy.class); - - protected String host; - protected String user; - protected String password; - protected String serverVersion; - protected String loginUrl; - - public RESTValidationStrategy(final String host, final String user, final String password, - final String serverVersion, final String loginUrl) { - super(); - this.host = host; - this.user = user; - this.password = password; - this.serverVersion = serverVersion; - this.loginUrl = loginUrl; - } - - public RESTValidationStrategy(final String loginUrl) { - this.loginUrl = loginUrl; - } - - public RESTValidationStrategy() { - } - - public String getUser() { - return user; - } - - public void setUser(final String user) { - this.user = user; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } - - public String getLoginUrl() { - return loginUrl; - } - - public void setLoginUrl(final String loginUrl) { - this.loginUrl = loginUrl; - } - - public String getHost() { - return host; - } - - public void setHost(final String host) { - this.host = host; - } - - public void executeMethod(final HttpMethodBase method, final HttpClient client, - final String protocol) - throws CloudstackRESTException, HttpException, IOException { - if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) { - throw new CloudstackRESTException("Hostname/credentials are null or empty"); - } - - client.executeMethod(method); - if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - method.releaseConnection(); - // login and try again - login(protocol, client); - client.executeMethod(method); - } - } - - /** - * Logs against the REST server. The cookie is stored in the _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/src/com/cloud/maint/Version.java b/utils/src/main/java/com/cloud/maint/Version.java similarity index 100% rename from utils/src/com/cloud/maint/Version.java rename to utils/src/main/java/com/cloud/maint/Version.java diff --git a/utils/src/com/cloud/utils/ActionDelegate.java b/utils/src/main/java/com/cloud/utils/ActionDelegate.java similarity index 100% rename from utils/src/com/cloud/utils/ActionDelegate.java rename to utils/src/main/java/com/cloud/utils/ActionDelegate.java diff --git a/utils/src/com/cloud/utils/AutoCloseableUtil.java b/utils/src/main/java/com/cloud/utils/AutoCloseableUtil.java similarity index 100% rename from utils/src/com/cloud/utils/AutoCloseableUtil.java rename to utils/src/main/java/com/cloud/utils/AutoCloseableUtil.java diff --git a/utils/src/com/cloud/utils/CloudResourceBundle.java b/utils/src/main/java/com/cloud/utils/CloudResourceBundle.java similarity index 100% rename from utils/src/com/cloud/utils/CloudResourceBundle.java rename to utils/src/main/java/com/cloud/utils/CloudResourceBundle.java diff --git a/utils/src/com/cloud/utils/ConstantTimeComparator.java b/utils/src/main/java/com/cloud/utils/ConstantTimeComparator.java similarity index 100% rename from utils/src/com/cloud/utils/ConstantTimeComparator.java rename to utils/src/main/java/com/cloud/utils/ConstantTimeComparator.java diff --git a/utils/src/com/cloud/utils/DateUtil.java b/utils/src/main/java/com/cloud/utils/DateUtil.java similarity index 100% rename from utils/src/com/cloud/utils/DateUtil.java rename to utils/src/main/java/com/cloud/utils/DateUtil.java diff --git a/utils/src/com/cloud/utils/EncryptionUtil.java b/utils/src/main/java/com/cloud/utils/EncryptionUtil.java similarity index 100% rename from utils/src/com/cloud/utils/EncryptionUtil.java rename to utils/src/main/java/com/cloud/utils/EncryptionUtil.java diff --git a/utils/src/com/cloud/utils/EnumUtils.java b/utils/src/main/java/com/cloud/utils/EnumUtils.java similarity index 100% rename from utils/src/com/cloud/utils/EnumUtils.java rename to utils/src/main/java/com/cloud/utils/EnumUtils.java diff --git a/utils/src/com/cloud/utils/ExecutionResult.java b/utils/src/main/java/com/cloud/utils/ExecutionResult.java similarity index 100% rename from utils/src/com/cloud/utils/ExecutionResult.java rename to utils/src/main/java/com/cloud/utils/ExecutionResult.java diff --git a/utils/src/com/cloud/utils/FileUtil.java b/utils/src/main/java/com/cloud/utils/FileUtil.java similarity index 100% rename from utils/src/com/cloud/utils/FileUtil.java rename to utils/src/main/java/com/cloud/utils/FileUtil.java diff --git a/utils/src/com/cloud/utils/HttpUtils.java b/utils/src/main/java/com/cloud/utils/HttpUtils.java similarity index 100% rename from utils/src/com/cloud/utils/HttpUtils.java rename to utils/src/main/java/com/cloud/utils/HttpUtils.java diff --git a/utils/src/com/cloud/utils/IteratorUtil.java b/utils/src/main/java/com/cloud/utils/IteratorUtil.java similarity index 100% rename from utils/src/com/cloud/utils/IteratorUtil.java rename to utils/src/main/java/com/cloud/utils/IteratorUtil.java diff --git a/utils/src/com/cloud/utils/Journal.java b/utils/src/main/java/com/cloud/utils/Journal.java similarity index 100% rename from utils/src/com/cloud/utils/Journal.java rename to utils/src/main/java/com/cloud/utils/Journal.java diff --git a/utils/src/com/cloud/utils/LogUtils.java b/utils/src/main/java/com/cloud/utils/LogUtils.java similarity index 100% rename from utils/src/com/cloud/utils/LogUtils.java rename to utils/src/main/java/com/cloud/utils/LogUtils.java diff --git a/utils/src/com/cloud/utils/MethodCapturer.java b/utils/src/main/java/com/cloud/utils/MethodCapturer.java similarity index 100% rename from utils/src/com/cloud/utils/MethodCapturer.java rename to utils/src/main/java/com/cloud/utils/MethodCapturer.java diff --git a/utils/src/com/cloud/utils/NumbersUtil.java b/utils/src/main/java/com/cloud/utils/NumbersUtil.java similarity index 100% rename from utils/src/com/cloud/utils/NumbersUtil.java rename to utils/src/main/java/com/cloud/utils/NumbersUtil.java diff --git a/utils/src/com/cloud/utils/Pair.java b/utils/src/main/java/com/cloud/utils/Pair.java similarity index 100% rename from utils/src/com/cloud/utils/Pair.java rename to utils/src/main/java/com/cloud/utils/Pair.java diff --git a/utils/src/com/cloud/utils/PasswordGenerator.java b/utils/src/main/java/com/cloud/utils/PasswordGenerator.java similarity index 100% rename from utils/src/com/cloud/utils/PasswordGenerator.java rename to utils/src/main/java/com/cloud/utils/PasswordGenerator.java diff --git a/utils/src/com/cloud/utils/Predicate.java b/utils/src/main/java/com/cloud/utils/Predicate.java similarity index 100% rename from utils/src/com/cloud/utils/Predicate.java rename to utils/src/main/java/com/cloud/utils/Predicate.java diff --git a/utils/src/com/cloud/utils/ProcessUtil.java b/utils/src/main/java/com/cloud/utils/ProcessUtil.java similarity index 100% rename from utils/src/com/cloud/utils/ProcessUtil.java rename to utils/src/main/java/com/cloud/utils/ProcessUtil.java diff --git a/utils/src/com/cloud/utils/Profiler.java b/utils/src/main/java/com/cloud/utils/Profiler.java similarity index 100% rename from utils/src/com/cloud/utils/Profiler.java rename to utils/src/main/java/com/cloud/utils/Profiler.java diff --git a/utils/src/com/cloud/utils/PropertiesUtil.java b/utils/src/main/java/com/cloud/utils/PropertiesUtil.java similarity index 100% rename from utils/src/com/cloud/utils/PropertiesUtil.java rename to utils/src/main/java/com/cloud/utils/PropertiesUtil.java diff --git a/utils/src/com/cloud/utils/ReflectUtil.java b/utils/src/main/java/com/cloud/utils/ReflectUtil.java similarity index 100% rename from utils/src/com/cloud/utils/ReflectUtil.java rename to utils/src/main/java/com/cloud/utils/ReflectUtil.java diff --git a/utils/src/com/cloud/utils/ReflectionUse.java b/utils/src/main/java/com/cloud/utils/ReflectionUse.java similarity index 100% rename from utils/src/com/cloud/utils/ReflectionUse.java rename to utils/src/main/java/com/cloud/utils/ReflectionUse.java diff --git a/utils/src/com/cloud/utils/S3Utils.java b/utils/src/main/java/com/cloud/utils/S3Utils.java similarity index 100% rename from utils/src/com/cloud/utils/S3Utils.java rename to utils/src/main/java/com/cloud/utils/S3Utils.java diff --git a/utils/src/com/cloud/utils/SerialVersionUID.java b/utils/src/main/java/com/cloud/utils/SerialVersionUID.java similarity index 100% rename from utils/src/com/cloud/utils/SerialVersionUID.java rename to utils/src/main/java/com/cloud/utils/SerialVersionUID.java diff --git a/utils/src/com/cloud/utils/StringUtils.java b/utils/src/main/java/com/cloud/utils/StringUtils.java similarity index 100% rename from utils/src/com/cloud/utils/StringUtils.java rename to utils/src/main/java/com/cloud/utils/StringUtils.java diff --git a/utils/src/com/cloud/utils/SwiftUtil.java b/utils/src/main/java/com/cloud/utils/SwiftUtil.java similarity index 100% rename from utils/src/com/cloud/utils/SwiftUtil.java rename to utils/src/main/java/com/cloud/utils/SwiftUtil.java diff --git a/utils/src/com/cloud/utils/Ternary.java b/utils/src/main/java/com/cloud/utils/Ternary.java similarity index 100% rename from utils/src/com/cloud/utils/Ternary.java rename to utils/src/main/java/com/cloud/utils/Ternary.java diff --git a/utils/src/com/cloud/utils/UriUtils.java b/utils/src/main/java/com/cloud/utils/UriUtils.java similarity index 100% rename from utils/src/com/cloud/utils/UriUtils.java rename to utils/src/main/java/com/cloud/utils/UriUtils.java diff --git a/utils/src/com/cloud/utils/UsernamePasswordValidator.java b/utils/src/main/java/com/cloud/utils/UsernamePasswordValidator.java similarity index 100% rename from utils/src/com/cloud/utils/UsernamePasswordValidator.java rename to utils/src/main/java/com/cloud/utils/UsernamePasswordValidator.java diff --git a/utils/src/com/cloud/utils/UuidUtils.java b/utils/src/main/java/com/cloud/utils/UuidUtils.java similarity index 100% rename from utils/src/com/cloud/utils/UuidUtils.java rename to utils/src/main/java/com/cloud/utils/UuidUtils.java diff --git a/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java b/utils/src/main/java/com/cloud/utils/backoff/BackoffAlgorithm.java similarity index 100% rename from utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java rename to utils/src/main/java/com/cloud/utils/backoff/BackoffAlgorithm.java diff --git a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java b/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java similarity index 100% rename from utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java rename to utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java diff --git a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java b/utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java similarity index 100% rename from utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java rename to utils/src/main/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmOkResponse.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPolicyMapResponse.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmPortProfileResponse.java diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java b/utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java similarity index 100% rename from utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java rename to utils/src/main/java/com/cloud/utils/cisco/n1kv/vsm/VsmResponse.java diff --git a/utils/src/com/cloud/utils/component/Adapter.java b/utils/src/main/java/com/cloud/utils/component/Adapter.java similarity index 100% rename from utils/src/com/cloud/utils/component/Adapter.java rename to utils/src/main/java/com/cloud/utils/component/Adapter.java diff --git a/utils/src/com/cloud/utils/component/AdapterBase.java b/utils/src/main/java/com/cloud/utils/component/AdapterBase.java similarity index 100% rename from utils/src/com/cloud/utils/component/AdapterBase.java rename to utils/src/main/java/com/cloud/utils/component/AdapterBase.java diff --git a/utils/src/com/cloud/utils/component/AdapterList.java b/utils/src/main/java/com/cloud/utils/component/AdapterList.java similarity index 100% rename from utils/src/com/cloud/utils/component/AdapterList.java rename to utils/src/main/java/com/cloud/utils/component/AdapterList.java diff --git a/utils/src/com/cloud/utils/component/ComponentContext.java b/utils/src/main/java/com/cloud/utils/component/ComponentContext.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentContext.java rename to utils/src/main/java/com/cloud/utils/component/ComponentContext.java diff --git a/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java b/utils/src/main/java/com/cloud/utils/component/ComponentInstantiationPostProcessor.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java rename to utils/src/main/java/com/cloud/utils/component/ComponentInstantiationPostProcessor.java diff --git a/utils/src/com/cloud/utils/component/ComponentLifecycle.java b/utils/src/main/java/com/cloud/utils/component/ComponentLifecycle.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentLifecycle.java rename to utils/src/main/java/com/cloud/utils/component/ComponentLifecycle.java diff --git a/utils/src/com/cloud/utils/component/ComponentLifecycleBase.java b/utils/src/main/java/com/cloud/utils/component/ComponentLifecycleBase.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentLifecycleBase.java rename to utils/src/main/java/com/cloud/utils/component/ComponentLifecycleBase.java diff --git a/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java b/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptable.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java rename to utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptable.java diff --git a/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java b/utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptor.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java rename to utils/src/main/java/com/cloud/utils/component/ComponentMethodInterceptor.java diff --git a/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java b/utils/src/main/java/com/cloud/utils/component/ComponentNamingPolicy.java similarity index 100% rename from utils/src/com/cloud/utils/component/ComponentNamingPolicy.java rename to utils/src/main/java/com/cloud/utils/component/ComponentNamingPolicy.java diff --git a/utils/src/com/cloud/utils/component/Manager.java b/utils/src/main/java/com/cloud/utils/component/Manager.java similarity index 100% rename from utils/src/com/cloud/utils/component/Manager.java rename to utils/src/main/java/com/cloud/utils/component/Manager.java diff --git a/utils/src/com/cloud/utils/component/ManagerBase.java b/utils/src/main/java/com/cloud/utils/component/ManagerBase.java similarity index 100% rename from utils/src/com/cloud/utils/component/ManagerBase.java rename to utils/src/main/java/com/cloud/utils/component/ManagerBase.java diff --git a/utils/src/com/cloud/utils/component/Named.java b/utils/src/main/java/com/cloud/utils/component/Named.java similarity index 100% rename from utils/src/com/cloud/utils/component/Named.java rename to utils/src/main/java/com/cloud/utils/component/Named.java diff --git a/utils/src/com/cloud/utils/component/PluggableService.java b/utils/src/main/java/com/cloud/utils/component/PluggableService.java similarity index 100% rename from utils/src/com/cloud/utils/component/PluggableService.java rename to utils/src/main/java/com/cloud/utils/component/PluggableService.java diff --git a/utils/src/com/cloud/utils/component/Registry.java b/utils/src/main/java/com/cloud/utils/component/Registry.java similarity index 100% rename from utils/src/com/cloud/utils/component/Registry.java rename to utils/src/main/java/com/cloud/utils/component/Registry.java diff --git a/utils/src/com/cloud/utils/component/SystemIntegrityChecker.java b/utils/src/main/java/com/cloud/utils/component/SystemIntegrityChecker.java similarity index 100% rename from utils/src/com/cloud/utils/component/SystemIntegrityChecker.java rename to utils/src/main/java/com/cloud/utils/component/SystemIntegrityChecker.java diff --git a/utils/src/com/cloud/utils/concurrency/NamedThreadFactory.java b/utils/src/main/java/com/cloud/utils/concurrency/NamedThreadFactory.java similarity index 100% rename from utils/src/com/cloud/utils/concurrency/NamedThreadFactory.java rename to utils/src/main/java/com/cloud/utils/concurrency/NamedThreadFactory.java diff --git a/utils/src/com/cloud/utils/concurrency/Scheduler.java b/utils/src/main/java/com/cloud/utils/concurrency/Scheduler.java similarity index 100% rename from utils/src/com/cloud/utils/concurrency/Scheduler.java rename to utils/src/main/java/com/cloud/utils/concurrency/Scheduler.java diff --git a/utils/src/com/cloud/utils/concurrency/SynchronizationEvent.java b/utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java similarity index 100% rename from utils/src/com/cloud/utils/concurrency/SynchronizationEvent.java rename to utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java diff --git a/utils/src/com/cloud/utils/concurrency/TestClock.java b/utils/src/main/java/com/cloud/utils/concurrency/TestClock.java similarity index 100% rename from utils/src/com/cloud/utils/concurrency/TestClock.java rename to utils/src/main/java/com/cloud/utils/concurrency/TestClock.java diff --git a/utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java b/utils/src/main/java/com/cloud/utils/crypt/DBEncryptionUtil.java similarity index 100% rename from utils/src/com/cloud/utils/crypt/DBEncryptionUtil.java rename to utils/src/main/java/com/cloud/utils/crypt/DBEncryptionUtil.java diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java b/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java similarity index 100% rename from utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java rename to utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java b/utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeySender.java similarity index 100% rename from utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java rename to utils/src/main/java/com/cloud/utils/crypt/EncryptionSecretKeySender.java diff --git a/utils/src/com/cloud/utils/crypt/RSAHelper.java b/utils/src/main/java/com/cloud/utils/crypt/RSAHelper.java similarity index 100% rename from utils/src/com/cloud/utils/crypt/RSAHelper.java rename to utils/src/main/java/com/cloud/utils/crypt/RSAHelper.java diff --git a/utils/src/com/cloud/utils/db/DbProperties.java b/utils/src/main/java/com/cloud/utils/db/DbProperties.java similarity index 100% rename from utils/src/com/cloud/utils/db/DbProperties.java rename to utils/src/main/java/com/cloud/utils/db/DbProperties.java diff --git a/utils/src/com/cloud/utils/db/EntityManager.java b/utils/src/main/java/com/cloud/utils/db/EntityManager.java similarity index 100% rename from utils/src/com/cloud/utils/db/EntityManager.java rename to utils/src/main/java/com/cloud/utils/db/EntityManager.java diff --git a/utils/src/com/cloud/utils/db/UUIDManager.java b/utils/src/main/java/com/cloud/utils/db/UUIDManager.java similarity index 100% rename from utils/src/com/cloud/utils/db/UUIDManager.java rename to utils/src/main/java/com/cloud/utils/db/UUIDManager.java diff --git a/utils/src/com/cloud/utils/encoding/URLEncoder.java b/utils/src/main/java/com/cloud/utils/encoding/URLEncoder.java similarity index 100% rename from utils/src/com/cloud/utils/encoding/URLEncoder.java rename to utils/src/main/java/com/cloud/utils/encoding/URLEncoder.java diff --git a/utils/src/com/cloud/utils/events/EventArgs.java b/utils/src/main/java/com/cloud/utils/events/EventArgs.java similarity index 100% rename from utils/src/com/cloud/utils/events/EventArgs.java rename to utils/src/main/java/com/cloud/utils/events/EventArgs.java diff --git a/utils/src/com/cloud/utils/events/SubscriptionMgr.java b/utils/src/main/java/com/cloud/utils/events/SubscriptionMgr.java similarity index 100% rename from utils/src/com/cloud/utils/events/SubscriptionMgr.java rename to utils/src/main/java/com/cloud/utils/events/SubscriptionMgr.java diff --git a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java b/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java similarity index 100% rename from utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java rename to utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java diff --git a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java b/utils/src/main/java/com/cloud/utils/exception/CloudRuntimeException.java similarity index 100% rename from utils/src/com/cloud/utils/exception/CloudRuntimeException.java rename to utils/src/main/java/com/cloud/utils/exception/CloudRuntimeException.java diff --git a/utils/src/com/cloud/utils/exception/ErrorContext.java b/utils/src/main/java/com/cloud/utils/exception/ErrorContext.java similarity index 100% rename from utils/src/com/cloud/utils/exception/ErrorContext.java rename to utils/src/main/java/com/cloud/utils/exception/ErrorContext.java diff --git a/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java b/utils/src/main/java/com/cloud/utils/exception/ExceptionProxyObject.java similarity index 100% rename from utils/src/com/cloud/utils/exception/ExceptionProxyObject.java rename to utils/src/main/java/com/cloud/utils/exception/ExceptionProxyObject.java diff --git a/utils/src/com/cloud/utils/exception/ExceptionUtil.java b/utils/src/main/java/com/cloud/utils/exception/ExceptionUtil.java similarity index 100% rename from utils/src/com/cloud/utils/exception/ExceptionUtil.java rename to utils/src/main/java/com/cloud/utils/exception/ExceptionUtil.java diff --git a/utils/src/com/cloud/utils/exception/ExecutionException.java b/utils/src/main/java/com/cloud/utils/exception/ExecutionException.java similarity index 100% rename from utils/src/com/cloud/utils/exception/ExecutionException.java rename to utils/src/main/java/com/cloud/utils/exception/ExecutionException.java diff --git a/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java b/utils/src/main/java/com/cloud/utils/exception/HypervisorVersionChangedException.java similarity index 100% rename from utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java rename to utils/src/main/java/com/cloud/utils/exception/HypervisorVersionChangedException.java diff --git a/utils/src/com/cloud/utils/fsm/ChangeEvent.java b/utils/src/main/java/com/cloud/utils/fsm/ChangeEvent.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/ChangeEvent.java rename to utils/src/main/java/com/cloud/utils/fsm/ChangeEvent.java diff --git a/utils/src/com/cloud/utils/fsm/FiniteState.java b/utils/src/main/java/com/cloud/utils/fsm/FiniteState.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/FiniteState.java rename to utils/src/main/java/com/cloud/utils/fsm/FiniteState.java diff --git a/utils/src/com/cloud/utils/fsm/FiniteState2.java b/utils/src/main/java/com/cloud/utils/fsm/FiniteState2.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/FiniteState2.java rename to utils/src/main/java/com/cloud/utils/fsm/FiniteState2.java diff --git a/utils/src/com/cloud/utils/fsm/FiniteStateObject.java b/utils/src/main/java/com/cloud/utils/fsm/FiniteStateObject.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/FiniteStateObject.java rename to utils/src/main/java/com/cloud/utils/fsm/FiniteStateObject.java diff --git a/utils/src/com/cloud/utils/fsm/NoTransitionException.java b/utils/src/main/java/com/cloud/utils/fsm/NoTransitionException.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/NoTransitionException.java rename to utils/src/main/java/com/cloud/utils/fsm/NoTransitionException.java diff --git a/utils/src/com/cloud/utils/fsm/State.java b/utils/src/main/java/com/cloud/utils/fsm/State.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/State.java rename to utils/src/main/java/com/cloud/utils/fsm/State.java diff --git a/utils/src/com/cloud/utils/fsm/StateDao.java b/utils/src/main/java/com/cloud/utils/fsm/StateDao.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/StateDao.java rename to utils/src/main/java/com/cloud/utils/fsm/StateDao.java diff --git a/utils/src/com/cloud/utils/fsm/StateListener.java b/utils/src/main/java/com/cloud/utils/fsm/StateListener.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/StateListener.java rename to utils/src/main/java/com/cloud/utils/fsm/StateListener.java diff --git a/utils/src/com/cloud/utils/fsm/StateMachine.java b/utils/src/main/java/com/cloud/utils/fsm/StateMachine.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/StateMachine.java rename to utils/src/main/java/com/cloud/utils/fsm/StateMachine.java diff --git a/utils/src/com/cloud/utils/fsm/StateMachine2.java b/utils/src/main/java/com/cloud/utils/fsm/StateMachine2.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/StateMachine2.java rename to utils/src/main/java/com/cloud/utils/fsm/StateMachine2.java diff --git a/utils/src/com/cloud/utils/fsm/StateObject.java b/utils/src/main/java/com/cloud/utils/fsm/StateObject.java similarity index 100% rename from utils/src/com/cloud/utils/fsm/StateObject.java rename to utils/src/main/java/com/cloud/utils/fsm/StateObject.java diff --git a/utils/src/com/cloud/utils/mgmt/JmxUtil.java b/utils/src/main/java/com/cloud/utils/mgmt/JmxUtil.java similarity index 100% rename from utils/src/com/cloud/utils/mgmt/JmxUtil.java rename to utils/src/main/java/com/cloud/utils/mgmt/JmxUtil.java diff --git a/utils/src/com/cloud/utils/mgmt/ManagementBean.java b/utils/src/main/java/com/cloud/utils/mgmt/ManagementBean.java similarity index 100% rename from utils/src/com/cloud/utils/mgmt/ManagementBean.java rename to utils/src/main/java/com/cloud/utils/mgmt/ManagementBean.java diff --git a/utils/src/com/cloud/utils/mgmt/PropertyMapDynamicBean.java b/utils/src/main/java/com/cloud/utils/mgmt/PropertyMapDynamicBean.java similarity index 100% rename from utils/src/com/cloud/utils/mgmt/PropertyMapDynamicBean.java rename to utils/src/main/java/com/cloud/utils/mgmt/PropertyMapDynamicBean.java diff --git a/utils/src/com/cloud/utils/net/Ip.java b/utils/src/main/java/com/cloud/utils/net/Ip.java similarity index 100% rename from utils/src/com/cloud/utils/net/Ip.java rename to utils/src/main/java/com/cloud/utils/net/Ip.java diff --git a/utils/src/com/cloud/utils/net/Ip4Address.java b/utils/src/main/java/com/cloud/utils/net/Ip4Address.java similarity index 100% rename from utils/src/com/cloud/utils/net/Ip4Address.java rename to utils/src/main/java/com/cloud/utils/net/Ip4Address.java diff --git a/utils/src/com/cloud/utils/net/MacAddress.java b/utils/src/main/java/com/cloud/utils/net/MacAddress.java similarity index 100% rename from utils/src/com/cloud/utils/net/MacAddress.java rename to utils/src/main/java/com/cloud/utils/net/MacAddress.java diff --git a/utils/src/com/cloud/utils/net/NetUtils.java b/utils/src/main/java/com/cloud/utils/net/NetUtils.java similarity index 100% rename from utils/src/com/cloud/utils/net/NetUtils.java rename to utils/src/main/java/com/cloud/utils/net/NetUtils.java diff --git a/utils/src/com/cloud/utils/net/NfsUtils.java b/utils/src/main/java/com/cloud/utils/net/NfsUtils.java similarity index 100% rename from utils/src/com/cloud/utils/net/NfsUtils.java rename to utils/src/main/java/com/cloud/utils/net/NfsUtils.java diff --git a/utils/src/com/cloud/utils/net/UrlUtil.java b/utils/src/main/java/com/cloud/utils/net/UrlUtil.java similarity index 100% rename from utils/src/com/cloud/utils/net/UrlUtil.java rename to utils/src/main/java/com/cloud/utils/net/UrlUtil.java diff --git a/utils/src/com/cloud/utils/nio/HandlerFactory.java b/utils/src/main/java/com/cloud/utils/nio/HandlerFactory.java similarity index 100% rename from utils/src/com/cloud/utils/nio/HandlerFactory.java rename to utils/src/main/java/com/cloud/utils/nio/HandlerFactory.java diff --git a/utils/src/com/cloud/utils/nio/Link.java b/utils/src/main/java/com/cloud/utils/nio/Link.java similarity index 100% rename from utils/src/com/cloud/utils/nio/Link.java rename to utils/src/main/java/com/cloud/utils/nio/Link.java diff --git a/utils/src/com/cloud/utils/nio/NioClient.java b/utils/src/main/java/com/cloud/utils/nio/NioClient.java similarity index 100% rename from utils/src/com/cloud/utils/nio/NioClient.java rename to utils/src/main/java/com/cloud/utils/nio/NioClient.java diff --git a/utils/src/com/cloud/utils/nio/NioConnection.java b/utils/src/main/java/com/cloud/utils/nio/NioConnection.java similarity index 100% rename from utils/src/com/cloud/utils/nio/NioConnection.java rename to utils/src/main/java/com/cloud/utils/nio/NioConnection.java diff --git a/utils/src/com/cloud/utils/nio/NioServer.java b/utils/src/main/java/com/cloud/utils/nio/NioServer.java similarity index 100% rename from utils/src/com/cloud/utils/nio/NioServer.java rename to utils/src/main/java/com/cloud/utils/nio/NioServer.java diff --git a/utils/src/com/cloud/utils/nio/Task.java b/utils/src/main/java/com/cloud/utils/nio/Task.java similarity index 100% rename from utils/src/com/cloud/utils/nio/Task.java rename to utils/src/main/java/com/cloud/utils/nio/Task.java diff --git a/utils/src/com/cloud/utils/nio/TrustAllManager.java b/utils/src/main/java/com/cloud/utils/nio/TrustAllManager.java similarity index 100% rename from utils/src/com/cloud/utils/nio/TrustAllManager.java rename to utils/src/main/java/com/cloud/utils/nio/TrustAllManager.java diff --git a/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java b/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java new file mode 100644 index 00000000000..5c291557519 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/BasicRestClient.java @@ -0,0 +1,118 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import java.io.IOException; +import java.net.URI; + +import org.apache.http.HttpHost; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.log4j.Logger; + +public class BasicRestClient implements RestClient { + + private static final Logger s_logger = Logger.getLogger(BasicRestClient.class); + + private static final String HTTPS = HttpConstants.HTTPS; + private static final int HTTPS_PORT = HttpConstants.HTTPS_PORT; + + private final CloseableHttpClient client; + private final HttpClientContext clientContext; + + private BasicRestClient(final Builder builder) { + client = builder.client; + clientContext = builder.clientContext; + clientContext.setTargetHost(buildHttpHost(builder.host)); + } + + protected BasicRestClient(final CloseableHttpClient client, final HttpClientContext clientContex, final String host) { + this.client = client; + clientContext = clientContex; + clientContext.setTargetHost(buildHttpHost(host)); + } + + private static HttpHost buildHttpHost(final String host) { + return new HttpHost(host, HTTPS_PORT, HTTPS); + } + + @SuppressWarnings("rawtypes") + public static Builder create() { + return new Builder(); + } + + @Override + public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException { + logRequestExecution(request); + try { + return client.execute(clientContext.getTargetHost(), request, clientContext); + } catch (final IOException e) { + throw new CloudstackRESTException("Could not execute request " + request, e); + } + } + + private void logRequestExecution(final HttpUriRequest request) { + final URI uri = request.getURI(); + String query = uri.getQuery(); + query = query != null ? "?" + query : ""; + s_logger.debug("Executig " + request.getMethod() + " request on " + clientContext.getTargetHost() + uri.getPath() + query); + } + + @Override + public void closeResponse(final CloseableHttpResponse response) throws CloudstackRESTException { + try { + s_logger.debug("Closing HTTP connection"); + response.close(); + } catch (final IOException e) { + final StringBuilder sb = new StringBuilder(); + sb.append("Failed to close response object for request.\nResponse: ").append(response); + throw new CloudstackRESTException(sb.toString(), e); + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected static class Builder { + private CloseableHttpClient client; + private HttpClientContext clientContext = HttpClientContext.create(); + private String host; + + public T client(final CloseableHttpClient client) { + this.client = client; + return (T) this; + } + + public T clientContext(final HttpClientContext clientContext) { + this.clientContext = clientContext; + return (T) this; + } + + public T host(final String host) { + this.host = host; + return (T) this; + } + + public BasicRestClient build() { + return new BasicRestClient(this); + } + } + +} diff --git a/utils/src/com/cloud/utils/rest/CloudstackRESTException.java b/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java similarity index 89% rename from utils/src/com/cloud/utils/rest/CloudstackRESTException.java rename to utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java index 5985fa0a524..2078d576775 100644 --- a/utils/src/com/cloud/utils/rest/CloudstackRESTException.java +++ b/utils/src/main/java/com/cloud/utils/rest/CloudstackRESTException.java @@ -19,19 +19,13 @@ package com.cloud.utils.rest; +@SuppressWarnings("serial") public class CloudstackRESTException extends Exception { - public CloudstackRESTException() { - } - public CloudstackRESTException(final String message) { super(message); } - public CloudstackRESTException(final Throwable cause) { - super(cause); - } - public CloudstackRESTException(final String message, final Throwable cause) { super(message, cause); } diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java b/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java new file mode 100644 index 00000000000..1c6f564f818 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/HttpClientHelper.java @@ -0,0 +1,71 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +import javax.net.ssl.SSLContext; + +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.LaxRedirectStrategy; +import org.apache.http.impl.client.StandardHttpRequestRetryHandler; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContexts; + +public class HttpClientHelper { + + private static final String HTTPS = HttpConstants.HTTPS; + + public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { + final Registry socketFactoryRegistry = createSocketFactoryConfigration(); + final BasicCookieStore cookieStore = new BasicCookieStore(); + return HttpClientBuilder.create() + .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)) + .setRedirectStrategy(new LaxRedirectStrategy()) + .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setMaxRedirects(maxRedirects).build()) + .setDefaultCookieStore(cookieStore) + .setRetryHandler(new StandardHttpRequestRetryHandler()) + .build(); + } + + private static Registry createSocketFactoryConfigration() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { + Registry socketFactoryRegistry; + final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build(); + final SSLConnectionSocketFactory cnnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + socketFactoryRegistry = RegistryBuilder. create() + .register(HTTPS, cnnectionSocketFactory) + .build(); + + return socketFactoryRegistry; + } + +} diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java b/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java new file mode 100644 index 00000000000..93502a55557 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/HttpConstants.java @@ -0,0 +1,34 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +public class HttpConstants { + + public static final int HTTPS_PORT = 443; + public static final String HTTPS = "https"; + public static final String GET_METHOD_TYPE = "get"; + public static final String DELETE_METHOD_TYPE = "delete"; + public static final String PUT_METHOD_TYPE = "put"; + public static final String POST_METHOD_TYPE = "post"; + public static final String TEXT_HTML_CONTENT_TYPE = "text/html"; + public static final String JSON_CONTENT_TYPE = "application/json"; + public static final String CONTENT_TYPE = "Content-Type"; + +} diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java b/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java new file mode 100644 index 00000000000..7fecad02037 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/HttpMethods.java @@ -0,0 +1,41 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; + +public enum HttpMethods { + + GET(HttpGet.METHOD_NAME), POST(HttpPost.METHOD_NAME), PUT(HttpPut.METHOD_NAME), DELETE(HttpDelete.METHOD_NAME); + + private final String name; + + private HttpMethods(final String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java b/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java new file mode 100644 index 00000000000..9492920b8cf --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/HttpStatusCodeHelper.java @@ -0,0 +1,34 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import org.apache.http.HttpStatus; + +public class HttpStatusCodeHelper { + + public static boolean isSuccess(final int statusCode) { + return statusCode >= HttpStatus.SC_OK && statusCode <= HttpStatus.SC_MULTI_STATUS; + } + + public static boolean isUnauthorized(final int statusCode) { + return statusCode == HttpStatus.SC_UNAUTHORIZED; + } + +} diff --git a/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java b/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java new file mode 100644 index 00000000000..4fb3a1d5229 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/HttpUriRequestBuilder.java @@ -0,0 +1,119 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.Consts; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.methods.RequestBuilder; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHeader; +import org.springframework.util.Assert; + +import com.google.common.base.Optional; + +public class HttpUriRequestBuilder { + + private static final String CONTENT_TYPE = HttpConstants.CONTENT_TYPE; + private static final String JSON_CONTENT_TYPE = HttpConstants.JSON_CONTENT_TYPE; + + private static final Optional ABSENT = Optional.absent(); + + private HttpMethods method; + private String path; + private Optional jsonPayload = ABSENT; + private final Map parameters = new HashMap(); + private final Map methodParameters = new HashMap(); + + private HttpUriRequestBuilder() { + + } + + public static HttpUriRequestBuilder create() { + return new HttpUriRequestBuilder(); + } + + public HttpUriRequestBuilder method(final HttpMethods method) { + this.method = method; + return this; + } + + public HttpUriRequestBuilder path(final String path) { + this.path = path; + return this; + } + + public HttpUriRequestBuilder jsonPayload(final Optional jsonPayload) { + this.jsonPayload = jsonPayload; + return this; + } + + public HttpUriRequestBuilder parameters(final Map parameters) { + this.parameters.clear(); + this.parameters.putAll(parameters); + return this; + } + + public HttpUriRequestBuilder methodParameters(final Map methodParameters) { + this.methodParameters.clear(); + this.methodParameters.putAll(methodParameters); + return this; + } + + public HttpUriRequest build() { + validate(); + final RequestBuilder builder = RequestBuilder.create(method.toString()).setUri(buildUri()); + if (!methodParameters.isEmpty()) { + for (final Entry entry : methodParameters.entrySet()) { + builder.addParameter(entry.getKey(), entry.getValue()); + } + } + if (jsonPayload.isPresent()) { + builder.addHeader(new BasicHeader(CONTENT_TYPE, JSON_CONTENT_TYPE)) + .setEntity(new StringEntity(jsonPayload.get(), ContentType.create(JSON_CONTENT_TYPE, Consts.UTF_8))); + } + return builder.build(); + } + + private void validate() { + Assert.notNull(method, "HTTP Method cannot be null"); + Assert.hasText(path, "target path must be defined"); + Assert.isTrue(path.startsWith("/"), "targte path must start with a '/' character"); + } + + private URI buildUri() { + try { + final URIBuilder builder = new URIBuilder().setPath(path); + for (final Map.Entry entry : parameters.entrySet()) { + builder.addParameter(entry.getKey(), entry.getValue()); + } + return builder.build(); + } catch (final URISyntaxException e) { + throw new IllegalArgumentException("Unable to build REST Service URI", e); + } + } +} diff --git a/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java new file mode 100644 index 00000000000..fc5bae38283 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/RESTServiceConnector.java @@ -0,0 +1,166 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; + +import com.google.common.base.Optional; +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializer; + +/** + * This abstraction encapsulates client side code for REST service communication. It encapsulates access in a REST client. There can be different implementations of that client + * implementing {@link RestClient}, and any of them should mention the needed data to work. + * + * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide in the constructor a map of classes to deserializers for these classes. + */ +public class RESTServiceConnector { + + private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class); + + private static final Optional ABSENT = Optional.absent(); + + private final RestClient client; + private final Gson gson; + + private RESTServiceConnector(final Builder builder) { + client = builder.client; + gson = setGsonDeserializer(builder.classToDeserializerMap); + } + + private static Gson setGsonDeserializer(final Map, JsonDeserializer> classToDeserializerMap) { + final GsonBuilder gsonBuilder = new GsonBuilder(); + for (final Map.Entry, JsonDeserializer> entry : classToDeserializerMap.entrySet()) { + gsonBuilder.registerTypeAdapter(entry.getKey(), entry.getValue()); + } + return gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + } + + public static Builder create() { + return new Builder(); + } + + public void executeUpdateObject(final T newObject, final String path, final Map parameters) throws CloudstackRESTException { + s_logger.debug("Executing update object on " + path); + client.closeResponse(createAndExecuteRequest(HttpMethods.PUT, path, parameters, Optional.fromNullable(gson.toJson(newObject)))); + } + + public void executeUpdateObject(final T newObject, final String path) throws CloudstackRESTException { + executeUpdateObject(newObject, path, new HashMap()); + } + + @SuppressWarnings("unchecked") + public T executeCreateObject(final T newObject, final String path, final Map parameters) throws CloudstackRESTException { + s_logger.debug("Executing create object on " + path); + final CloseableHttpResponse response = createAndExecuteRequest(HttpMethods.POST, path, parameters, Optional.fromNullable(gson.toJson(newObject))); + return (T) readResponseBody(response, newObject.getClass()); + } + + public T executeCreateObject(final T newObject, final String uri) throws CloudstackRESTException { + return executeCreateObject(newObject, uri, new HashMap()); + } + + public void executeDeleteObject(final String path) throws CloudstackRESTException { + s_logger.debug("Executing delete object on " + path); + client.closeResponse(createAndExecuteRequest(HttpMethods.DELETE, path, new HashMap(), ABSENT)); + } + + public T executeRetrieveObject(final Type returnObjectType, final String path, final Map parameters) throws CloudstackRESTException { + s_logger.debug("Executing retrieve object on " + path); + final CloseableHttpResponse response = createAndExecuteRequest(HttpMethods.GET, path, parameters, ABSENT); + return readResponseBody(response, returnObjectType); + } + + public T executeRetrieveObject(final Type returnObjectType, final String path) throws CloudstackRESTException { + return executeRetrieveObject(returnObjectType, path, new HashMap()); + } + + private CloseableHttpResponse createAndExecuteRequest(final HttpMethods method, final String path, final Map parameters, final Optional jsonPayLoad) + throws CloudstackRESTException { + final HttpUriRequest httpRequest = HttpUriRequestBuilder.create() + .path(path) + .parameters(parameters) + .jsonPayload(jsonPayLoad) + .method(method) + .build(); + if (jsonPayLoad.isPresent()) { + s_logger.debug("Built request '" + httpRequest + "' with payload: " + jsonPayLoad); + } + return executeRequest(httpRequest); + } + + private CloseableHttpResponse executeRequest(final HttpUriRequest httpRequest) throws CloudstackRESTException { + final CloseableHttpResponse response = client.execute(httpRequest); + s_logger.debug("Executed request: " + httpRequest + " status was " + response.getStatusLine().toString()); + return response; + } + + private T readResponseBody(final CloseableHttpResponse response, final Type type) throws CloudstackRESTException { + final HttpEntity entity = response.getEntity(); + try { + final String stringEntity = EntityUtils.toString(entity); + s_logger.debug("Response entity: " + stringEntity); + EntityUtils.consumeQuietly(entity); + return gson.fromJson(stringEntity, type); + } catch (final IOException e) { + throw new CloudstackRESTException("Could not deserialize response to JSON. Entity: " + entity, e); + } finally { + client.closeResponse(response); + } + + } + + public static class Builder { + private RestClient client; + final private Map, JsonDeserializer> classToDeserializerMap = new HashMap, JsonDeserializer>(); + + public Builder client(final RestClient client) { + this.client = client; + return this; + } + + public Builder classToDeserializerMap(final Map, JsonDeserializer> classToDeserializerMap) { + this.classToDeserializerMap.clear(); + this.classToDeserializerMap.putAll(classToDeserializerMap); + return this; + } + + public Builder classToDeserializerEntry(final Class clazz, final JsonDeserializer deserializer) { + classToDeserializerMap.put(clazz, deserializer); + return this; + } + + public RESTServiceConnector build() { + return new RESTServiceConnector(this); + } + } + +} diff --git a/utils/src/main/java/com/cloud/utils/rest/RestClient.java b/utils/src/main/java/com/cloud/utils/rest/RestClient.java new file mode 100644 index 00000000000..104f09bd8f5 --- /dev/null +++ b/utils/src/main/java/com/cloud/utils/rest/RestClient.java @@ -0,0 +1,31 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; + +public interface RestClient { + + public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException; + + public void closeResponse(final CloseableHttpResponse response) throws CloudstackRESTException; + +} diff --git a/utils/src/com/cloud/utils/script/OutputInterpreter.java b/utils/src/main/java/com/cloud/utils/script/OutputInterpreter.java similarity index 100% rename from utils/src/com/cloud/utils/script/OutputInterpreter.java rename to utils/src/main/java/com/cloud/utils/script/OutputInterpreter.java diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/main/java/com/cloud/utils/script/Script.java similarity index 100% rename from utils/src/com/cloud/utils/script/Script.java rename to utils/src/main/java/com/cloud/utils/script/Script.java diff --git a/utils/src/com/cloud/utils/script/Script2.java b/utils/src/main/java/com/cloud/utils/script/Script2.java similarity index 100% rename from utils/src/com/cloud/utils/script/Script2.java rename to utils/src/main/java/com/cloud/utils/script/Script2.java diff --git a/utils/src/com/cloud/utils/security/CertificateHelper.java b/utils/src/main/java/com/cloud/utils/security/CertificateHelper.java similarity index 100% rename from utils/src/com/cloud/utils/security/CertificateHelper.java rename to utils/src/main/java/com/cloud/utils/security/CertificateHelper.java diff --git a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java b/utils/src/main/java/com/cloud/utils/ssh/SSHCmdHelper.java similarity index 100% rename from utils/src/com/cloud/utils/ssh/SSHCmdHelper.java rename to utils/src/main/java/com/cloud/utils/ssh/SSHCmdHelper.java diff --git a/utils/src/com/cloud/utils/ssh/SSHKeysHelper.java b/utils/src/main/java/com/cloud/utils/ssh/SSHKeysHelper.java similarity index 100% rename from utils/src/com/cloud/utils/ssh/SSHKeysHelper.java rename to utils/src/main/java/com/cloud/utils/ssh/SSHKeysHelper.java diff --git a/utils/src/com/cloud/utils/ssh/SshException.java b/utils/src/main/java/com/cloud/utils/ssh/SshException.java similarity index 100% rename from utils/src/com/cloud/utils/ssh/SshException.java rename to utils/src/main/java/com/cloud/utils/ssh/SshException.java diff --git a/utils/src/com/cloud/utils/ssh/SshHelper.java b/utils/src/main/java/com/cloud/utils/ssh/SshHelper.java similarity index 100% rename from utils/src/com/cloud/utils/ssh/SshHelper.java rename to utils/src/main/java/com/cloud/utils/ssh/SshHelper.java diff --git a/utils/src/com/cloud/utils/storage/encoding/DecodedDataObject.java b/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataObject.java similarity index 100% rename from utils/src/com/cloud/utils/storage/encoding/DecodedDataObject.java rename to utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataObject.java diff --git a/utils/src/com/cloud/utils/storage/encoding/DecodedDataStore.java b/utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataStore.java similarity index 100% rename from utils/src/com/cloud/utils/storage/encoding/DecodedDataStore.java rename to utils/src/main/java/com/cloud/utils/storage/encoding/DecodedDataStore.java diff --git a/utils/src/com/cloud/utils/storage/encoding/Decoder.java b/utils/src/main/java/com/cloud/utils/storage/encoding/Decoder.java similarity index 100% rename from utils/src/com/cloud/utils/storage/encoding/Decoder.java rename to utils/src/main/java/com/cloud/utils/storage/encoding/Decoder.java diff --git a/utils/src/com/cloud/utils/storage/encoding/EncodingType.java b/utils/src/main/java/com/cloud/utils/storage/encoding/EncodingType.java similarity index 100% rename from utils/src/com/cloud/utils/storage/encoding/EncodingType.java rename to utils/src/main/java/com/cloud/utils/storage/encoding/EncodingType.java diff --git a/utils/src/com/cloud/utils/time/InaccurateClock.java b/utils/src/main/java/com/cloud/utils/time/InaccurateClock.java similarity index 100% rename from utils/src/com/cloud/utils/time/InaccurateClock.java rename to utils/src/main/java/com/cloud/utils/time/InaccurateClock.java diff --git a/utils/src/com/cloud/utils/time/InaccurateClockMBean.java b/utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java similarity index 100% rename from utils/src/com/cloud/utils/time/InaccurateClockMBean.java rename to utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java diff --git a/utils/src/com/cloud/utils/xmlobject/XmlObject.java b/utils/src/main/java/com/cloud/utils/xmlobject/XmlObject.java similarity index 100% rename from utils/src/com/cloud/utils/xmlobject/XmlObject.java rename to utils/src/main/java/com/cloud/utils/xmlobject/XmlObject.java diff --git a/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java b/utils/src/main/java/com/cloud/utils/xmlobject/XmlObjectParser.java similarity index 100% rename from utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java rename to utils/src/main/java/com/cloud/utils/xmlobject/XmlObjectParser.java diff --git a/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java rename to utils/src/main/java/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java b/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteClient.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java rename to utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteClient.java diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java b/utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteException.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java rename to utils/src/main/java/org/apache/cloudstack/utils/graphite/GraphiteException.java diff --git a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java rename to utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java diff --git a/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java b/utils/src/main/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java rename to utils/src/main/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java diff --git a/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/security/SSLUtils.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/security/SSLUtils.java rename to utils/src/main/java/org/apache/cloudstack/utils/security/SSLUtils.java diff --git a/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java b/utils/src/main/java/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java rename to utils/src/main/java/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java diff --git a/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java similarity index 100% rename from utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java rename to utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java diff --git a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java similarity index 100% rename from utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java rename to utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java diff --git a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java similarity index 100% rename from utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java rename to utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java diff --git a/utils/certs/cloud.keystore b/utils/src/main/resources/cloud.keystore similarity index 100% rename from utils/certs/cloud.keystore rename to utils/src/main/resources/cloud.keystore diff --git a/utils/test/com/cloud/utils/DateUtilTest.java b/utils/src/test/java/com/cloud/utils/DateUtilTest.java similarity index 100% rename from utils/test/com/cloud/utils/DateUtilTest.java rename to utils/src/test/java/com/cloud/utils/DateUtilTest.java diff --git a/utils/test/com/cloud/utils/DummyImpl.java b/utils/src/test/java/com/cloud/utils/DummyImpl.java similarity index 100% rename from utils/test/com/cloud/utils/DummyImpl.java rename to utils/src/test/java/com/cloud/utils/DummyImpl.java diff --git a/utils/test/com/cloud/utils/DummyInterface.java b/utils/src/test/java/com/cloud/utils/DummyInterface.java similarity index 100% rename from utils/test/com/cloud/utils/DummyInterface.java rename to utils/src/test/java/com/cloud/utils/DummyInterface.java diff --git a/utils/test/com/cloud/utils/DummyPremiumImpl.java b/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java similarity index 100% rename from utils/test/com/cloud/utils/DummyPremiumImpl.java rename to utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java diff --git a/utils/test/com/cloud/utils/HttpUtilsTest.java b/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java similarity index 100% rename from utils/test/com/cloud/utils/HttpUtilsTest.java rename to utils/src/test/java/com/cloud/utils/HttpUtilsTest.java diff --git a/utils/test/com/cloud/utils/NumbersUtilTest.java b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java similarity index 100% rename from utils/test/com/cloud/utils/NumbersUtilTest.java rename to utils/src/test/java/com/cloud/utils/NumbersUtilTest.java diff --git a/utils/test/com/cloud/utils/PasswordGeneratorTest.java b/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java similarity index 100% rename from utils/test/com/cloud/utils/PasswordGeneratorTest.java rename to utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java diff --git a/utils/test/com/cloud/utils/ProcessUtilTest.java b/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java similarity index 100% rename from utils/test/com/cloud/utils/ProcessUtilTest.java rename to utils/src/test/java/com/cloud/utils/ProcessUtilTest.java diff --git a/utils/test/com/cloud/utils/PropertiesUtilsTest.java b/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java similarity index 100% rename from utils/test/com/cloud/utils/PropertiesUtilsTest.java rename to utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java diff --git a/utils/test/com/cloud/utils/ReflectUtilTest.java b/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java similarity index 100% rename from utils/test/com/cloud/utils/ReflectUtilTest.java rename to utils/src/test/java/com/cloud/utils/ReflectUtilTest.java diff --git a/utils/test/com/cloud/utils/ScriptTest.java b/utils/src/test/java/com/cloud/utils/ScriptTest.java similarity index 100% rename from utils/test/com/cloud/utils/ScriptTest.java rename to utils/src/test/java/com/cloud/utils/ScriptTest.java diff --git a/utils/test/com/cloud/utils/StringUtilsTest.java b/utils/src/test/java/com/cloud/utils/StringUtilsTest.java similarity index 100% rename from utils/test/com/cloud/utils/StringUtilsTest.java rename to utils/src/test/java/com/cloud/utils/StringUtilsTest.java diff --git a/utils/test/com/cloud/utils/TernaryTest.java b/utils/src/test/java/com/cloud/utils/TernaryTest.java similarity index 100% rename from utils/test/com/cloud/utils/TernaryTest.java rename to utils/src/test/java/com/cloud/utils/TernaryTest.java diff --git a/utils/test/com/cloud/utils/TestProfiler.java b/utils/src/test/java/com/cloud/utils/TestProfiler.java similarity index 100% rename from utils/test/com/cloud/utils/TestProfiler.java rename to utils/src/test/java/com/cloud/utils/TestProfiler.java diff --git a/utils/test/com/cloud/utils/UriUtilsTest.java b/utils/src/test/java/com/cloud/utils/UriUtilsTest.java similarity index 100% rename from utils/test/com/cloud/utils/UriUtilsTest.java rename to utils/src/test/java/com/cloud/utils/UriUtilsTest.java diff --git a/utils/test/com/cloud/utils/UuidUtilsTest.java b/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java similarity index 100% rename from utils/test/com/cloud/utils/UuidUtilsTest.java rename to utils/src/test/java/com/cloud/utils/UuidUtilsTest.java diff --git a/utils/test/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java b/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java similarity index 100% rename from utils/test/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java rename to utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java diff --git a/utils/test/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java b/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java similarity index 100% rename from utils/test/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java rename to utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java diff --git a/utils/test/com/cloud/utils/crypto/RSAHelperTest.java b/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java similarity index 100% rename from utils/test/com/cloud/utils/crypto/RSAHelperTest.java rename to utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java diff --git a/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java b/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java similarity index 100% rename from utils/test/com/cloud/utils/encoding/UrlEncoderTest.java rename to utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java diff --git a/utils/test/com/cloud/utils/exception/ExceptionUtilTest.java b/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java similarity index 100% rename from utils/test/com/cloud/utils/exception/ExceptionUtilTest.java rename to utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java diff --git a/utils/test/com/cloud/utils/net/Ip4AddressTest.java b/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java similarity index 100% rename from utils/test/com/cloud/utils/net/Ip4AddressTest.java rename to utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java diff --git a/utils/test/com/cloud/utils/net/IpTest.java b/utils/src/test/java/com/cloud/utils/net/IpTest.java similarity index 100% rename from utils/test/com/cloud/utils/net/IpTest.java rename to utils/src/test/java/com/cloud/utils/net/IpTest.java diff --git a/utils/test/com/cloud/utils/net/MacAddressTest.java b/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java similarity index 100% rename from utils/test/com/cloud/utils/net/MacAddressTest.java rename to utils/src/test/java/com/cloud/utils/net/MacAddressTest.java diff --git a/utils/test/com/cloud/utils/net/NetUtilsTest.java b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java similarity index 100% rename from utils/test/com/cloud/utils/net/NetUtilsTest.java rename to utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java diff --git a/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java b/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java new file mode 100644 index 00000000000..c30103ef20a --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/BasicRestClientTest.java @@ -0,0 +1,106 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import org.apache.http.HttpHost; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.message.BasicStatusLine; +import org.junit.BeforeClass; +import org.junit.Test; + +public class BasicRestClientTest { + + private static final String LOCALHOST = "localhost"; + private static final String HTTPS = HttpConstants.HTTPS; + + private static final StatusLine HTTP_200_REPSONSE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 200, "OK"); + private static final StatusLine HTTP_503_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 503, "Service unavailable"); + + private static final CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class); + + private static CloseableHttpClient httpClient; + private static HttpUriRequest request; + + @BeforeClass + public static void setupClass() throws Exception { + request = HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("/path") + .build(); + httpClient = spy(HttpClientHelper.createHttpClient(2)); + } + + @Test + public void testExecuteRequest() throws Exception { + when(mockResponse.getStatusLine()).thenReturn(HTTP_200_REPSONSE); + doReturn(mockResponse).when(httpClient).execute(any(HttpHost.class), HttpRequestMatcher.eq(request), any(HttpClientContext.class)); + final BasicRestClient restClient = BasicRestClient.create() + .host(LOCALHOST) + .client(httpClient) + .build(); + + final CloseableHttpResponse response = restClient.execute(request); + + assertThat(response, notNullValue()); + assertThat(response, sameInstance(mockResponse)); + assertThat(response.getStatusLine(), sameInstance(HTTP_200_REPSONSE)); + } + + @Test + public void testExecuteRequestStatusCodeIsNotOk() throws Exception { + when(mockResponse.getStatusLine()).thenReturn(HTTP_503_STATUSLINE); + doReturn(mockResponse).when(httpClient).execute(any(HttpHost.class), HttpRequestMatcher.eq(request), any(HttpClientContext.class)); + final BasicRestClient restClient = BasicRestClient.create() + .host(LOCALHOST) + .client(httpClient) + .build(); + + final CloseableHttpResponse response = restClient.execute(request); + + assertThat(response, notNullValue()); + assertThat(response, sameInstance(mockResponse)); + assertThat(response.getStatusLine(), sameInstance(HTTP_503_STATUSLINE)); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteRequestWhenClientThrowsIOException() throws Exception { + final BasicRestClient restClient = BasicRestClient.create() + .host(LOCALHOST) + .client(HttpClientHelper.createHttpClient(5)) + .build(); + + restClient.execute(request); + } + +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java b/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java new file mode 100644 index 00000000000..20b32dd5a6e --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpClientHelperTest.java @@ -0,0 +1,38 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.notNullValue; + +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.Test; + +public class HttpClientHelperTest { + + @Test + public void testCreateClient() throws Exception { + int maxRedirects = 5; + final CloseableHttpClient client = HttpClientHelper.createHttpClient(maxRedirects); + + assertThat(client, notNullValue()); + } + +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java new file mode 100644 index 00000000000..effec792bcf --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpRequestMatcher.java @@ -0,0 +1,141 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.mockito.Matchers.argThat; + +import java.io.IOException; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.HttpRequest; +import org.apache.http.ParseException; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.util.EntityUtils; +import org.hamcrest.Description; +import org.hamcrest.SelfDescribing; +import org.mockito.ArgumentMatcher; + +public class HttpRequestMatcher extends ArgumentMatcher { + private final HttpRequest wanted; + + public HttpRequestMatcher(final HttpRequest wanted) { + this.wanted = wanted; + } + + public static HttpRequest eq(final HttpRequest request) { + return argThat(new HttpRequestMatcher(request)); + } + + @Override + public boolean matches(final Object actual) { + if (actual instanceof HttpUriRequest) { + final HttpUriRequest converted = (HttpUriRequest) actual; + return checkMethod(converted) && checkUri(converted) && checkPayload(converted); + } else { + return wanted == actual; + } + } + + private boolean checkPayload(final HttpUriRequest actual) { + final String wantedPayload = getPayload(wanted); + final String actualPayload = getPayload(actual); + return equalsString(wantedPayload, actualPayload); + } + + private static String getPayload(final HttpRequest request) { + String payload = ""; + if (request instanceof HttpEntityEnclosingRequest) { + try { + payload = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity()); + } catch (final ParseException e) { + throw new IllegalArgumentException("Couldn't read request's entity payload.", e); + } catch (final IOException e) { + throw new IllegalArgumentException("Couldn't read request's entity payload.", e); + } + } + return payload; + } + + private boolean checkUri(final HttpUriRequest actual) { + if (wanted instanceof HttpUriRequest) { + final String wantedQuery = ((HttpUriRequest) wanted).getURI().getQuery(); + final String actualQuery = actual.getURI().getQuery(); + return equalsString(wantedQuery, actualQuery); + } else { + return wanted == actual; + } + } + + private boolean checkMethod(final HttpUriRequest actual) { + if (wanted instanceof HttpUriRequest) { + final String wantedMethod = ((HttpUriRequest) wanted).getMethod(); + final String actualMethod = actual.getMethod(); + return equalsString(wantedMethod, actualMethod); + } else { + return wanted == actual; + } + } + + private static boolean equalsString(final String a, final String b) { + return a == b || a != null && a.equals(b); + } + + @Override + public void describeTo(final Description description) { + description.appendText(describe(wanted)); + } + + public String describe(final HttpRequest object) { + final StringBuilder sb = new StringBuilder(); + if (object instanceof HttpUriRequest) { + final HttpUriRequest converted = (HttpUriRequest) object; + sb.append("method = ").append(converted.getMethod()); + sb.append(", query = ").append(converted.getURI().getQuery()); + sb.append(", payload = ").append(getPayload(object)); + } + return sb.toString(); + } + + @Override + public boolean equals(final Object o) { + return EqualsBuilder.reflectionEquals(this, o); + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + public SelfDescribing withExtraTypeInfo() { + return new SelfDescribing() { + @Override + public void describeTo(final Description description) { + description.appendText("(" + wanted.getClass().getSimpleName() + ") ").appendText(describe(wanted)); + } + }; + } + + public boolean typeMatches(final Object object) { + return wanted != null && object != null && object.getClass() == wanted.getClass(); + } + +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java b/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java new file mode 100644 index 00000000000..3999b208622 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpStatusCodeHelperTest.java @@ -0,0 +1,59 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import org.apache.http.HttpStatus; +import org.junit.Test; + +public class HttpStatusCodeHelperTest { + + @Test + public void testIsSuccess() throws Exception { + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_SWITCHING_PROTOCOLS), equalTo(false)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_PROCESSING), equalTo(false)); + + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_OK), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_CREATED), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_ACCEPTED), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_NO_CONTENT), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_RESET_CONTENT), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_PARTIAL_CONTENT), equalTo(true)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_MULTI_STATUS), equalTo(true)); + + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_MULTIPLE_CHOICES), equalTo(false)); + assertThat(HttpStatusCodeHelper.isSuccess(HttpStatus.SC_MOVED_PERMANENTLY), equalTo(false)); + } + + @Test + public void testIsUnauthorized() throws Exception { + assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_TEMPORARY_REDIRECT), equalTo(false)); + assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_BAD_REQUEST), equalTo(false)); + + assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_UNAUTHORIZED), equalTo(true)); + + assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_PAYMENT_REQUIRED), equalTo(false)); + assertThat(HttpStatusCodeHelper.isUnauthorized(HttpStatus.SC_FORBIDDEN), equalTo(false)); + } + +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java new file mode 100644 index 00000000000..470f563e909 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestBuilderTest.java @@ -0,0 +1,115 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +import java.util.HashMap; + +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpUriRequest; +import org.junit.Test; + +import com.google.common.base.Optional; + +public class HttpUriRequestBuilderTest { + + @Test(expected = IllegalArgumentException.class) + public void testBuildWithNullMethod() throws Exception { + HttpUriRequestBuilder.create().path("/path").build(); + } + + @Test(expected = IllegalArgumentException.class) + public void testBuildWithNullPath() throws Exception { + HttpUriRequestBuilder.create().method(HttpMethods.GET).build(); + } + + @Test(expected = IllegalArgumentException.class) + public void testBuildWithEmptyPath() throws Exception { + HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("") + .build(); + } + + @Test(expected = IllegalArgumentException.class) + public void testBuildWithIlegalPath() throws Exception { + HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("path") + .build(); + } + + @Test + public void testBuildSimpleRequest() throws Exception { + final HttpUriRequest request = HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("/path") + .build(); + + assertThat(request, notNullValue()); + assertThat(request.getURI().getPath(), equalTo("/path")); + assertThat(request.getURI().getScheme(), nullValue()); + assertThat(request.getURI().getQuery(), nullValue()); + assertThat(request.getURI().getHost(), nullValue()); + assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME)); + } + + @Test + public void testBuildRequestWithParameters() throws Exception { + final HashMap parameters = new HashMap(); + parameters.put("key1", "value1"); + final HttpUriRequest request = HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("/path") + .parameters(parameters) + .build(); + + assertThat(request, notNullValue()); + assertThat(request.getURI().getPath(), equalTo("/path")); + assertThat(request.getURI().getQuery(), equalTo("key1=value1")); + assertThat(request.getURI().getScheme(), nullValue()); + assertThat(request.getURI().getHost(), nullValue()); + assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME)); + } + + @Test + public void testBuildRequestWithJsonPayload() throws Exception { + final HttpUriRequest request = HttpUriRequestBuilder.create() + .method(HttpMethods.GET) + .path("/path") + .jsonPayload(Optional.of("{'key1':'value1'}")) + .build(); + + assertThat(request, notNullValue()); + assertThat(request.getURI().getPath(), equalTo("/path")); + assertThat(request.getURI().getScheme(), nullValue()); + assertThat(request.getURI().getQuery(), nullValue()); + assertThat(request.getURI().getHost(), nullValue()); + assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME)); + assertThat(request.containsHeader(HttpConstants.CONTENT_TYPE), equalTo(true)); + assertThat(request.getFirstHeader(HttpConstants.CONTENT_TYPE).getValue(), equalTo(HttpConstants.JSON_CONTENT_TYPE)); + assertThat(request, HttpUriRequestPayloadMatcher.hasPayload("{'key1':'value1'}")); + } + +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java new file mode 100644 index 00000000000..f2d091f5f65 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestMethodMatcher.java @@ -0,0 +1,44 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Matchers.argThat; + +import org.apache.http.client.methods.HttpUriRequest; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; + +public class HttpUriRequestMethodMatcher extends FeatureMatcher { + + public static HttpUriRequest aMethod(final String method) { + return argThat(new HttpUriRequestMethodMatcher(equalTo(method), "method", "method")); + } + + public HttpUriRequestMethodMatcher(final Matcher subMatcher, final String featureDescription, final String featureName) { + super(subMatcher, featureDescription, featureName); + } + + @Override + protected String featureValueOf(final HttpUriRequest actual) { + return actual.getMethod(); + } + +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java new file mode 100644 index 00000000000..948e9f6b424 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPathMatcher.java @@ -0,0 +1,43 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Matchers.argThat; + +import org.apache.http.client.methods.HttpUriRequest; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; + +public class HttpUriRequestPathMatcher extends FeatureMatcher { + + public static HttpUriRequest aPath(final String path) { + return argThat(new HttpUriRequestPathMatcher(equalTo(path), "path", "path")); + } + + public HttpUriRequestPathMatcher(final Matcher subMatcher, final String featureDescription, final String featureName) { + super(subMatcher, featureDescription, featureName); + } + + @Override + protected String featureValueOf(final HttpUriRequest actual) { + return actual.getURI().getPath(); + } +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java new file mode 100644 index 00000000000..724f495ab97 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestPayloadMatcher.java @@ -0,0 +1,62 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Matchers.argThat; + +import java.io.IOException; + +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.ParseException; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.util.EntityUtils; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; + +public class HttpUriRequestPayloadMatcher extends FeatureMatcher { + + public static HttpUriRequest aPayload(final String payload) { + return argThat(hasPayload(payload)); + } + + public static HttpUriRequestPayloadMatcher hasPayload(final String payload) { + return new HttpUriRequestPayloadMatcher(equalTo(payload), "payload", "payload"); + } + + public HttpUriRequestPayloadMatcher(final Matcher subMatcher, final String featureDescription, final String featureName) { + super(subMatcher, featureDescription, featureName); + } + + @Override + protected String featureValueOf(final HttpUriRequest actual) { + String payload = ""; + if (actual instanceof HttpEntityEnclosingRequest) { + try { + payload = EntityUtils.toString(((HttpEntityEnclosingRequest) actual).getEntity()); + } catch (final ParseException e) { + throw new IllegalArgumentException("Couldn't read request's entity payload.", e); + } catch (final IOException e) { + throw new IllegalArgumentException("Couldn't read request's entity payload.", e); + } + } + return payload; + } +} diff --git a/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java new file mode 100644 index 00000000000..e73641bf865 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/HttpUriRequestQueryMatcher.java @@ -0,0 +1,48 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Matchers.argThat; + +import org.apache.http.client.methods.HttpUriRequest; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; + +public class HttpUriRequestQueryMatcher extends FeatureMatcher { + + public static HttpUriRequest aQuery(final String query) { + return argThat(new HttpUriRequestQueryMatcher(equalTo(query), "query", "query")); + } + + public static HttpUriRequest aQueryThatContains(final String query) { + return argThat(new HttpUriRequestQueryMatcher(containsString(query), "query", "query")); + } + + public HttpUriRequestQueryMatcher(final Matcher subMatcher, final String featureDescription, final String featureName) { + super(subMatcher, featureDescription, featureName); + } + + @Override + protected String featureValueOf(final HttpUriRequest actual) { + return actual.getURI().getQuery(); + } +} diff --git a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java new file mode 100644 index 00000000000..e26ee6acd57 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java @@ -0,0 +1,323 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.ProtocolVersion; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.message.BasicStatusLine; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.type.CollectionType; +import org.junit.Test; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +public class RESTServiceConnectorTest { + private static final BasicStatusLine HTTP_200_STATUS_LINE = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); + private static final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + private static final Map DEFAULT_TEST_PARAMETERS = new HashMap(); + static { + DEFAULT_TEST_PARAMETERS.put("arg1", "val1"); + DEFAULT_TEST_PARAMETERS.put("arg2", "val2"); + } + + @Test + public void testExecuteUpdateObject() throws Exception { + final TestPojo newObject = new TestPojo(); + newObject.setField("newValue"); + final String newObjectJson = gson.toJson(newObject); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + connector.executeUpdateObject(newObject, "/somepath"); + + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); + } + + @Test + public void testExecuteUpdateObjectWithParameters() throws Exception { + final TestPojo newObject = new TestPojo(); + newObject.setField("newValue"); + final String newObjectJson = gson.toJson(newObject); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + connector.executeUpdateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS); + + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class)); + } + + @Test + public void testExecuteCreateObject() throws Exception { + final TestPojo newObject = new TestPojo(); + newObject.setField("newValue"); + final String newObjectJson = gson.toJson(newObject); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getEntity()).thenReturn(new StringEntity(newObjectJson)); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + final TestPojo object = connector.executeCreateObject(newObject, "/somepath"); + + assertThat(object, notNullValue()); + assertThat(object, equalTo(newObject)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); + verify(response).close(); + } + + @Test + public void testExecuteCreateObjectWithParameters() throws Exception { + final TestPojo newObject = new TestPojo(); + newObject.setField("newValue"); + final String newObjectJson = gson.toJson(newObject); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getEntity()).thenReturn(new StringEntity(newObjectJson)); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS); + + assertThat(object, notNullValue()); + assertThat(object, equalTo(newObject)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class)); + verify(response).close(); + } + + @Test + public void testExecuteDeleteObject() throws Exception { + final HttpEntity entity = mock(HttpEntity.class); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getEntity()).thenReturn(entity); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + connector.executeDeleteObject("/somepath"); + + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("DELETE"), any(HttpClientContext.class)); + verify(response).close(); + } + + @Test + public void testExecuteRetrieveObject() throws Exception { + final TestPojo existingObject = new TestPojo(); + existingObject.setField("existingValue"); + final String newObjectJson = gson.toJson(existingObject); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getEntity()).thenReturn(new StringEntity(newObjectJson)); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath"); + + assertThat(object, notNullValue()); + assertThat(object, equalTo(existingObject)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); + verify(response).close(); + } + + @Test + public void testExecuteRetrieveObjectWithParameters() throws Exception { + final TestPojo existingObject = new TestPojo(); + existingObject.setField("existingValue"); + final String newObjectJson = gson.toJson(existingObject); + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getEntity()).thenReturn(new StringEntity(newObjectJson)); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); + + final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath", DEFAULT_TEST_PARAMETERS); + + assertThat(object, notNullValue()); + assertThat(object, equalTo(existingObject)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class)); + verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class)); + verify(response).close(); + } + + @Test(expected = JsonParseException.class) + public void testCustomDeserializerTypeMismatch() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + when(response.getEntity()).thenReturn(new StringEntity("[{somethig_not_type : \"WrongType\"}]")); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final RESTServiceConnector connector = new RESTServiceConnector.Builder() + .client(restClient) + .classToDeserializerEntry(TestPojo.class, new TestPojoDeserializer()) + .build(); + + connector.executeRetrieveObject(TestPojo.class, "/somepath"); + } + + @Test + public void testCustomDeserializerForCustomLists() throws Exception { + final CloseableHttpResponse response = mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); + when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}")); + final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); + final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); + final Class clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass(); + final RESTServiceConnector connector = new RESTServiceConnector.Builder() + .client(restClient) + .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer()) + .build(); + + connector.executeRetrieveObject(TestPojo.class, "/somepath"); + } + + class NiciraList { + private List results; + private int resultCount; + + public List getResults() { + return results; + } + + public void setResults(final List results) { + this.results = results; + } + + public int getResultCount() { + return resultCount; + } + + public void setResultCount(final int resultCount) { + this.resultCount = resultCount; + } + + } + + class TestPojo { + private String field; + + public String getField() { + return field; + } + + public void setField(final String field) { + this.field = field; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(final Object obj) { + return EqualsBuilder.reflectionEquals(this, obj); + } + + } + + private final class TestPojoDeserializer implements JsonDeserializer { + @Override + public TestPojo deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { + final JsonObject jsonObject = json.getAsJsonObject(); + + if (!jsonObject.has("type")) { + throw new JsonParseException("Deserializing as a TestPojo, but no type present in the json object"); + } + + return context.deserialize(jsonObject, TestPojo.class); + } + } + + private final class CustomListDeserializer implements JsonDeserializer { + private final Gson standardGson = new GsonBuilder().create(); + + @Override + public T deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { + final JsonObject jsonObject = json.getAsJsonObject(); + + System.err.println(json.toString()); + + if (jsonObject.has("results")) { + final JsonArray results = jsonObject.getAsJsonArray("results"); + return context.deserialize(results, typeOfT); + } else { + return standardGson.fromJson(jsonObject, typeOfT); + } + } + } +} diff --git a/utils/test/com/cloud/utils/ssh/SSHKeysHelperTest.java b/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java similarity index 100% rename from utils/test/com/cloud/utils/ssh/SSHKeysHelperTest.java rename to utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java diff --git a/utils/test/com/cloud/utils/testcase/Log4jEnabledTestCase.java b/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java similarity index 100% rename from utils/test/com/cloud/utils/testcase/Log4jEnabledTestCase.java rename to utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java diff --git a/utils/test/com/cloud/utils/testcase/NioTest.java b/utils/src/test/java/com/cloud/utils/testcase/NioTest.java similarity index 100% rename from utils/test/com/cloud/utils/testcase/NioTest.java rename to utils/src/test/java/com/cloud/utils/testcase/NioTest.java diff --git a/utils/test/com/cloud/utils/xmlobject/TestXmlObject.java b/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject.java similarity index 100% rename from utils/test/com/cloud/utils/xmlobject/TestXmlObject.java rename to utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject.java diff --git a/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java b/utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject2.java similarity index 100% rename from utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java rename to utils/src/test/java/com/cloud/utils/xmlobject/TestXmlObject2.java diff --git a/utils/test/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java b/utils/src/test/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java similarity index 100% rename from utils/test/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java rename to utils/src/test/java/org/apache/cloudstack/utils/imagestore/ImageStoreUtilTest.java diff --git a/utils/test/resources/com/cloud/utils/QualifierTestContext.xml b/utils/src/test/resources/com/cloud/utils/QualifierTestContext.xml similarity index 100% rename from utils/test/resources/com/cloud/utils/QualifierTestContext.xml rename to utils/src/test/resources/com/cloud/utils/QualifierTestContext.xml diff --git a/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml b/utils/src/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml similarity index 100% rename from utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml rename to utils/src/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml diff --git a/utils/test/resources/log4j.xml b/utils/src/test/resources/log4j.xml similarity index 100% rename from utils/test/resources/log4j.xml rename to utils/src/test/resources/log4j.xml diff --git a/utils/test/resources/testContext.xml b/utils/src/test/resources/testContext.xml similarity index 100% rename from utils/test/resources/testContext.xml rename to utils/src/test/resources/testContext.xml diff --git a/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java deleted file mode 100644 index 6d58b5be3d8..00000000000 --- a/utils/test/com/cloud/utils/rest/RESTServiceConnectorTest.java +++ /dev/null @@ -1,395 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package com.cloud.utils.rest; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.Collections; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.params.HttpClientParams; -import org.apache.http.HttpStatus; -import org.junit.Before; -import org.junit.Test; - -public class RESTServiceConnectorTest { - protected static final String UUID = "aaaa"; - protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; - - RESTServiceConnector connector; - HttpClient client = mock(HttpClient.class); - HttpMethod method; - String type; - String uri; - - @Before - public void setUp() { - final HttpClientParams hmp = mock(HttpClientParams.class); - when(client.getParams()).thenReturn(hmp); - connector = new RESTServiceConnector(null) { - @Override - public HttpClient createHttpClient() { - return client; - } - - @Override - public HttpMethod createMethod(final String newType, final String newUri) { - type = newType; - uri = newUri; - return method; - } - }; - - connector.validation = new RESTValidationStrategy(); - connector.setAdminCredentials("admin", "adminpass"); - connector.setControllerAddress("localhost"); - } - - @Test(expected = CloudstackRESTException.class) - public void testExecuteLoginWithoutHostname() throws CloudstackRESTException { - connector.setControllerAddress(null); - connector.validation.login(RESTServiceConnector.protocol, client); - } - - @Test(expected = CloudstackRESTException.class) - public void testExecuteLoginWithoutCredentials() throws CloudstackRESTException { - method = mock(PutMethod.class); - connector.setAdminCredentials(null, null); - connector.validation.login(RESTServiceConnector.protocol, client); - } - - @Test(expected = CloudstackRESTException.class) - public void testExecuteUpdateObjectWithoutHostname() throws CloudstackRESTException { - method = mock(PutMethod.class); - connector.setControllerAddress(null); - connector.executeUpdateObject(new String(), "/", Collections. 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(); - } - - @Test(expected = CloudstackRESTException.class) - public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException { - final GetMethod gm = mock(GetMethod.class); - when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); - connector.executeMethod(gm); - verify(gm, times(1)).getStatusCode(); - } - - /* Bit of a roundabout way to ensure that login is called after an un authorized result - * It not possible to properly mock login() - */ - public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException, HttpException, IOException { - // Prepare - final GetMethod gm = mock(GetMethod.class); - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); - - final RESTValidationStrategy previousValidationStrategy = connector.validation; - connector.validation = new RESTValidationStrategy(){ - @Override - protected void login(final String protocol, final HttpClient client) - throws CloudstackRESTException { - // Do nothing - } - }; - connector.setAdminCredentials("admin", "adminpass"); - connector.setControllerAddress("localhost"); - - // Execute - connector.executeMethod(gm); - // Leave mock object as is was - connector.validation = previousValidationStrategy; - - // Assert/verify - verify(gm, times(2)).getStatusCode(); - } - - @Test - public void testExecuteCreateObject() throws CloudstackRESTException, IOException { - JsonEntity ls = new JsonEntity(); - method = mock(PostMethod.class); - when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); - when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); - ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections. 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