You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by hu...@apache.org on 2014/02/18 09:53:05 UTC
[2/4] Nvp and rest refactoring and more tests
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
index 2717c31..23fe82a 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -76,7 +76,7 @@ import com.cloud.host.Host;
import com.cloud.network.nicira.Attachment;
import com.cloud.network.nicira.ControlClusterStatus;
import com.cloud.network.nicira.DestinationNatRule;
-import com.cloud.network.nicira.LogicalRouterConfig;
+import com.cloud.network.nicira.LogicalRouter;
import com.cloud.network.nicira.LogicalRouterPort;
import com.cloud.network.nicira.LogicalSwitch;
import com.cloud.network.nicira.LogicalSwitchPort;
@@ -132,7 +132,7 @@ public class NiciraNvpResourceTest {
public void testInitialization() throws ConfigurationException {
resource.configure("NiciraNvpResource", parameters);
- StartupCommand[] sc = resource.initialize();
+ final StartupCommand[] sc = resource.initialize();
assertTrue(sc.length == 1);
assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid()));
assertTrue("Incorrect NVP device name", "nvptestdevice".equals(sc[0].getName()));
@@ -143,11 +143,11 @@ public class NiciraNvpResourceTest {
public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- ControlClusterStatus ccs = mock(ControlClusterStatus.class);
+ final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("stable");
when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
- PingCommand ping = resource.getCurrentStatus(42);
+ final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping != null);
assertTrue(ping.getHostId() == 42);
assertTrue(ping.getHostType() == Host.Type.L2Networking);
@@ -157,11 +157,11 @@ public class NiciraNvpResourceTest {
public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- ControlClusterStatus ccs = mock(ControlClusterStatus.class);
+ final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("unstable");
when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
- PingCommand ping = resource.getCurrentStatus(42);
+ final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping == null);
}
@@ -169,11 +169,11 @@ public class NiciraNvpResourceTest {
public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- ControlClusterStatus ccs = mock(ControlClusterStatus.class);
+ final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("unstable");
when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException());
- PingCommand ping = resource.getCurrentStatus(42);
+ final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping == null);
}
@@ -181,12 +181,12 @@ public class NiciraNvpResourceTest {
public void testRetries() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalSwitch ls = mock(LogicalSwitch.class);
+ final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls);
- CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
assertTrue(clsa.getResult());
}
@@ -194,12 +194,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalSwitch ls = mock(LogicalSwitch.class);
+ final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls);
- CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
assertTrue(clsa.getResult());
assertTrue("cccc".equals(clsa.getLogicalSwitchUuid()));
}
@@ -208,12 +208,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalSwitch ls = mock(LogicalSwitch.class);
+ final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException());
- CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
- CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
+ final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
+ final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
assertFalse(clsa.getResult());
}
@@ -221,8 +221,8 @@ public class NiciraNvpResourceTest {
public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
- DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
+ final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
+ final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
assertTrue(dlsa.getResult());
}
@@ -232,8 +232,8 @@ public class NiciraNvpResourceTest {
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any());
- DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
- DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
+ final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
+ final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
assertFalse(dlsa.getResult());
}
@@ -241,12 +241,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee");
when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
- CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
assertTrue(clspa.getResult());
assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid()));
@@ -256,12 +256,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee");
when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException());
- CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
assertFalse(clspa.getResult());
}
@@ -269,13 +269,13 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee");
when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
- doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
- CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
- CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
+ final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
+ final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
assertFalse(clspa.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any());
}
@@ -285,7 +285,7 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters);
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any());
- DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(dlspa.getResult());
}
@@ -293,8 +293,8 @@ public class NiciraNvpResourceTest {
public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
- UpdateLogicalSwitchPortAnswer dlspa =
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
+ final UpdateLogicalSwitchPortAnswer dlspa =
(UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
assertFalse(dlspa.getResult());
}
@@ -304,11 +304,12 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters);
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
when(lspl.getResultCount()).thenReturn(1);
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
- FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertTrue(flspa.getResult());
}
@@ -317,11 +318,12 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters);
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
when(lspl.getResultCount()).thenReturn(0);
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
- FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(flspa.getResult());
}
@@ -331,7 +333,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException());
- FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
+ final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(flspa.getResult());
}
@@ -339,17 +341,17 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalRouterConfig lrc = mock(LogicalRouterConfig.class);
- LogicalRouterPort lrp = mock(LogicalRouterPort.class);
- LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ final LogicalRouter lrc = mock(LogicalRouter.class);
+ final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lrc.getUuid()).thenReturn("ccccc");
when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
when(lsp.getUuid()).thenReturn("fffff");
- when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
- CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertTrue(clra.getResult());
assertTrue("ccccc".equals(clra.getLogicalRouterUuid()));
@@ -360,9 +362,9 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenThrow(new NiciraNvpApiException());
- CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenThrow(new NiciraNvpApiException());
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertFalse(clra.getResult());
}
@@ -371,12 +373,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalRouterConfig lrc = mock(LogicalRouterConfig.class);
+ final LogicalRouter lrc = mock(LogicalRouter.class);
when(lrc.getUuid()).thenReturn("ccccc");
- when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException());
- CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertFalse(clra.getResult());
verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
@@ -386,18 +388,18 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- LogicalRouterConfig lrc = mock(LogicalRouterConfig.class);
- LogicalRouterPort lrp = mock(LogicalRouterPort.class);
- LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
+ final LogicalRouter lrc = mock(LogicalRouter.class);
+ final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
+ final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lrc.getUuid()).thenReturn("ccccc");
when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
when(lsp.getUuid()).thenReturn("fffff");
- when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc);
+ when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException());
- CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
- CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
+ final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
+ final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertFalse(clra.getResult());
verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
@@ -409,7 +411,7 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters);
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa"));
- DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
+ final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
assertFalse(dlspa.getResult());
}
@@ -417,16 +419,17 @@ public class NiciraNvpResourceTest {
public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
- ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
+ final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<LogicalRouterPort> list = mock(NiciraNvpList.class);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
- doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalRouterPort((String)any(), (LogicalRouterPort)any());
+ doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list);
- ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertFalse(answer.getResult());
}
@@ -440,31 +443,32 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
- List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
- NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
- ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
- public boolean matches(Object argument) {
- NatRule rule = (NatRule)argument;
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
@@ -485,33 +489,34 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
- List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
- public boolean matches(Object argument) {
- NatRule rule = (NatRule)argument;
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
@@ -532,15 +537,15 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false);
- List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
final UUID rule0Uuid = UUID.randomUUID();
final UUID rule1Uuid = UUID.randomUUID();
rulepair[0].setUuid(rule0Uuid);
@@ -549,18 +554,19 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override
- public boolean matches(Object argument) {
- UUID uuid = (UUID)argument;
+ public boolean matches(final Object argument) {
+ final UUID uuid = (UUID)argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true;
}
@@ -578,26 +584,27 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
- StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
- List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+ final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
+ final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
+ final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(0);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertFalse(a.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
@@ -612,31 +619,32 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
- List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
- NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
- ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
- public boolean matches(Object argument) {
- NatRule rule = (NatRule)argument;
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
@@ -657,33 +665,34 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true);
- List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override
- public boolean matches(Object argument) {
- NatRule rule = (NatRule)argument;
+ public boolean matches(final Object argument) {
+ final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true;
}
@@ -704,15 +713,15 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true);
- List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
final UUID rule0Uuid = UUID.randomUUID();
final UUID rule1Uuid = UUID.randomUUID();
rulepair[0].setUuid(rule0Uuid);
@@ -721,18 +730,19 @@ public class NiciraNvpResourceTest {
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override
- public boolean matches(Object argument) {
- UUID uuid = (UUID)argument;
+ public boolean matches(final Object argument) {
+ final UUID uuid = (UUID)argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true;
}
@@ -750,26 +760,27 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
- List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls
- NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(0);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
- ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertFalse(a.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
@@ -784,25 +795,26 @@ public class NiciraNvpResourceTest {
*/
// Mock the command
- ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
- PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false);
- List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+ final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
+ final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false);
+ final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule);
when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api find call
@SuppressWarnings("unchecked")
+ final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls
- NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp");
+ final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp");
rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
- ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
+ final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
// The expected result is false, Nicira does not support port ranges in DNAT
assertFalse(a.getResult());
@@ -811,16 +823,16 @@ public class NiciraNvpResourceTest {
@Test
public void testGenerateStaticNatRulePair() {
- NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
+ final NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
assertTrue("DestinationNatRule".equals(rules[0].getType()));
assertTrue("SourceNatRule".equals(rules[1].getType()));
- DestinationNatRule dnr = (DestinationNatRule)rules[0];
+ final DestinationNatRule dnr = (DestinationNatRule)rules[0];
assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
assertTrue(dnr.getToDestinationPort() == null);
assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
- SourceNatRule snr = (SourceNatRule)rules[1];
+ final SourceNatRule snr = (SourceNatRule)rules[1];
assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
assertTrue(snr.getToSourcePort() == null);
assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
@@ -828,18 +840,18 @@ public class NiciraNvpResourceTest {
@Test
public void testGeneratePortForwardingRulePair() {
- NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
+ final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
assertTrue("DestinationNatRule".equals(rules[0].getType()));
assertTrue("SourceNatRule".equals(rules[1].getType()));
- DestinationNatRule dnr = (DestinationNatRule)rules[0];
+ final DestinationNatRule dnr = (DestinationNatRule)rules[0];
assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
assertTrue(dnr.getToDestinationPort() == 8080);
assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
assertTrue(dnr.getMatch().getDestinationPort() == 80);
assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6);
- SourceNatRule snr = (SourceNatRule)rules[1];
+ final SourceNatRule snr = (SourceNatRule)rules[1];
assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
assertTrue(snr.getToSourcePort() == 80);
assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index cf6e960..d9bd2de 100644
--- a/pom.xml
+++ b/pom.xml
@@ -36,6 +36,7 @@
<properties>
<cs.jdk.version>1.7</cs.jdk.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<cs.log4j.version>1.2.16</cs.log4j.version>
<cs.log4j.extras.version>1.1</cs.log4j.extras.version>
@@ -501,6 +502,11 @@
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-site-plugin</artifactId>
+ <version>3.3</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${cs.checkstyle.version}</version>
<dependencies>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/utils/pom.xml
----------------------------------------------------------------------
diff --git a/utils/pom.xml b/utils/pom.xml
index f63d7c4..f3b8f5f 100755
--- a/utils/pom.xml
+++ b/utils/pom.xml
@@ -141,6 +141,10 @@
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
</dependencies>
<build>
<plugins>
@@ -173,4 +177,27 @@
</resource>
</resources>
</build>
+
+ <profiles>
+ <profile>
+ <id>integration</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>integration-test</goal>
+ <goal>verify</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+
</project>
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
new file mode 100644
index 0000000..e522852
--- /dev/null
+++ b/utils/src/com/cloud/utils/rest/BasicEncodedRESTValidationStrategy.java
@@ -0,0 +1,47 @@
+package com.cloud.utils.rest;
+
+import java.io.IOException;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethodBase;
+
+/**
+ * Base 64 encoded authorization strategy. This implementation as opposed to
+ * {@link RESTValidationStrategy} doesn't do a login after auth error, but instead
+ * includes the encoded credentials in each request, instead of a cookie.
+ */
+public class BasicEncodedRESTValidationStrategy extends RESTValidationStrategy {
+
+ public BasicEncodedRESTValidationStrategy(final String host, final String adminuser, final String adminpass) {
+ super();
+ this.host = host;
+ user = adminuser;
+ password = adminpass;
+ }
+
+ public BasicEncodedRESTValidationStrategy() {
+ }
+
+ @Override
+ public void executeMethod(final HttpMethodBase method, final HttpClient client,
+ final String protocol)
+ throws CloudstackRESTException, HttpException, IOException {
+ if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
+ throw new CloudstackRESTException("Hostname/credentials are null or empty");
+ }
+
+ final String encodedCredentials = encodeCredentials();
+ method.setRequestHeader("Authorization", "Basic " + encodedCredentials);
+ client.executeMethod(method);
+ }
+
+ private String encodeCredentials() {
+ final String authString = user + ":" + password;
+ final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
+ final String authStringEnc = new String(authEncBytes);
+ return authStringEnc;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/utils/src/com/cloud/utils/rest/CloudstackRESTException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/CloudstackRESTException.java b/utils/src/com/cloud/utils/rest/CloudstackRESTException.java
new file mode 100644
index 0000000..8d74598
--- /dev/null
+++ b/utils/src/com/cloud/utils/rest/CloudstackRESTException.java
@@ -0,0 +1,36 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.utils.rest;
+
+public class CloudstackRESTException extends Exception {
+
+ public CloudstackRESTException() {
+ }
+
+ public CloudstackRESTException(final String message) {
+ super(message);
+ }
+
+ public CloudstackRESTException(final Throwable cause) {
+ super(cause);
+ }
+
+ public CloudstackRESTException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/utils/src/com/cloud/utils/rest/RESTServiceConnector.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/RESTServiceConnector.java b/utils/src/com/cloud/utils/rest/RESTServiceConnector.java
new file mode 100644
index 0000000..7cc2e89
--- /dev/null
+++ b/utils/src/com/cloud/utils/rest/RESTServiceConnector.java
@@ -0,0 +1,377 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.utils.rest;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Type;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.Socket;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpMethodBase;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.cookie.CookiePolicy;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.Protocol;
+import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
+import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+import org.apache.log4j.Logger;
+
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * This abstraction encapsulates client side code for REST service communication. It encapsulates
+ * access in a delegate validation strategy. There may different implementations extending
+ * {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
+ *
+ * This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide
+ * in the constructor a list of classes and a list of deserializers for these classes. These should
+ * be a correlated so that Nth deserializer is correctly mapped to Nth class.
+ */
+public class RESTServiceConnector {
+ private static final String HTTPS = "https";
+ protected static final String GET_METHOD_TYPE = "get";
+ protected static final String DELETE_METHOD_TYPE = "delete";
+ protected static final String PUT_METHOD_TYPE = "put";
+ protected static final String POST_METHOD_TYPE = "post";
+ private static final String TEXT_HTML_CONTENT_TYPE = "text/html";
+ private static final String JSON_CONTENT_TYPE = "application/json";
+ private static final String CONTENT_TYPE = "Content-Type";
+ private static final int BODY_RESP_MAX_LEN = 1024;
+ private static final int HTTPS_PORT = 443;
+
+ private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class);
+
+ protected final static String protocol = HTTPS;
+
+ private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
+
+ protected RESTValidationStrategy validation;
+
+ private final HttpClient client;
+
+ private final Gson gson;
+
+
+ /**
+ * Getter that may be needed only for test purpose
+ *
+ * @return
+ */
+ public Gson getGson() {
+ return gson;
+ }
+
+ public RESTServiceConnector(final RESTValidationStrategy validationStrategy) {
+ this(validationStrategy, null, null);
+ }
+
+ public RESTServiceConnector(final RESTValidationStrategy validationStrategy, final List<Class<?>> classList, final List<JsonDeserializer<?>> deserializerList) {
+ validation = validationStrategy;
+ client = createHttpClient();
+ client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
+
+ try {
+ // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
+ Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT));
+ } catch (final IOException e) {
+ s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
+ }
+
+ final GsonBuilder gsonBuilder = new GsonBuilder();
+ if(classList != null && deserializerList != null) {
+ for(int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
+ gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
+ }
+ }
+ gson = gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
+ }
+
+ public HttpClient createHttpClient() {
+ return new HttpClient(s_httpClientManager);
+ }
+
+ public HttpMethod createMethod(final String type, final String uri) throws CloudstackRESTException {
+ String url;
+ try {
+ url = new URL(protocol, validation.getHost(), uri).toString();
+ } catch (final MalformedURLException e) {
+ s_logger.error("Unable to build REST Service URL", e);
+ throw new CloudstackRESTException("Unable to build Nicira API URL", e);
+ }
+
+ if (POST_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new PostMethod(url);
+ } else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new GetMethod(url);
+ } else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new DeleteMethod(url);
+ } else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) {
+ return new PutMethod(url);
+ } else {
+ throw new CloudstackRESTException("Requesting unknown method type");
+ }
+ }
+
+ public void setControllerAddress(final String address) {
+ validation.setHost(address);
+ }
+
+ public void setAdminCredentials(final String username, final String password) {
+ validation.setUser(username);
+ validation.setPassword(password);
+ }
+
+ public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
+
+ final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri);
+ pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+ try {
+ pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
+ } catch (final UnsupportedEncodingException e) {
+ throw new CloudstackRESTException("Failed to encode json request body", e);
+ }
+
+ executeMethod(pm);
+
+ if (pm.getStatusCode() != HttpStatus.SC_OK) {
+ final String errorMessage = responseToErrorMessage(pm);
+ pm.releaseConnection();
+ s_logger.error("Failed to update object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to update object : " + errorMessage);
+ }
+ pm.releaseConnection();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters)
+ throws CloudstackRESTException {
+
+ final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri);
+ pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+ try {
+ pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
+ } catch (final UnsupportedEncodingException e) {
+ throw new CloudstackRESTException("Failed to encode json request body", e);
+ }
+
+ executeMethod(pm);
+
+ if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
+ final String errorMessage = responseToErrorMessage(pm);
+ pm.releaseConnection();
+ s_logger.error("Failed to create object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to create object : " + errorMessage);
+ }
+
+ T result;
+ try {
+ result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
+ } catch (final IOException e) {
+ throw new CloudstackRESTException("Failed to decode json response body", e);
+ } finally {
+ pm.releaseConnection();
+ }
+
+ return result;
+ }
+
+ public void executeDeleteObject(final String uri) throws CloudstackRESTException {
+ final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri);
+ dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+
+ executeMethod(dm);
+
+ if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
+ final String errorMessage = responseToErrorMessage(dm);
+ dm.releaseConnection();
+ s_logger.error("Failed to delete object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to delete object : " + errorMessage);
+ }
+ dm.releaseConnection();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
+ final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri);
+ gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
+ if (parameters != null && !parameters.isEmpty()) {
+ final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
+ for (final Entry<String, String> e : parameters.entrySet()) {
+ nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
+ }
+ gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
+ }
+
+ executeMethod(gm);
+
+ if (gm.getStatusCode() != HttpStatus.SC_OK) {
+ final String errorMessage = responseToErrorMessage(gm);
+ gm.releaseConnection();
+ s_logger.error("Failed to retrieve object : " + errorMessage);
+ throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
+ }
+
+ T returnValue;
+ try {
+ returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
+ } catch (final IOException e) {
+ s_logger.error("IOException while retrieving response body", e);
+ throw new CloudstackRESTException(e);
+ } finally {
+ gm.releaseConnection();
+ }
+ return returnValue;
+ }
+
+ public void executeMethod(final HttpMethodBase method) throws CloudstackRESTException {
+ try {
+ validation.executeMethod(method, client, protocol);
+ } catch (final HttpException e) {
+ s_logger.error("HttpException caught while trying to connect to the REST Service", e);
+ method.releaseConnection();
+ throw new CloudstackRESTException("API call to REST Service Failed", e);
+ } catch (final IOException e) {
+ s_logger.error("IOException caught while trying to connect to the REST Service", e);
+ method.releaseConnection();
+ throw new CloudstackRESTException("API call to Nicira REST Service Failed", e);
+ }
+ }
+
+ private String responseToErrorMessage(final HttpMethodBase method) {
+ assert method.isRequestSent() : "no use getting an error message unless the request is sent";
+
+ if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
+ // The error message is the response content
+ // Safety margin of 1024 characters, anything longer is probably useless
+ // and will clutter the logs
+ try {
+ return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
+ } catch (final IOException e) {
+ s_logger.debug("Error while loading response body", e);
+ }
+ }
+
+ // The default
+ return method.getStatusText();
+ }
+
+ /* Some controllers use a self-signed certificate. The
+ * TrustingProtocolSocketFactory will accept any provided
+ * certificate when making an SSL connection to the SDN
+ * Manager
+ */
+ private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
+
+ private SSLSocketFactory ssf;
+
+ public TrustingProtocolSocketFactory() throws IOException {
+ // Create a trust manager that does not validate certificate chains
+ final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+
+ @Override
+ public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
+ // Trust always
+ }
+
+ @Override
+ public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
+ // Trust always
+ }
+ }};
+
+ try {
+ // Install the all-trusting trust manager
+ final SSLContext sc = SSLContext.getInstance("SSL");
+ sc.init(null, trustAllCerts, new java.security.SecureRandom());
+ ssf = sc.getSocketFactory();
+ } catch (final KeyManagementException e) {
+ throw new IOException(e);
+ } catch (final NoSuchAlgorithmException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public Socket createSocket(final String host, final int port) throws IOException {
+ return ssf.createSocket(host, port);
+ }
+
+ @Override
+ public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
+ return ssf.createSocket(address, port, localAddress, localPort);
+ }
+
+ @Override
+ public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
+ return ssf.createSocket(socket, host, port, autoClose);
+ }
+
+ @Override
+ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
+ throws IOException, UnknownHostException, ConnectTimeoutException {
+ final int timeout = params.getConnectionTimeout();
+ if (timeout == 0) {
+ return createSocket(host, port, localAddress, localPort);
+ } else {
+ final Socket s = ssf.createSocket();
+ s.bind(new InetSocketAddress(localAddress, localPort));
+ s.connect(new InetSocketAddress(host, port), timeout);
+ return s;
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510972ab/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java b/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java
new file mode 100644
index 0000000..cb25614
--- /dev/null
+++ b/utils/src/com/cloud/utils/rest/RESTValidationStrategy.java
@@ -0,0 +1,146 @@
+package com.cloud.utils.rest;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethodBase;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.log4j.Logger;
+
+/**
+ * Basic authentication strategy. This strategy needs user and password for authentication.
+ *
+ * A login URL is needed which will be used for login and getting the cookie to be
+ * used in next requests. If an executeMethod request fails due to authorization it will try
+ * to login, get the cookie and repeat the attempt to execute the method.
+ */
+public class RESTValidationStrategy {
+
+ private static final Logger s_logger = Logger.getLogger(RESTValidationStrategy.class);
+
+ protected String host;
+ protected String user;
+ protected String password;
+ protected String serverVersion;
+ protected String loginUrl;
+
+ public RESTValidationStrategy(final String host, final String user, final String password,
+ final String serverVersion, final String loginUrl) {
+ super();
+ this.host = host;
+ this.user = user;
+ this.password = password;
+ this.serverVersion = serverVersion;
+ this.loginUrl = loginUrl;
+ }
+
+ public RESTValidationStrategy(final String loginUrl) {
+ this.loginUrl = loginUrl;
+ }
+
+ public RESTValidationStrategy() {
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(final String user) {
+ this.user = user;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(final String password) {
+ this.password = password;
+ }
+
+ public String getLoginUrl() {
+ return loginUrl;
+ }
+
+ public void setLoginUrl(final String loginUrl) {
+ this.loginUrl = loginUrl;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(final String host) {
+ this.host = host;
+ }
+
+ public void executeMethod(final HttpMethodBase method, final HttpClient client,
+ final String protocol)
+ throws CloudstackRESTException, HttpException, IOException {
+ if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
+ throw new CloudstackRESTException("Hostname/credentials are null or empty");
+ }
+
+ client.executeMethod(method);
+ if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
+ method.releaseConnection();
+ // login and try again
+ login(protocol, client);
+ client.executeMethod(method);
+ }
+ }
+
+ /**
+ * Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable.
+ * <p>
+ * The method returns false if the login failed or the connection could not be made.
+ *
+ */
+ protected void login(final String protocol,
+ final HttpClient client)
+ throws CloudstackRESTException {
+ String url;
+
+ if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
+ throw new CloudstackRESTException("Hostname/credentials are null or empty");
+ }
+
+ try {
+ url = new URL(protocol, host, loginUrl).toString();
+ } catch (final MalformedURLException e) {
+ s_logger.error("Unable to build Nicira API URL", e);
+ throw new CloudstackRESTException("Unable to build Nicira API URL", e);
+ }
+
+ final PostMethod pm = new PostMethod(url);
+ pm.addParameter("username", user);
+ pm.addParameter("password", password);
+
+ try {
+ client.executeMethod(pm);
+ } catch (final HttpException e) {
+ throw new CloudstackRESTException("REST Service API login failed ", e);
+ } catch (final IOException e) {
+ throw new CloudstackRESTException("REST Service API login failed ", e);
+ } finally {
+ pm.releaseConnection();
+ }
+
+ if (pm.getStatusCode() != HttpStatus.SC_OK) {
+ s_logger.error("REST Service API login failed : " + pm.getStatusText());
+ throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText());
+ }
+
+ // Extract the version for later use
+ if (pm.getResponseHeader("Server") != null) {
+ serverVersion = pm.getResponseHeader("Server").getValue();
+ s_logger.debug("Server reports version " + serverVersion);
+ }
+
+ // Success; the cookie required for login is kept in _client
+ }
+
+}