本文整理汇总了Java中com.google.api.services.compute.Compute类的典型用法代码示例。如果您正苦于以下问题:Java Compute类的具体用法?Java Compute怎么用?Java Compute使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Compute类属于com.google.api.services.compute包,在下文中一共展示了Compute类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testSimpleRetry
import com.google.api.services.compute.Compute; //导入依赖的package包/类
public void testSimpleRetry() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
.build();
MockSleeper mockSleeper = new MockSleeper();
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper,
TimeValue.timeValueSeconds(5));
Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null)
.setHttpRequestInitializer(retryHttpInitializerWrapper)
.setApplicationName("test")
.build();
HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
HttpResponse response = request.execute();
assertThat(mockSleeper.getCount(), equalTo(3));
assertThat(response.getStatusCode(), equalTo(200));
}
示例2: testIOExceptionRetry
import com.google.api.services.compute.Compute; //导入依赖的package包/类
public void testIOExceptionRetry() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
.build();
MockSleeper mockSleeper = new MockSleeper();
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper,
TimeValue.timeValueMillis(500));
Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null)
.setHttpRequestInitializer(retryHttpInitializerWrapper)
.setApplicationName("test")
.build();
HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
HttpResponse response = request.execute();
assertThat(mockSleeper.getCount(), equalTo(1));
assertThat(response.getStatusCode(), equalTo(200));
}
示例3: getGoogleComputeClient
import com.google.api.services.compute.Compute; //导入依赖的package包/类
/**
* Get a Google Compute Engine client object.
* @param userEmail The service account's client email.
* @param privateKey The service account's private key.
* @param scopes The scopes used in the compute client object.
* @param applicationName The application name.
* @return The created Compute Engine client object.
* @throws GeneralSecurityException Exception when creating http transport.
* @throws IOException Exception when creating http transport.
*/
public static Compute getGoogleComputeClient(String userEmail,
String privateKey,
List<String> scopes,
String applicationName)
throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(userEmail)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKey(privateKeyFromPkcs8(privateKey))
.build();
return new Compute.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(applicationName)
.build();
}
示例4: getInstanceIp
import com.google.api.services.compute.Compute; //导入依赖的package包/类
static String getInstanceIp(AccountDeploymentDetails<GoogleAccount> details, String instanceName) {
Compute compute = getCompute(details);
Instance instance = null;
try {
instance = compute.instances().get(details.getAccount().getProject(), "us-central1-f", instanceName).execute();
} catch (IOException e) {
throw new HalException(FATAL, "Unable to get instance " + instanceName);
}
return instance.getNetworkInterfaces()
.stream()
.map(i -> i.getAccessConfigs().stream()
.map(AccessConfig::getNatIP)
.filter(ip -> !StringUtils.isEmpty(ip))
.findFirst()
).filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElseThrow(() -> new HalException(FATAL, "No public IP associated with" + instanceName));
}
示例5: createInstance
import com.google.api.services.compute.Compute; //导入依赖的package包/类
public void createInstance(GoogleComputeProvider provider, String workerId) {
try {
final String instanceName = instanceName(workerId);
Compute compute = createApi(provider);
Operation diskOperation = createDisk(provider, compute, instanceName, provider.snapshotName);
logger.info(String.format("Wait for disk creation: %s", instanceName));
waitForOperation(provider, compute, diskOperation);
Operation instanceCreateOperation = makeInstance(provider, compute, workerId, instanceName);
logger.info(String.format("Wait for instance creation: %s", instanceName));
waitForOperation(provider, compute, instanceCreateOperation);
logger.info(String.format("Instance %s created successfully", instanceName));
} catch (Exception e) {
logger.error("Failed to created google compute engine instance", e);
}
}
示例6: stopAndRemoveInstance
import com.google.api.services.compute.Compute; //导入依赖的package包/类
public void stopAndRemoveInstance(GoogleComputeProvider provider, String workerId) {
try {
final String instanceName = instanceName(workerId);
Compute compute = createApi(provider);
logger.info(String.format("Stopping and removing instance: %s", instanceName));
Operation operation = compute
.instances()
.stop(provider.project, provider.zone, instanceName)
.execute();
waitForOperation(provider, compute, operation);
operation = compute.instances().delete(
provider.project, provider.zone, instanceName).execute();
waitForOperation(provider, compute, operation);
logger.info(String.format("Instance %s stopped", instanceName));
} catch (IOException | GeneralSecurityException e) {
logger.error("", e);
}
}
示例7: listRegions
import com.google.api.services.compute.Compute; //导入依赖的package包/类
@Override
public List<Region> listRegions()
{
List<Region> regions = Lists.newArrayList();
Compute.Zones.List zones = compute.zones().list(credentials_.getProject());
ZoneList zoneList = zones.execute();
for (Zone zone : zoneList.getItems())
{
regions.add(new Region(zone.getName())
.setEndpoint(zone.getSelfLink())
.setId(zone.getId().intValue())
.setStatus(RegionStatus.valueOf(zone.getStatus())));
}
return Collections.unmodifiableList(regions);
}
示例8: stopStart
import com.google.api.services.compute.Compute; //导入依赖的package包/类
private CloudVmInstanceStatus stopStart(GcpContext context, AuthenticatedContext auth, CloudInstance instance, boolean stopRequest) {
String projectId = GcpStackUtil.getProjectId(auth.getCloudCredential());
String availabilityZone = context.getLocation().getAvailabilityZone().value();
Compute compute = context.getCompute();
String instanceId = instance.getInstanceId();
try {
Get get = compute.instances().get(projectId, availabilityZone, instanceId);
String state = stopRequest ? "RUNNING" : "TERMINATED";
if (state.equals(get.execute().getStatus())) {
Operation operation = stopRequest ? compute.instances().stop(projectId, availabilityZone, instanceId).setPrettyPrint(true).execute()
: compute.instances().start(projectId, availabilityZone, instanceId).setPrettyPrint(true).execute();
CloudInstance operationAwareCloudInstance = createOperationAwareCloudInstance(instance, operation);
return checkInstances(context, auth, Collections.singletonList(operationAwareCloudInstance)).get(0);
} else {
LOGGER.info("Instance {} is not in {} state - won't start it.", state, instanceId);
return null;
}
} catch (IOException e) {
throw new GcpResourceException(String.format("An error occurred while stopping the vm '%s'", instanceId), e);
}
}
示例9: build
import com.google.api.services.compute.Compute; //导入依赖的package包/类
@Override
public CloudResource build(GcpContext context, AuthenticatedContext auth, Network network, Security security, CloudResource resource) throws Exception {
if (!isExistingNetwork(network)) {
Compute compute = context.getCompute();
String projectId = context.getProjectId();
com.google.api.services.compute.model.Network gcpNetwork = new com.google.api.services.compute.model.Network();
gcpNetwork.setName(resource.getName());
gcpNetwork.setAutoCreateSubnetworks(false);
Insert networkInsert = compute.networks().insert(projectId, gcpNetwork);
try {
Operation operation = networkInsert.execute();
if (operation.getHttpErrorStatusCode() != null) {
throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), resource.getName());
}
context.putParameter(NETWORK_NAME, resource.getName());
return createOperationAwareCloudResource(resource, operation);
} catch (GoogleJsonResponseException e) {
throw new GcpResourceException(checkException(e), resourceType(), resource.getName());
}
}
context.putParameter(NETWORK_NAME, resource.getName());
return new Builder().cloudResource(resource).persistent(false).build();
}
示例10: securityGroups
import com.google.api.services.compute.Compute; //导入依赖的package包/类
@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) throws IOException {
Compute compute = GcpStackUtil.buildCompute(cloudCredential);
String projectId = GcpStackUtil.getProjectId(cloudCredential);
Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
if (compute != null) {
FirewallList firewallList = compute.firewalls().list(projectId).execute();
for (Firewall firewall : firewallList.getItems()) {
Map<String, Object> properties = new HashMap<>();
properties.put("network", getNetworkName(firewall));
CloudSecurityGroup cloudSecurityGroup = new CloudSecurityGroup(firewall.getName(), firewall.getName(), properties);
result.computeIfAbsent(region.value(), k -> new HashSet<>()).add(cloudSecurityGroup);
}
}
return new CloudSecurityGroups(result);
}
示例11: update
import com.google.api.services.compute.Compute; //导入依赖的package包/类
@Override
public CloudResourceStatus update(GcpContext context, AuthenticatedContext auth, Group group, Network network, Security security, CloudResource resource) {
String projectId = context.getProjectId();
Compute compute = context.getCompute();
String resourceName = resource.getName();
try {
Firewall fireWall = compute.firewalls().get(projectId, resourceName).execute();
List<String> sourceRanges = getSourceRanges(security);
fireWall.setSourceRanges(sourceRanges);
Operation operation = compute.firewalls().update(projectId, resourceName, fireWall).execute();
CloudResource cloudResource = createOperationAwareCloudResource(resource, operation);
return checkResources(context, auth, Collections.singletonList(cloudResource)).get(0);
} catch (IOException e) {
throw new GcpResourceException("Failed to update resource!", GCP_FIREWALL_IN, resourceName, e);
}
}
示例12: checkImageStatus
import com.google.api.services.compute.Compute; //导入依赖的package包/类
@Override
public ImageStatusResult checkImageStatus(AuthenticatedContext authenticatedContext, CloudStack stack, com.sequenceiq.cloudbreak.cloud.model.Image image) {
CloudCredential credential = authenticatedContext.getCloudCredential();
String projectId = getProjectId(credential);
String imageName = image.getImageName();
try {
Image gcpApiImage = new Image();
gcpApiImage.setName(getImageName(imageName));
Compute compute = buildCompute(credential);
Get getImages = compute.images().get(projectId, gcpApiImage.getName());
String status = getImages.execute().getStatus();
LOGGER.info("Status of image {} copy: {}", gcpApiImage.getName(), status);
if (READY.equals(status)) {
return new ImageStatusResult(ImageStatus.CREATE_FINISHED, ImageStatusResult.COMPLETED);
}
} catch (IOException e) {
LOGGER.warn("Failed to retrieve image copy status", e);
return new ImageStatusResult(ImageStatus.CREATE_FAILED, 0);
}
return new ImageStatusResult(ImageStatus.IN_PROGRESS, ImageStatusResult.HALF);
}
示例13: waitOperation
import com.google.api.services.compute.Compute; //导入依赖的package包/类
private void waitOperation(Compute compute, Operation operation) throws java.io.IOException {
int tried = 0;
while (tried < MAX_TRY) {
LOGGER.info("check operation: " + operation.getName() + ", tried: " + tried);
Operation checkResponse = compute.globalOperations().get(defaultProjectId, operation.getName()).execute();
if ("DONE".equals(checkResponse.getStatus())) {
break;
}
tried++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
LOGGER.error("thread sleep interrupted", e);
}
}
if (tried == MAX_TRY) {
throw new RuntimeException("wait for operation exceeded maximum retry number, operation: " + operation.getName());
}
}
示例14: testRetryWaitTooLong
import com.google.api.services.compute.Compute; //导入依赖的package包/类
public void testRetryWaitTooLong() throws Exception {
TimeValue maxWaitTime = TimeValue.timeValueMillis(10);
int maxRetryTimes = 50;
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, maxRetryTimes);
JsonFactory jsonFactory = new JacksonFactory();
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
.build();
MockSleeper oneTimeSleeper = new MockSleeper() {
@Override
public void sleep(long millis) throws InterruptedException {
Thread.sleep(maxWaitTime.getMillis());
super.sleep(0); // important number, use this to get count
}
};
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, oneTimeSleeper, maxWaitTime);
Compute client = new Compute.Builder(fakeTransport, jsonFactory, null)
.setHttpRequestInitializer(retryHttpInitializerWrapper)
.setApplicationName("test")
.build();
HttpRequest request1 = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
try {
request1.execute();
fail("Request should fail if wait too long");
} catch (HttpResponseException e) {
assertThat(e.getStatusCode(), equalTo(HttpStatusCodes.STATUS_CODE_SERVER_ERROR));
// should only retry once.
assertThat(oneTimeSleeper.getCount(), lessThan(maxRetryTimes));
}
}
示例15: createComputeService
import com.google.api.services.compute.Compute; //导入依赖的package包/类
/**
* Set up the Compute Engine service
*
* @return Compute.Builder
*
* @throws IOException
* @throws GeneralSecurityException
*/
public static Compute createComputeService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleCredential credential = GoogleCredential.getApplicationDefault();
if (credential.createScopedRequired()) {
credential =
credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
}
return new Compute.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("b612_BetterWorld/1.0")
.build();
}