@Test(enabled = true)
  public void testReboot() {

    URI vAppRebootUri = URI.create(endpoint + "/vApp/" + vAppId + "/power/action/reboot");

    HttpRequest vAppEntityRequest =
        HttpRequest.builder()
            .method("GET")
            .endpoint(URI.create(endpoint + "/entity/" + vAppUrn))
            .addHeader("Accept", "*/*")
            .addHeader("x-vcloud-authorization", token)
            .addHeader(HttpHeaders.COOKIE, "vcloud-token=" + token)
            .build();

    HttpResponse vAppEntityResponse =
        HttpResponse.builder()
            .payload(
                payloadFromResourceWithContentType(
                    "/vapp/vAppEntity.xml", VCloudDirectorMediaType.ENTITY))
            .statusCode(200)
            .build();

    HttpRequest vAppRebootRequest =
        HttpRequest.builder()
            .method("POST")
            .endpoint(vAppRebootUri)
            .addHeader("Accept", "application/vnd.vmware.vcloud.task+xml")
            .addHeader("x-vcloud-authorization", token)
            .addHeader(HttpHeaders.COOKIE, "vcloud-token=" + token)
            .build();

    HttpResponse vAppRebootResponse =
        HttpResponse.builder()
            .payload(
                payloadFromResourceWithContentType(
                    "/vapp/vAppRebootTask.xml", VCloudDirectorMediaType.TASK))
            .statusCode(200)
            .build();

    VCloudDirectorApi vCloudDirectorApi =
        requestsSendResponses(
            loginRequest, sessionResponse,
            vAppEntityRequest, vAppEntityResponse,
            vAppRebootRequest, vAppRebootResponse);

    Task actual = vCloudDirectorApi.getVAppApi().reboot(vAppUrn);
    Task expected = rebootTask();

    assertEquals(actual, expected);
  }
  @Test
  public void testCorrect() throws SecurityException, NoSuchMethodException {

    HttpRequest request = HttpRequest.builder().method("GET").endpoint("http://momma").build();
    BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:");

    assertEquals(
        binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")),
        HttpRequest.builder()
            .method("GET")
            .endpoint("http://momma")
            .addHeader("prefix:imagename", "foo")
            .addHeader("prefix:serverid", "2")
            .build());
  }
  @Test
  public void testCreatePayload() {

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

    Server.Request.AttachVolumePayload payload =
        Server.Request.attachVolumeBuilder()
            .dataCenterId("datacenter-id")
            .serverId("server-id")
            .volumeId("volume-id")
            .build();

    String actual = binder.createPayload(payload);

    HttpRequest request =
        binder.createRequest(
            HttpRequest.builder().method("POST").endpoint("http://test.com").build(), actual);

    assertEquals(
        request.getEndpoint().getPath(),
        "/rest/v2/datacenters/datacenter-id/servers/server-id/volumes");
    assertNotNull(actual, "Binder returned null payload");

    Json json = injector.getInstance(Json.class);
    String expectedJson =
        json.toJson(
            json.fromJson(expectedPayload, new TypeToken<Map<String, Object>>() {}.getType()));

    assertEquals(actual, expectedJson);
  }
  public void testDescribeVolumesWithNovaEC2Status() {
    ElasticBlockStoreApi client =
        requestsSendResponses(
                describeAvailabilityZonesRequest,
                describeAvailabilityZonesResponse,
                HttpRequest.builder()
                    .method("POST")
                    .endpoint("http://localhost:8773/services/Cloud/")
                    .addHeader("Host", "localhost:8773")
                    .payload(
                        payloadFromStringWithContentType(
                            "Action=DescribeVolumes&Signature=AvRznSzGExM%2Buaj2JJj66wq4v4f%2BakicyLooRDtC0t0%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity",
                            "application/x-www-form-urlencoded"))
                    .build(),
                HttpResponse.builder()
                    .statusCode(200)
                    .payload(payloadFromResource("/nova_ec2_describe_volumes.xml"))
                    .build())
            .getElasticBlockStoreApi()
            .get();

    Set<Volume> expected =
        ImmutableSet.of(
            Volume.builder()
                .status(Volume.Status.AVAILABLE)
                .availabilityZone("nova")
                .region("nova")
                .id("vol-00000007")
                .size(1)
                .attachments(Attachment.builder().region("nova").build())
                .createTime(dateService.iso8601SecondsDateParse("2012-04-10T10:39:52Z"))
                .build());

    assertEquals(client.describeVolumesInRegion("nova"), expected);
  }
  public void testListFloatingIPsWhenResponseIs404() throws Exception {
    HttpRequest list =
        HttpRequest.builder()
            .method("GET")
            .endpoint(
                "https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips")
            .addHeader("Accept", "application/json")
            .addHeader("X-Auth-Token", authToken)
            .build();

    HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();

    NovaApi apiWhenNoServersExist =
        requestsSendResponses(
            keystoneAuthWithUsernameAndPasswordAndTenantName,
            responseWithKeystoneAccess,
            extensionsOfNovaRequest,
            extensionsOfNovaResponse,
            list,
            listResponse);

    assertTrue(
        apiWhenNoServersExist
            .getFloatingIPExtensionForZone("az-1.region-a.geo-1")
            .get()
            .list()
            .isEmpty());
  }
  public void testListArchivesWhenReponseIs2xx() throws Exception {
    ArchiveApi api =
        requestSendsResponse(
                HttpRequest.builder()
                    .method("POST")
                    .endpoint("https://api.glesys.com/archive/list/format/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==")
                    .build(),
                HttpResponse.builder()
                    .statusCode(200)
                    .payload(payloadFromResource("/archive_list.json"))
                    .build())
            .getArchiveApi();

    Set<Archive> expected =
        ImmutableSet.of(
            Archive.builder()
                .username("xxxxx_test1")
                .freeSize("20 GB")
                .totalSize("30 GB")
                .locked(false)
                .build());

    assertEquals(api.list().toSet(), expected);
  }
 @Test(expectedExceptions = IllegalArgumentException.class)
 public void testInvalidTypeInput() {
   BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false"));
   HttpRequest request =
       HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build();
   binder.bindToRequest(request, new Object());
 }
