本文整理了Java中org.jclouds.rest.HttpClient
类的一些代码示例,展示了HttpClient
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpClient
类的具体详情如下:
包路径:org.jclouds.rest.HttpClient
类名称:HttpClient
[英]Simple client
[中]简单客户端
代码示例来源:origin: org.apache.jclouds.labs/openstack-glance
.method("GET").endpoint(baseEndpointUri)
.addHeader(VERSION_NEGOTIATION_HEADER, "true").build();
InputStream response = client.invoke(negotiationRequest).getPayload().openStream();
VersionsJsonResponse versions = json.fromJson(Strings2.toStringAndClose(response), VersionsJsonResponse.class);
for (VersionsJsonResponse.Version version : versions.versions) {
代码示例来源:origin: jclouds/legacy-jclouds
public static void checkHttpGet(HttpClient client, NodeMetadata node, int port) {
for (int i = 0; i < 5; i++)
try {
assert client.get(URI.create(String.format("http://%s:%d", get(node.getPublicAddresses(), 0), port))) != null;
break;
} catch (UndeclaredThrowableException e) {
assertEquals(e.getCause().getClass(), TimeoutException.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
}
}
代码示例来源:origin: jclouds/legacy-jclouds
@Test(enabled = true, dependsOnMethods = "testRegisterTemplate")
public void testExtractTemplate() throws Exception {
// Initiate the extraction and wait for it to complete
AsyncCreateResponse response = client.getTemplateClient().extractTemplate(registeredTemplate.getId(), ExtractMode.HTTP_DOWNLOAD, registeredTemplate.getZoneId());
assertTrue(jobComplete.apply(response.getJobId()), registeredTemplate.toString());
// Get the result
AsyncJob<TemplateExtraction> asyncJob = client.getAsyncJobClient().getAsyncJob(response.getJobId());
TemplateExtraction extract = asyncJob.getResult();
assertNotNull(extract);
// Check that the URL can be retrieved
String extractUrl = extract.getUrl();
assertNotNull(extractUrl);
URI uri = new URI(URLDecoder.decode(extractUrl, "utf-8"));
assertTrue(cloudStackContext.utils().http().exists(uri), "does not exist: " + uri);
}
代码示例来源:origin: apache/jclouds
client.post(server.getUrl("/").toURI(), fakePayload);
fail("Should have errored since we didn't sent that much data!");
} catch (HttpResponseException expected) {
代码示例来源:origin: org.apache.jclouds.labs/abiquo
@Override
public String apply(final Credentials input) {
logger.info(">> Requesting an authentication token for user: %s...", input.identity);
HttpResponse response = http.invoke(HttpRequest.builder() //
.method("GET") //
.endpoint(URI.create(provider.getEndpoint() + "/login")) //
.addHeader(AUTHORIZATION, basic(input.identity, input.credential)) //
.build());
Optional<HttpCookie> token = readAuthenticationToken(response);
if (!token.isPresent()) {
throw new AuthorizationException("Could not obtain a new authentication token");
}
return token.get().getValue();
}
代码示例来源:origin: apache/jclouds
public static void checkHttpGet(HttpClient client, NodeMetadata node, int port) {
for (int i = 0; i < 5; i++)
try {
assert client.get(URI.create(String.format("http://%s:%d", get(node.getPublicAddresses(), 0), port))) != null;
break;
} catch (UndeclaredThrowableException e) {
assertEquals(e.getCause().getClass(), TimeoutException.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
}
}
代码示例来源:origin: apache/jclouds
@Test(enabled = true, dependsOnMethods = "testRegisterTemplate")
public void testExtractTemplate() throws Exception {
// Initiate the extraction and wait for it to complete
AsyncCreateResponse response = client.getTemplateApi().extractTemplate(registeredTemplate.getId(), ExtractMode.HTTP_DOWNLOAD, registeredTemplate.getZoneId());
assertTrue(jobComplete.apply(response.getJobId()), registeredTemplate.toString());
// Get the result
AsyncJob<TemplateExtraction> asyncJob = client.getAsyncJobApi().getAsyncJob(response.getJobId());
TemplateExtraction extract = asyncJob.getResult();
assertNotNull(extract);
// Check that the URL can be retrieved
String extractUrl = extract.getUrl();
assertNotNull(extractUrl);
URI uri = new URI(URLDecoder.decode(extractUrl, "utf-8"));
assertTrue(cloudStackContext.utils().http().exists(uri), "does not exist: " + uri);
}
代码示例来源:origin: org.apache.jclouds.karaf/commands
/**
* Writes to the {@link org.jclouds.blobstore.domain.Blob} using an InputStream.
*
* @param blobStore
* @param bucket
* @param blobName
* @param blob
* @param options
*/
public void write(BlobStore blobStore, String bucket, String blobName, Blob blob, PutOptions options, boolean signedRequest) throws Exception {
if (blobName.contains("/")) {
String directory = BlobStoreUtils.parseDirectoryFromPath(blobName);
if (!Strings.isNullOrEmpty(directory)) {
blobStore.createDirectory(bucket, directory);
}
}
if (signedRequest) {
BlobStoreContext context = blobStore.getContext();
HttpRequest request = context.getSigner().signPutBlob(bucket, blob);
HttpClient httpClient = context.utils().http();
HttpResponse response = httpClient.invoke(request);
int statusCode = response.getStatusCode();
if (statusCode != 200 && statusCode != 201) {
throw new IOException(response.getStatusLine());
}
} else {
blobStore.putBlob(bucket, blob, options);
}
}
代码示例来源:origin: jclouds/legacy-jclouds-chef
@Test(dependsOnMethods = "testCanUpdateRunList")
public void testRunNodesWithBootstrap() throws IOException {
Statement bootstrap = view.getChefService().createBootstrapScriptForGroup(group);
try {
nodes = computeContext.getComputeService().createNodesInGroup(group, 1, runScript(bootstrap));
} catch (RunNodesException e) {
nodes = concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet());
}
for (NodeMetadata node : nodes) {
URI uri = URI.create("http://" + getLast(node.getPublicAddresses()));
InputStream content = computeContext.utils().http().get(uri);
String string = Strings2.toStringAndClose(content);
assert string.indexOf("It works!") >= 0 : string;
}
}
代码示例来源:origin: apache/jclouds
public void signatureV4() {
Supplier<Credentials> accessAndSecretKey = Suppliers.ofInstance(new Credentials(identity, credential));
FormSignerV4 filter = new FormSignerV4(apiVersion, accessAndSecretKey, timestamp, serviceAndRegion);
HttpRequest request = filter.filter(sampleRequest);
assertEquals(api.utils().http().invoke(request).getStatusCode(), 200);
}
代码示例来源:origin: apache/jclouds
@Test(groups = "live")
public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException {
final String containerName = getScratchContainerName();
try {
view.getBlobStore().createContainerInLocation(null, containerName, publicRead());
assertConsistencyAwareContainerExists(containerName);
defaultLocation = Iterables.find(view.getBlobStore().list(), new Predicate<StorageMetadata>() {
@Override
public boolean apply(@Nullable StorageMetadata input) {
return input.getName().equals(containerName);
}
}).getLocation();
view.getBlobStore().putBlob(containerName,
view.getBlobStore().blobBuilder("hello").payload(TEST_STRING).build());
assertConsistencyAwareContainerSize(containerName, 1);
BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, "hello");
assertNotNull(metadata.getPublicUri(), metadata.toString());
SocketOpen socketOpen = context.utils().injector().getInstance(SocketOpen.class);
Predicate<HostAndPort> socketTester = retry(socketOpen, 60, 5, SECONDS);
int port = metadata.getPublicUri().getPort();
HostAndPort hostAndPort = HostAndPort.fromParts(metadata.getPublicUri().getHost(), port != -1 ? port : 80);
assertTrue(socketTester.apply(hostAndPort), metadata.getPublicUri().toString());
assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), TEST_STRING);
} finally {
// this container is now public, so we can't reuse it directly
recycleContainerAndAddToPool(containerName);
}
}
代码示例来源:origin: apache/jclouds
public void signatureV4_session() {
SessionCredentials creds = api.getApi().createTemporaryCredentials(durationSeconds(MINUTES.toSeconds(15)));
Supplier<Credentials> sessionToken = Suppliers.<Credentials>ofInstance(creds);
FormSignerV4 filter = new FormSignerV4(apiVersion, sessionToken, timestamp, serviceAndRegion);
HttpRequest request = filter.filter(sampleRequest);
assertEquals(api.utils().http().invoke(request).getStatusCode(), 200);
}
}
代码示例来源:origin: jclouds/legacy-jclouds
private void runCreateContainerInLocation(String payload, Location nonDefault) throws InterruptedException,
IOException {
String blobName = "hello";
BlobStore blobStore = view.getBlobStore();
final String containerName = getScratchContainerName();
try {
Logger.getAnonymousLogger().info(
String.format("creating public container %s in location %s", containerName, nonDefault.getId()));
blobStore.createContainerInLocation(nonDefault, containerName, publicRead());
assertConsistencyAwareContainerExists(containerName);
assertConsistencyAwareContainerInLocation(containerName, nonDefault);
blobStore.putBlob(containerName, blobStore.blobBuilder(blobName).payload(payload).build());
assertConsistencyAwareContainerSize(containerName, 1);
BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, blobName);
assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), payload);
assertConsistencyAwareBlobInLocation(containerName, blobName, nonDefault);
} finally {
// this container is now public, so we can't reuse it directly
recycleContainer(containerName);
}
}
代码示例来源:origin: apache/jclouds
@Test(groups = { "integration", "live" })
public void testSetBlobAccess() throws Exception {
BlobStore blobStore = view.getBlobStore();
String containerName = getContainerName();
String blobName = "set-access-blob-name";
try {
addBlobToContainer(containerName, blobName, blobName, MediaType.TEXT_PLAIN);
assertThat(blobStore.getBlobAccess(containerName, blobName)).isEqualTo(BlobAccess.PRIVATE);
blobStore.setBlobAccess(containerName, blobName, BlobAccess.PUBLIC_READ);
assertThat(blobStore.getBlobAccess(containerName, blobName)).isEqualTo(BlobAccess.PUBLIC_READ);
// test that blob is anonymously readable
HttpRequest request = view.getSigner().signGetBlob(containerName, blobName).toBuilder()
.replaceQueryParams(ImmutableMap.<String, String>of()).build();
HttpResponse response = view.utils().http().invoke(request);
assertThat(response.getStatusCode()).isEqualTo(200);
blobStore.setBlobAccess(containerName, blobName, BlobAccess.PRIVATE);
assertThat(blobStore.getBlobAccess(containerName, blobName)).isEqualTo(BlobAccess.PRIVATE);
} finally {
returnContainer(containerName);
}
}
代码示例来源:origin: apache/jclouds
private void runCreateContainerInLocation(String payload, Location nonDefault) throws InterruptedException,
IOException {
String blobName = "hello";
BlobStore blobStore = view.getBlobStore();
final String containerName = getScratchContainerName();
try {
Logger.getAnonymousLogger().info(
String.format("creating public container %s in location %s", containerName, nonDefault.getId()));
blobStore.createContainerInLocation(nonDefault, containerName, publicRead());
assertConsistencyAwareContainerExists(containerName);
assertConsistencyAwareContainerInLocation(containerName, nonDefault);
blobStore.putBlob(containerName, blobStore.blobBuilder(blobName).payload(payload).build());
assertConsistencyAwareContainerSize(containerName, 1);
BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, blobName);
assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), payload);
assertConsistencyAwareBlobInLocation(containerName, blobName, nonDefault);
} finally {
// this container is now public, so we can't reuse it directly
recycleContainerAndAddToPool(containerName);
}
}
}
代码示例来源:origin: apache/jclouds
HttpResponse response = client.invoke(request);
assertEquals(response.getStatusCode(), 200);
response = client.invoke(request);
assertEquals(response.getStatusCode(), 200);
response = client.invoke(request);
assertEquals(response.getStatusCode(), 200);
response = client.invoke(request);
assertEquals(response.getStatusCode(), 200);
代码示例来源:origin: jclouds/legacy-jclouds
@Test(groups = "live")
public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException {
final String containerName = getScratchContainerName();
try {
view.getBlobStore().createContainerInLocation(null, containerName, publicRead());
assertConsistencyAwareContainerExists(containerName);
defaultLocation = Iterables.find(view.getBlobStore().list(), new Predicate<StorageMetadata>() {
@Override
public boolean apply(@Nullable StorageMetadata input) {
return input.getName().equals(containerName);
}
}).getLocation();
view.getBlobStore().putBlob(containerName,
view.getBlobStore().blobBuilder("hello").payload(TEST_STRING).build());
assertConsistencyAwareContainerSize(containerName, 1);
BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, "hello");
assert metadata.getPublicUri() != null : metadata;
assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), TEST_STRING);
} finally {
// this container is now public, so we can't reuse it directly
recycleContainer(containerName);
}
}
代码示例来源:origin: apache/jclouds
@Test(groups = { "integration", "live" })
public void testSetContainerAccess() throws Exception {
BlobStore blobStore = view.getBlobStore();
String containerName = getContainerName();
try {
assertThat(blobStore.getContainerAccess(containerName)).isEqualTo(ContainerAccess.PRIVATE);
blobStore.setContainerAccess(containerName, ContainerAccess.PUBLIC_READ);
assertThat(blobStore.getContainerAccess(containerName)).isEqualTo(ContainerAccess.PUBLIC_READ);
String blobName = "blob";
blobStore.putBlob(containerName, blobStore.blobBuilder(blobName).payload("").build());
// test that blob is anonymously readable
HttpRequest request = view.getSigner().signGetBlob(containerName, blobName).toBuilder()
.replaceQueryParams(ImmutableMap.<String, String>of()).build();
HttpResponse response = view.utils().http().invoke(request);
assertThat(response.getStatusCode()).isEqualTo(200);
blobStore.setContainerAccess(containerName, ContainerAccess.PRIVATE);
assertThat(blobStore.getContainerAccess(containerName)).isEqualTo(ContainerAccess.PRIVATE);
} finally {
recycleContainerAndAddToPool(containerName);
}
}
代码示例来源:origin: org.apache.jclouds.karaf/commands
/**
* Returns an InputStream to a {@link org.jclouds.blobstore.domain.Blob}.
*
* @param containerName
* @param blobName
* @return
*/
public InputStream getBlobInputStream(BlobStore blobStore, String containerName, String blobName, boolean signedRequest)
throws Exception {
if (signedRequest) {
BlobStoreContext context = blobStore.getContext();
HttpRequest request = context.getSigner().signGetBlob(containerName, blobName);
HttpClient httpClient = context.utils().http();
HttpResponse response = httpClient.invoke(request);
int statusCode = response.getStatusCode();
if (statusCode != 200) {
throw new IOException(response.getStatusLine());
}
return response.getPayload().openStream();
}
Blob blob = blobStore.getBlob(containerName, blobName);
if (blob == null) {
if (!blobStore.containerExists(containerName)) {
throw new ContainerNotFoundException(containerName, "while getting blob");
}
throw new KeyNotFoundException(containerName, blobName, "while getting blob");
}
return blob.getPayload().openStream();
}
代码示例来源:origin: jclouds/legacy-jclouds
@Test
public void testSignGetUrlWithTime() throws InterruptedException, IOException {
String name = "hello";
String text = "fooooooooooooooooooooooo";
Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build();
String container = getContainerName();
try {
view.getBlobStore().putBlob(container, blob);
assertConsistencyAwareContainerSize(container, 1);
HttpRequest request = view.getSigner().signGetBlob(container, name, 3 /* seconds */);
assertEquals(request.getFilters().size(), 0);
assertEquals(Strings2.toString(view.utils().http().invoke(request).getPayload()), text);
TimeUnit.SECONDS.sleep(4);
try {
Strings2.toString(view.utils().http().invoke(request).getPayload());
fail("Temporary URL did not expire as expected");
} catch (AuthorizationException expected) {
}
} catch (UnsupportedOperationException ignore) {
throw new SkipException("signGetUrl with a time limit is not supported on " + provider);
} finally {
returnContainer(container);
}
}
内容来源于网络,如有侵权,请联系作者删除!