public void testListVirtualGuests() throws SecurityException, NoSuchMethodException, IOException { Method method = VirtualGuestAsyncClient.class.getMethod("listVirtualGuests"); HttpRequest httpRequest = processor.createRequest(method); assertRequestLineEquals( httpRequest, "GET https://api.softlayer.com/rest/v3/SoftLayer_Account/VirtualGuests.json?objectMask=virtualGuests.powerState%3BvirtualGuests.networkVlans%3BvirtualGuests.operatingSystem.passwords%3BvirtualGuests.datacenter%3BvirtualGuests.billingItem HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertPayloadEquals(httpRequest, null, null, false); // now make sure request filters apply by replaying httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); httpRequest = Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); assertRequestLineEquals( httpRequest, "GET https://api.softlayer.com/rest/v3/SoftLayer_Account/VirtualGuests.json?objectMask=virtualGuests.powerState%3BvirtualGuests.networkVlans%3BvirtualGuests.operatingSystem.passwords%3BvirtualGuests.datacenter%3BvirtualGuests.billingItem HTTP/1.1"); // for example, using basic authentication, we should get "only one" // header assertNonPayloadHeadersEqual( httpRequest, "Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); assertPayloadEquals(httpRequest, null, null, false); assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); checkFilters(httpRequest); }
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>"); }
private HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) { // Update the 'DATE' header String dateString = request.getFirstHeaderOrNull(HttpHeaders.DATE); if (dateString == null) { dateString = timeStampProvider.get(); } Date date = dateService.rfc1123DateParse(dateString); String expiration = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(date.getTime()) + timeInSeconds); HttpRequest.Builder<?> builder = request.toBuilder().replaceHeader(HttpHeaders.DATE, expiration); String stringToSign = authSigner.createStringToSign(builder.build()); // We MUST encode the signature because addQueryParam internally _always_ decodes values // and if we don't encode the signature here, the decoding may change the signature. For e.g. // any '+' characters in the signature will be converted to space ' ' on decoding. String signature = authSigner.sign(stringToSign); try { signature = URLEncoder.encode(signature, Charsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Bad encoding on input: " + signature, e); } HttpRequest ret = builder .addQueryParam(HttpHeaders.EXPIRES, expiration) .addQueryParam("AWSAccessKeyId", identity) // Signature MUST be the last parameter because if it isn't, even encoded '+' values in // the // signature will be converted to a space by a subsequent addQueryParameter. // See HttpRequestTest.testAddBase64AndUrlEncodedQueryParams for more details. .addQueryParam(TEMPORARY_SIGNATURE_PARAM, signature) .build(); return ret; }
@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)); }
@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 HttpRequest sign(HttpRequest request) { // Grab the needed data to build the signature Multimap<String, String> canonicalizedHeadersMap = buildCanonicalizedHeadersMap(request); String canonicalizedHeadersString = buildCanonicalizedHeadersString(canonicalizedHeadersMap); String signedHeaders = buildSignedHeaders(canonicalizedHeadersMap); String date = request.getFirstHeaderOrNull(GlacierHeaders.ALTERNATE_DATE); String dateWithoutTimestamp = formatDateWithoutTimestamp(date); String method = request.getMethod(); String endpoint = request.getEndpoint().getRawPath(); String credentialScope = buildCredentialScope(dateWithoutTimestamp); HashCode hashedPayload = buildHashedPayload(request); // Task 1: Create a Canonical Request For Signature Version 4. HashCode hashedCanonicalRequest = buildHashedCanonicalRequest( method, endpoint, hashedPayload, canonicalizedHeadersString, signedHeaders); // Task 2: Create a String to Sign for Signature Version 4. String stringToSign = createStringToSign(date, credentialScope, hashedCanonicalRequest); // Task 3: Calculate the AWS Signature Version 4. String signature = buildSignature(dateWithoutTimestamp, stringToSign); // Sign the request String authHeader = buildAuthHeader(identity, credentialScope, signedHeaders, signature); request = request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION, authHeader).build(); return request; }
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); }
@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); }
@Test public void test401ShouldRetry4Times() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, Access> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(command.getCurrentRequest()).andReturn(request).anyTimes(); expect(request.getHeaders()).andStubReturn(null); cache.invalidateAll(); expectLastCall().anyTimes(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("")).anyTimes(); expect(response.getStatusCode()).andReturn(401).anyTimes(); replay(command, request, response, cache); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); for (int i = 0; i < RetryOnRenew.NUM_RETRIES - 1; ++i) { assertTrue(retry.shouldRetryRequest(command, response), "Expected retry to succeed"); } assertFalse( retry.shouldRetryRequest(command, response), "Expected retry to fail on attempt " + RetryOnRenew.NUM_RETRIES); verify(command, response, cache); }
public HttpResponse call() throws Exception { HttpResponse response = null; for (; ; ) { HttpRequest request = command.getCurrentRequest(); Q nativeRequest = null; try { for (HttpRequestFilter filter : request.getFilters()) { request = filter.filter(request); } checkRequestHasContentLengthOrChunkedEncoding( request, "After filtering, the request has neither chunked encoding nor content length: " + request); logger.debug("Sending request %s: %s", request.hashCode(), request.getRequestLine()); wirePayloadIfEnabled(wire, request); utils.logRequest(headerLog, request, ">>"); nativeRequest = convert(request); response = invoke(nativeRequest); logger.debug("Receiving response %s: %s", request.hashCode(), response.getStatusLine()); utils.logResponse(headerLog, response, "<<"); if (response.getPayload() != null && wire.enabled()) wire.input(response); int statusCode = response.getStatusCode(); if (statusCode >= 300) { if (shouldContinue(response)) continue; else break; } else { break; } } catch (Exception e) { IOException ioe = Throwables2.getFirstThrowableOfType(e, IOException.class); if (ioe != null) { if (ioe instanceof SSLException) { command.setException( new AuthorizationException( e.getMessage() + " connecting to " + command.getCurrentRequest().getRequestLine(), e)); break; } else if (ioRetryHandler.shouldRetryRequest(command, ioe)) { continue; } } command.setException( new HttpResponseException( e.getMessage() + " connecting to " + command.getCurrentRequest().getRequestLine(), command, null, e)); break; } finally { cleanup(nativeRequest); } } if (command.getException() != null) throw command.getException(); return response; }
private void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) { buffer .append( utils.valueOrEmpty( request.getPayload() == null ? null : request.getPayload().getContentMetadata().getContentType())) .append("\n"); }
public void testAuth() throws UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException { BasicAuthentication filter = new BasicAuthentication(USER, PASSWORD, new JCECrypto(null)); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); filter.filter(request); assertEquals( request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); }
public static void logRequest(Logger logger, HttpRequest request, String prefix) { if (logger.isDebugEnabled()) { logger.debug("%s %s", prefix, request.getRequestLine().toString()); for (Entry<String, String> header : request.getHeaders().entries()) { if (header.getKey() != null) logger.debug("%s %s: %s", prefix, header.getKey(), header.getValue()); } } }
public void testGood() { AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); object.setPayload(payload); object.getUserMetadata().getListableMetadata().put("apple", "bear"); object.getUserMetadata().getListableMetadata().put("sushi", "king"); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); request = binder.bindToRequest(request, object); assertEquals(request.getFirstHeaderOrNull("x-emc-listable-meta"), "apple=bear,sushi=king"); }
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 testSignRemoveBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { HttpRequest request = signer.signRemoveBlob("container", "name"); assertRequestLineEquals(request, "DELETE http://storageUrl/container/name HTTP/1.1"); assertNonPayloadHeadersEqual(request, "X-Auth-Token: testtoken\n"); assertPayloadEquals(request, null, null, false); assertEquals(request.getFilters().size(), 0); }
@VisibleForTesting void appendHttpHeaders(HttpRequest request, StringBuilder toSign) { // Only the value is used, not the header // name. If a request does not include the header, this is an empty string. for (String header : new String[] {"Range"}) toSign .append(utils.valueOrEmpty(request.getHeaders().get(header)).toLowerCase()) .append("\n"); // Standard HTTP header, in UTC format. Only the date value is used, not the header name. toSign.append(request.getHeaders().get(HttpHeaders.DATE).iterator().next()).append("\n"); }
public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { HttpRequest request = signer.signGetBlob("container", "name"); assertRequestLineEquals( request, "GET https://accesspoint.atmosonline.com/rest/namespace/container/name HTTP/1.1"); assertNonPayloadHeadersEqual( request, "Accept: */*\nDate: Thu, 05 Jun 2008 16:38:19 GMT\nx-emc-signature: Mhe5tqaKv04BlMvEjreNKkHHxzk=\nx-emc-uid: identity\n"); assertPayloadEquals(request, null, null, false); assertEquals(request.getFilters().size(), 0); }
@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()); }
public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method( InstanceApi.class, "setInstanceInitiatedShutdownBehaviorForInstanceInRegion", String.class, String.class, InstanceInitiatedShutdownBehavior.class); GeneratedHttpRequest request = processor.createRequest( method, Lists.<Object>newArrayList(null, "1", InstanceInitiatedShutdownBehavior.TERMINATE)); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals( request, setInstanceInitiatedShutdownBehavior.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertFallbackClassEquals(method, null); checkFilters(request); }
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 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()); }
@Override public HttpRequest filter(HttpRequest request) throws HttpException { return request .toBuilder() .replaceHeader(AuthHeaders.AUTH_TOKEN, authTokenProvider.get()) .build(); }
public void testAuthorizeIngressICMPToSecurityGroups() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = Invokable.from( SecurityGroupAsyncClient.class.getMethod( "authorizeIngressICMPToSecurityGroups", String.class, int.class, int.class, Multimap.class, AccountInDomainOptions[].class)); GeneratedHttpRequest httpRequest = processor.createRequest( method, ImmutableList.<Object>of( 2, 22, 22, ImmutableMultimap.of("adrian", "group1", "adrian", "group2", "bob", "group1"))); assertRequestLineEquals(httpRequest, authorizeSecurityGroupIngress2.getRequestLine()); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertPayloadEquals(httpRequest, null, null, false); assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); assertSaxResponseParserClassEquals(method, null); assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); checkFilters(httpRequest); }
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 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()); }
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"); }
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 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(); }