/** @author Adrian Cole */
@Test(groups = "unit", testName = "LocationApiExpectTest")
public class LocationApiExpectTest extends BaseAzureManagementApiExpectTest {

  HttpRequest list =
      HttpRequest.builder()
          .method("GET")
          .endpoint("https://management.core.windows.net/" + subscriptionId + "/locations")
          .addHeader("x-ms-version", "2012-03-01")
          .addHeader("Accept", "application/xml")
          .build();

  public void testListWhenResponseIs2xx() throws Exception {

    HttpResponse listResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResourceWithContentType("/locations.xml", "application"))
            .build();

    AzureManagementApi apiWhenExist = requestSendsResponse(list, listResponse);

    assertEquals(
        apiWhenExist.getLocationApi().list().toString(),
        new ListLocationsTest().expected().toString());
  }

  public void testListWhenResponseIs404() throws Exception {

    HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();

    AzureManagementApi apiWhenDontExist = requestSendsResponse(list, listResponse);

    assertEquals(apiWhenDontExist.getLocationApi().list(), ImmutableSet.of());
  }
}
  public BaseGlanceExpectTest() {
    provider = "openstack-glance";
    keystoneAuthWithUsernameAndPassword =
        KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPasswordAndTenantName(
            identity, credential);
    keystoneAuthWithAccessKeyAndSecretKey =
        KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantName(
            identity, credential);

    authToken = KeystoneFixture.INSTANCE.getAuthToken();
    responseWithKeystoneAccess = KeystoneFixture.INSTANCE.responseWithAccess();
    // now, createContext arg will need tenant prefix
    identity = KeystoneFixture.INSTANCE.getTenantName() + ":" + identity;
    // version negotiation
    versionNegotiationRequest =
        HttpRequest.builder()
            .method("GET")
            .endpoint("https://glance.jclouds.org:9292/")
            .addHeader(RegionToEndpointNegotiateVersion.VERSION_NEGOTIATION_HEADER, "true")
            .build();
    versionNegotiationResponse =
        HttpResponse.builder()
            .statusCode(300)
            .message("HTTP/1.1 300 Multiple Choices")
            .payload(
                payloadFromResourceWithContentType(
                    "/glanceVersionResponse.json", "application/json"))
            .build();
  }
  public void testDeleteAndSaveSnapshotWhenResponseIs2xx() throws Exception {
    HttpRequest delete =
        HttpRequest.builder()
            .method("POST")
            .endpoint("https://rds.us-east-1.amazonaws.com/")
            .addHeader("Host", "rds.us-east-1.amazonaws.com")
            .payload(
                payloadFromStringWithContentType(
                    "Action=DeleteDBInstance"
                        + "&DBInstanceIdentifier=id"
                        + "&FinalDBSnapshotIdentifier=snap"
                        + "&Signature=aKuG1%2FYbZAzUFdAZTjke1LYRfR5JU86UxDt%2BtwdPJwE%3D"
                        + "&SignatureMethod=HmacSHA256"
                        + "&SignatureVersion=2"
                        + "&Timestamp=2009-11-08T15%3A54%3A08.897Z"
                        + "&Version=2012-04-23"
                        + "&AWSAccessKeyId=identity",
                    "application/x-www-form-urlencoded"))
            .build();
    HttpResponse deleteResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResourceWithContentType("/delete_instance.xml", "text/xml"))
            .build();

    RDSApi apiWhenExist = requestSendsResponse(delete, deleteResponse);

    apiWhenExist.getInstanceApi().deleteAndSaveSnapshot("id", "snap");
  }
  @Test
  public void testUpdatePayload() {

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

    Lan.Request.UpdatePayload payload =
        Lan.Request.updatingBuilder()
            .dataCenterId("datacenter-id")
            .id("lan-id")
            .isPublic(false)
            .build();

    String actual = binder.createPayload(payload);

    HttpRequest request =
        binder.createRequest(
            HttpRequest.builder().method("POST").endpoint("http://test.com").build(), actual);

    assertEquals(request.getEndpoint().getPath(), "/rest/v2/datacenters/datacenter-id/lans/lan-id");
    assertNotNull(actual, "Binder returned null payload");

    Json json = injector.getInstance(Json.class);

    HashMap<String, Object> expectedPayload = new HashMap<String, Object>();

    expectedPayload.put("public", false);

    assertEquals(actual, json.toJson(expectedPayload));
  }
  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>");
  }
  @Test
  public void testUpdatePayload() {

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

    FirewallRule.Request.UpdatePayload payload =
        FirewallRule.Request.updatingBuilder()
            .dataCenterId("datacenter-id")
            .serverId("server-id")
            .nicId("nic-id")
            .id("id")
            .name("apache-firewall")
            .build();

    String actual = binder.createPayload(payload);

    HttpRequest request =
        binder.createRequest(
            HttpRequest.builder().method("POST").endpoint("http://test.com").build(), actual);

    assertEquals(
        request.getEndpoint().getPath(),
        "/rest/v2/datacenters/datacenter-id/servers/server-id/nics/nic-id/firewallrules/id");
    assertNotNull(actual, "Binder returned null payload");

    Json json = injector.getInstance(Json.class);

    HashMap<String, Object> expectedPayload = new HashMap<String, Object>();

    expectedPayload.put("name", "apache-firewall");

    assertEquals(actual, json.toJson(expectedPayload));
  }
  private void assertCodeMakes(
      String method,
      URI uri,
      int statusCode,
      String message,
      String contentType,
      String content,
      Class<? extends Exception> expected) {

    SoftLayerErrorHandler function =
        Guice.createInjector().getInstance(SoftLayerErrorHandler.class);

    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();
    HttpResponse response =
        HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();
    response.getPayload().getContentMetadata().setContentType(contentType);

    expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();
    command.setException(classEq(expected));

    replay(command);

    function.handleError(command, response);

    verify(command);
  }
  public void testListServersWhenResponseIs2xx() throws Exception {
    HttpRequest listServers =
        HttpRequest.builder()
            .method("GET")
            .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers")
            .addHeader("Accept", "application/json")
            .addHeader("X-Auth-Token", authToken)
            .build();

    HttpResponse listServersResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResource("/server_list.json"))
            .build();

    NovaApi apiWhenServersExist =
        requestsSendResponses(
            keystoneAuthWithAccessKeyAndSecretKeyAndTenantId,
            responseWithKeystoneAccess,
            listServers,
            listServersResponse);

    assertEquals(
        apiWhenServersExist.getConfiguredZones(),
        ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1"));

    assertEquals(
        apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(),
        new ParseServerListTest().expected().toString());
  }
  public void testAllocateWithPoolNameWhenResponseIs2xx() throws Exception {
    HttpRequest createFloatingIP =
        HttpRequest.builder()
            .method("POST")
            .endpoint(
                "https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips")
            .addHeader("Accept", "application/json")
            .addHeader("X-Auth-Token", authToken)
            .payload(payloadFromStringWithContentType("{\"pool\":\"myPool\"}", "application/json"))
            .build();

    HttpResponse createFloatingIPResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResource("/floatingip_details.json"))
            .build();

    NovaApi apiWhenFloatingIPsExist =
        requestsSendResponses(
            keystoneAuthWithUsernameAndPasswordAndTenantName,
            responseWithKeystoneAccess,
            extensionsOfNovaRequest,
            extensionsOfNovaResponse,
            createFloatingIP,
            createFloatingIPResponse);

    assertEquals(
        apiWhenFloatingIPsExist
            .getFloatingIPExtensionForZone("az-1.region-a.geo-1")
            .get()
            .allocateFromPool("myPool")
            .toString(),
        new ParseFloatingIPTest().expected().toString());
  }
  public void testAllocateWhenResponseIs404() throws Exception {
    HttpRequest createFloatingIP =
        HttpRequest.builder()
            .method("POST")
            .endpoint(
                "https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips")
            .addHeader("Accept", "application/json")
            .addHeader("X-Auth-Token", authToken)
            .payload(payloadFromStringWithContentType("{}", "application/json"))
            .build();

    HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(404).build();

    NovaApi apiWhenNoServersExist =
        requestsSendResponses(
            keystoneAuthWithUsernameAndPasswordAndTenantName,
            responseWithKeystoneAccess,
            extensionsOfNovaRequest,
            extensionsOfNovaResponse,
            createFloatingIP,
            createFloatingIPResponse);

    assertNull(
        apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().create());
  }
  public void testListTypesByNamesWhenResponseIs2xx() throws Exception {
    HttpRequest listWithOptions =
        HttpRequest.builder()
            .method("POST")
            .endpoint("https://elasticloadbalancing.us-east-1.amazonaws.com/")
            .addHeader("Host", "elasticloadbalancing.us-east-1.amazonaws.com")
            .payload(
                payloadFromStringWithContentType(
                    "Action=DescribeLoadBalancerPolicyTypes"
                        + "&PolicyTypeNames.member.1=moo"
                        + "&Signature=cX8twwn2E6%2B7V3CGZ4ac69NhyolJLsV1nzpQl3wQXW8%3D"
                        + "&SignatureMethod=HmacSHA256"
                        + "&SignatureVersion=2"
                        + "&Timestamp=2009-11-08T15%3A54%3A08.897Z"
                        + "&Version=2012-06-01"
                        + "&AWSAccessKeyId=identity",
                    "application/x-www-form-urlencoded"))
            .build();

    HttpResponse listWithOptionsResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResourceWithContentType("/describe_policy_types.xml", "text/xml"))
            .build();

    ELBApi apiWhenWithOptionsExist = requestSendsResponse(listWithOptions, listWithOptionsResponse);

    assertEquals(
        apiWhenWithOptionsExist.getPolicyApi().listTypes(ImmutableSet.of("moo")).toString(),
        new DescribeLoadBalancerPolicyTypesResponseTest().expected().toString());
  }
  public void testCreateDomainWhenResponseIs2xx() {
    GlobalDomainClient client =
        requestSendsResponse(
            HttpRequest.builder()
                .method("GET")
                .endpoint(
                    URI.create(
                        "http://localhost:8080/client/api?response=json&command=createDomain&"
                            + "name=test&apiKey=identity&signature=6cxzEo7h63G0hgTTMLm4lGsSDK8%3D"))
                .addHeader("Accept", "application/json")
                .build(),
            HttpResponse.builder()
                .statusCode(200)
                .payload(payloadFromResource("/createdomainresponse.json"))
                .build());

    assertEquals(
        client.createDomain("test"),
        Domain.builder()
            .id("10")
            .name("test")
            .level(1)
            .parentDomainId("1")
            .parentDomainName("ROOT")
            .hasChild(false)
            .build());
  }
  public void testCreateKeyWhenResponseIs202() throws Exception {
    HttpRequest create =
        HttpRequest.builder()
            .method("POST")
            .endpoint(URI.create("https://api.joyentcloud.com/my/keys"))
            .headers(
                ImmutableMultimap.<String, String>builder()
                    .put("X-Api-Version", "~6.5")
                    .put("Accept", "application/json")
                    .put("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==")
                    .build())
            .payload(
                payloadFromStringWithContentType(
                    "{\"name\":\"rsa\",\"key\":\"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...\"}",
                    "application/json"))
            .build();

    HttpResponse createResponse =
        HttpResponse.builder()
            .statusCode(202)
            .message("HTTP/1.1 202 Accepted")
            .payload(
                payloadFromResourceWithContentType("/key.json", "application/json; charset=UTF-8"))
            .build();

    JoyentCloudClient clientWithNewKey =
        requestsSendResponses(getDatacenters, getDatacentersResponse, create, createResponse);

    assertEquals(
        clientWithNewKey.getKeyClient().create(new ParseKeyTest().expected()).toString(),
        new ParseKeyTest().expected().toString());
  }
  public void testUpdateDomainWhenResponseIs2xx() {
    GlobalDomainClient client =
        requestSendsResponse(
            HttpRequest.builder()
                .method("GET")
                .endpoint(
                    URI.create(
                        "http://localhost:8080/client/api?response=json&"
                            + "command=updateDomain&id=10&name=test-2&apiKey=identity&signature=5t1eUf2Eyf%2FaB6qt%2BqIj%2BmcwFIo%3D"))
                .addHeader("Accept", "application/json")
                .build(),
            HttpResponse.builder()
                .statusCode(200)
                .payload(payloadFromResource("/updatedomainresponse.json"))
                .build());

    assertEquals(
        client.updateDomain("10", name("test-2")),
        Domain.builder()
            .id("10")
            .name("test-2")
            .level(1)
            .parentDomainId("1")
            .parentDomainName("ROOT")
            .hasChild(false)
            .build());
  }
  public void testListWithOptionsWhenResponseIs2xx() throws Exception {
    HttpRequest listWithOptions =
        HttpRequest.builder()
            .method("POST")
            .endpoint("https://elasticloadbalancing.us-east-1.amazonaws.com/")
            .addHeader("Host", "elasticloadbalancing.us-east-1.amazonaws.com")
            .payload(
                payloadFromStringWithContentType(
                    "Action=DescribeLoadBalancerPolicies"
                        + "&LoadBalancerName=moo"
                        + "&Signature=c8PG1b5wI5YMU0motVEo5Mz7d5w8gy8u51kfCR6SnRI%3D"
                        + "&SignatureMethod=HmacSHA256"
                        + "&SignatureVersion=2"
                        + "&Timestamp=2009-11-08T15%3A54%3A08.897Z"
                        + "&Version=2012-06-01"
                        + "&AWSAccessKeyId=identity",
                    "application/x-www-form-urlencoded"))
            .build();

    HttpResponse listWithOptionsResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResourceWithContentType("/describe_policies.xml", "text/xml"))
            .build();

    ELBApi apiWhenWithOptionsExist = requestSendsResponse(listWithOptions, listWithOptionsResponse);

    assertEquals(
        apiWhenWithOptionsExist.getPolicyApi().list(loadBalancerName("moo")).toString(),
        new DescribeLoadBalancerPoliciesResponseTest().expected().toString());
  }
 @Test(expectedExceptions = IllegalArgumentException.class)
 public void testMustBeMap() {
   BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:");
   HttpRequest request = HttpRequest.builder().method("POST").endpoint("http://localhost").build();
   ;
   binder.bindToRequest(request, new File("foo"));
 }
  public void testListWithOptionsWhenResponseIs2xx() throws Exception {
    HttpRequest listWithOptions =
        HttpRequest.builder()
            .method("POST")
            .endpoint("https://rds.us-east-1.amazonaws.com/")
            .addHeader("Host", "rds.us-east-1.amazonaws.com")
            .payload(
                payloadFromStringWithContentType(
                    "Action=DescribeDBInstances"
                        + "&Marker=MARKER"
                        + "&Signature=TFW8vaU2IppmBey0ZHttbWz4rMFh%2F5ACWl6Xyt58sQU%3D"
                        + "&SignatureMethod=HmacSHA256"
                        + "&SignatureVersion=2"
                        + "&Timestamp=2009-11-08T15%3A54%3A08.897Z"
                        + "&Version=2012-04-23"
                        + "&AWSAccessKeyId=identity",
                    "application/x-www-form-urlencoded"))
            .build();

    HttpResponse listWithOptionsResponse =
        HttpResponse.builder()
            .statusCode(200)
            .payload(payloadFromResourceWithContentType("/describe_instances.xml", "text/xml"))
            .build();

    RDSApi apiWhenWithOptionsExist = requestSendsResponse(listWithOptions, listWithOptionsResponse);

    assertEquals(
        apiWhenWithOptionsExist.getInstanceApi().list(afterMarker("MARKER")).toString(),
        new DescribeDBInstancesResponseTest().expected().toString());
  }
 public void testBindEmptyArray() throws IOException {
   BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false"));
   HttpRequest request =
       HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build();
   request = binder.bindToRequest(request, new VolumeManagementDto[] {});
   assertPayloadEquals(request.getPayload(), withHeader("<links/>"), LinksDto.class);
 }
 public static <T> HttpRequest cleanRequest(HttpRequest returnVal) {
   checkNotNull(returnVal, "http request");
   for (HttpRequestFilter filter : returnVal.getFilters()) returnVal = filter.filter(returnVal);
   return HttpRequest.builder()
       .method(returnVal.getMethod())
       .endpoint(returnVal.getEndpoint())
       .headers(returnVal.getHeaders())
       .payload(returnVal.getPayload())
       .build();
 }
  /** Test that BlobRequestSigner creates expected URIs. */
  public void testBlobRequestSigner() throws Exception {
    String containerName = "container";
    String blobName = "blob";
    URI endPoint =
        new URI(
            "http",
            "localhost",
            String.format("/transient/%s/%s", containerName, blobName),
            /*fragment=*/ null);
    BlobRequestSigner signer = context.getSigner();
    HttpRequest request;
    HttpRequest expected;

    request = signer.signGetBlob(containerName, blobName);
    expected =
        HttpRequest.builder()
            .method("GET")
            .endpoint(endPoint)
            .headers(request.getHeaders())
            .build();
    assertEquals(expected, request);

    request = signer.signRemoveBlob(containerName, blobName);
    expected =
        HttpRequest.builder()
            .method("DELETE")
            .endpoint(endPoint)
            .headers(request.getHeaders())
            .build();
    assertEquals(expected, request);

    Blob blob = blobStore.blobBuilder(blobName).forSigning().build();
    request = signer.signPutBlob(containerName, blob);
    expected =
        HttpRequest.builder()
            .method("PUT")
            .endpoint(endPoint)
            .headers(request.getHeaders())
            .payload(new PhantomPayload())
            .build();
    assertEquals(expected, request);
  }
  public void testApplyInputStream() throws IOException {

    HttpRequest request = HttpRequest.builder().method("GET").endpoint("http://test").build();
    BindNoBucketLoggingToXmlPayload binder =
        injector.getInstance(BindNoBucketLoggingToXmlPayload.class);

    request = binder.bindToRequest(request, "bucket");
    assertEquals(
        request.getPayload().getRawContent(),
        "<BucketLoggingStatus xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"/>");
  }
  public void testGetArchiveAllowedArguments4xxWhenResponseIs2xx() throws Exception {
    ArchiveApi api =
        requestSendsResponse(
                HttpRequest.builder()
                    .method("GET")
                    .endpoint("https://api.glesys.com/archive/allowedarguments/format/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==")
                    .build(),
                HttpResponse.builder().statusCode(404).build())
            .getArchiveApi();

    assertNull(api.getAllowedArguments());
  }
  public void testListArchivesWhenResponseIs4xxReturnsEmpty() {
    ArchiveApi api =
        requestSendsResponse(
                HttpRequest.builder()
                    .method("POST")
                    .endpoint("https://api.glesys.com/archive/list/format/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==")
                    .build(),
                HttpResponse.builder().statusCode(404).build())
            .getArchiveApi();

    assertTrue(api.list().isEmpty());
  }