/**
 * Tests behavior of {@code BindInstantiateVAppTemplateParamsToXmlPayload}
 *
 * @author Adrian Cole
 */
@Test(groups = "unit")
public class BindInstantiateVAppTemplateParamsToXmlPayloadTest {
  Injector injector =
      Guice.createInjector(
          Rocoto.expandVariables(
              new ConfigurationModule() {

                @Override
                protected void bindConfigurations() {
                  bindProperties(TerremarkVCloudApiMetadata.defaultProperties());
                }

                @SuppressWarnings("unused")
                @Network
                @Provides
                @Singleton
                Supplier<ReferenceType> provideNetwork() {
                  return Suppliers.<ReferenceType>ofInstance(
                      new ReferenceTypeImpl(
                          null, null, URI.create("https://vcloud.safesecureweb.com/network/1990")));
                }
              }));

  public void testAllOptions() throws IOException {

    String expected =
        Strings2.toStringAndClose(
            getClass().getResourceAsStream("/InstantiateVAppTemplateParams-options-test.xml"));
    Multimap<String, String> headers =
        Multimaps.synchronizedMultimap(HashMultimap.<String, String>create());
    GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
    expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
    expect(request.getArgs())
        .andReturn(
            ImmutableList.<Object>of(
                InstantiateVAppTemplateOptions.Builder.processorCount(2)
                    .memory(512)
                    .inGroup("group")
                    .withPassword("password")
                    .inRow("row")
                    .addNetworkConfig(new NetworkConfig(URI.create("http://network")))))
        .atLeastOnce();
    expect(request.getFirstHeaderOrNull("Content-Type"))
        .andReturn("application/unknown")
        .atLeastOnce();
    expect(request.getHeaders()).andReturn(headers).atLeastOnce();
    request.setPayload(expected);
    replay(request);

    BindInstantiateVAppTemplateParamsToXmlPayload binder =
        injector.getInstance(BindInstantiateVAppTemplateParamsToXmlPayload.class);

    Map<String, String> map = Maps.newHashMap();
    map.put("name", "name");
    map.put("template", "https://vcloud/vAppTemplate/3");
    binder.bindToRequest(request, map);
  }
}
/**
 * Tests behavior of {@code BindNetworkConnectionSectionToXmlPayload}
 *
 * @author Adrian Cole
 */
@Test(groups = "unit")
public class BindNetworkConnectionSectionToXmlPayloadTest {
  Injector injector =
      Guice.createInjector(
          Rocoto.expandVariables(
              new ConfigurationModule() {

                @Override
                protected void bindConfigurations() {
                  bindProperties(new VCloudPropertiesBuilder(new Properties()).build());
                }
              }));

  public void testWithIpAllocationModeNONE() throws IOException {

    HttpRequest request =
        HttpRequest.builder().endpoint(URI.create("http://localhost/key")).method("GET").build();

    BindNetworkConnectionSectionToXmlPayload binder =
        injector.getInstance(BindNetworkConnectionSectionToXmlPayload.class);

    binder.bindToRequest(
        request,
        NetworkConnectionSection.builder()
            .type("application/vnd.vmware.vcloud.networkConnectionSection+xml")
            .info("Specifies the available VM network connections")
            .href(URI.create("https://1.1.1.1/api/v1.0/vApp/vm-1/networkConnectionSection/"))
            .connections(
                ImmutableSet.<NetworkConnection>of(
                    NetworkConnection.builder()
                        .network("none")
                        .ipAddressAllocationMode(IpAddressAllocationMode.NONE)
                        .build()))
            .build());
    assertEquals(
        request.getPayload().getContentMetadata().getContentType(),
        "application/vnd.vmware.vcloud.networkConnectionSection+xml");

    assertEquals(
        request.getPayload().getRawContent(),
        "<NetworkConnectionSection xmlns=\"http://www.vmware.com/vcloud/v1\" xmlns:ovf=\"http://schemas.dmtf.org/ovf/envelope/1\" href=\"https://1.1.1.1/api/v1.0/vApp/vm-1/networkConnectionSection/\" ovf:required=\"false\" type=\"application/vnd.vmware.vcloud.networkConnectionSection+xml\"><ovf:Info>Specifies the available VM network connections</ovf:Info><NetworkConnection network=\"none\"><NetworkConnectionIndex>0</NetworkConnectionIndex><IsConnected>false</IsConnected><IpAddressAllocationMode>NONE</IpAddressAllocationMode></NetworkConnection></NetworkConnectionSection>");
  }
}
  public void run(String[] args) throws Exception {
    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
      printUsage();
      System.exit(-1);
    }

    Options options = new Options();
    buildOptions(options);
    Daemonizer.buildOptions(options);
    Parser parser = new GnuParser();
    final CommandLine cli = parser.parse(options, args);
    Daemonizer.handleDaemonization(cli);

    Set<Module> modules = new HashSet<>();
    WMATARealtimeModule.addModuleAndDependencies(modules);

    _injector =
        Guice.createInjector(
            new URLConverter(),
            new FileConverter(),
            new PropertiesConverter(),
            new ConfigurationModule() {
              @Override
              protected void bindConfigurations() {
                bindEnvironmentVariables();
                bindSystemProperties();

                if (cli.hasOption(ARG_CONFIG_FILE)) {
                  bindProperties(new File(cli.getOptionValue(ARG_CONFIG_FILE)));
                }
              }
            },
            Rocoto.expandVariables(modules));

    _injector.injectMembers(this);

    _tripUpdatesUrl = getConfigurationValue(URL.class, "tripUpdates.url");
    if (_tripUpdatesUrl != null) {
      GtfsRealtimeServlet servlet = _injector.getInstance(GtfsRealtimeServlet.class);
      servlet.setUrl(_tripUpdatesUrl);
      servlet.setSource(_tripUpdatesExporter);
    }

    _tripUpdatesPath = getConfigurationValue(File.class, "tripUpdates.path");
    if (_tripUpdatesPath != null) {
      GtfsRealtimeFileWriter writer = _injector.getInstance(GtfsRealtimeFileWriter.class);
      writer.setPath(_tripUpdatesPath);
      writer.setSource(_tripUpdatesExporter);
    }

    _vehiclePositionsUrl = getConfigurationValue(URL.class, "vehiclePositions.url");
    if (_vehiclePositionsUrl != null) {
      GtfsRealtimeServlet servlet = _injector.getInstance(GtfsRealtimeServlet.class);
      servlet.setUrl(_vehiclePositionsUrl);
      servlet.setSource(_vehiclePositionsExporter);
    }

    _vehiclePositionsPath = getConfigurationValue(File.class, "vehiclePositions.path");
    if (_vehiclePositionsPath != null) {
      GtfsRealtimeFileWriter writer = _injector.getInstance(GtfsRealtimeFileWriter.class);
      writer.setPath(_vehiclePositionsPath);
      writer.setSource(_vehiclePositionsExporter);
    }

    _alertsUrl = getConfigurationValue(URL.class, "alerts.url");
    if (_alertsUrl != null) {
      GtfsRealtimeServlet servlet = _injector.getInstance(GtfsRealtimeServlet.class);
      servlet.setUrl(_alertsUrl);
      servlet.setSource(_alertsExporter);
    }

    _alertsPath = getConfigurationValue(File.class, "alerts.path");
    if (_alertsPath != null) {
      GtfsRealtimeFileWriter writer = _injector.getInstance(GtfsRealtimeFileWriter.class);
      writer.setPath(_alertsPath);
      writer.setSource(_alertsExporter);
    }

    _lifecycleService.start();
  }