use of com.google.cloud.compute.v1.Image in project spring-cloud-gcp by spring-cloud.
the class CloudVisionTemplate method analyzeImage.
/**
* Analyze an image and extract the features of the image specified by
* {@code featureTypes}.
* <p>A feature describes the kind of Cloud Vision analysis one wishes to perform on an
* image, such as text detection, image labelling, facial detection, etc. A full list of
* feature types can be found in {@link Feature.Type}.
* @param imageResource the image one wishes to analyze. The Cloud Vision APIs support
* image formats described here: https://cloud.google.com/vision/docs/supported-files
* @param imageContext the image context used to customize the Vision API request
* @param featureTypes the types of image analysis to perform on the image
* @return the results of image analyses
* @throws CloudVisionException if the image could not be read or if a malformed response
* is received from the Cloud Vision APIs
*/
public AnnotateImageResponse analyzeImage(Resource imageResource, ImageContext imageContext, Feature.Type... featureTypes) {
ByteString imgBytes;
try {
imgBytes = ByteString.readFrom(imageResource.getInputStream());
} catch (IOException ex) {
throw new CloudVisionException("Failed to read image bytes from provided resource.", ex);
}
Image image = Image.newBuilder().setContent(imgBytes).build();
List<Feature> featureList = Arrays.stream(featureTypes).map((featureType) -> Feature.newBuilder().setType(featureType).build()).collect(Collectors.toList());
BatchAnnotateImagesRequest request = BatchAnnotateImagesRequest.newBuilder().addRequests(AnnotateImageRequest.newBuilder().addAllFeatures(featureList).setImageContext(imageContext).setImage(image)).build();
BatchAnnotateImagesResponse batchResponse = this.imageAnnotatorClient.batchAnnotateImages(request);
List<AnnotateImageResponse> annotateImageResponses = batchResponse.getResponsesList();
if (!annotateImageResponses.isEmpty()) {
return annotateImageResponses.get(0);
} else {
throw new CloudVisionException("Failed to receive valid response Vision APIs; empty response received.");
}
}
use of com.google.cloud.compute.v1.Image in project ovirt-engine by oVirt.
the class OpenStackImageProviderProxy method getImageAsDiskImage.
public DiskImage getImageAsDiskImage(String id) {
DiskImage diskImage = new DiskImage();
Image glanceImage;
try {
glanceImage = getClient().images().show(id).execute();
} catch (OpenStackResponseException e) {
log.debug("Exception:", e);
throw new OpenStackImageException(OpenStackImageException.ErrorType.IMAGE_NOT_FOUND, "Cannot find the specified image.");
} catch (RuntimeException rte) {
log.error("Exception:", rte);
throw new RuntimeException("Failed to import from the repository.");
}
validateContainerFormat(glanceImage);
String shortHash = glanceImage.getId().substring(0, 7);
if (glanceImage.getName() != null) {
diskImage.setDiskDescription(glanceImage.getName() + " (" + shortHash + ")");
} else {
diskImage.setDiskDescription("Glance disk: " + shortHash);
}
setDiskAttributes(diskImage, glanceImage);
if (glanceImage.getDiskFormat().equals(GlanceImageFormat.RAW.getValue())) {
diskImage.setVolumeFormat(VolumeFormat.RAW);
} else if (glanceImage.getDiskFormat().equals(GlanceImageFormat.COW.getValue())) {
diskImage.setVolumeFormat(VolumeFormat.COW);
} else {
throw new OpenStackImageException(OpenStackImageException.ErrorType.UNSUPPORTED_DISK_FORMAT, "Unknown disk format: " + glanceImage.getDiskFormat());
}
return diskImage;
}
use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.
the class CreateInstanceTemplate method createInstanceTemplate.
/*
Create a new instance template with the provided name and a specific
instance configuration.
*/
public static void createInstanceTemplate(String projectId, String templateName) throws IOException, ExecutionException, InterruptedException {
try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {
String machineType = "e2-standard-4";
String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
// The template describes the size and source image of the boot disk
// to attach to the instance.
AttachedDisk attachedDisk = AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(250).build()).setAutoDelete(true).setBoot(true).build();
// The template connects the instance to the `default` network,
// without specifying a subnetwork.
NetworkInterface networkInterface = NetworkInterface.newBuilder().setName("global/networks/default").addAccessConfigs(AccessConfig.newBuilder().setName("External NAT").setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString()).setNetworkTier(NetworkTier.PREMIUM.toString()).build()).build();
InstanceProperties instanceProperties = InstanceProperties.newBuilder().addDisks(attachedDisk).setMachineType(machineType).addNetworkInterfaces(networkInterface).build();
InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest.newBuilder().setProject(projectId).setInstanceTemplateResource(InstanceTemplate.newBuilder().setName(templateName).setProperties(instanceProperties).build()).build();
// Create the Instance Template.
Operation response = instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest).get();
if (response.hasError()) {
System.out.println("Instance Template creation failed ! ! " + response);
return;
}
System.out.printf("Instance Template Operation Status %s: %s", templateName, response.getStatus());
}
}
use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.
the class SnippetsIT method deleteImage.
private static void deleteImage(Image image) throws IOException, InterruptedException, ExecutionException {
try (ImagesClient imagesClient = ImagesClient.create()) {
OperationFuture<Operation, Operation> operation = imagesClient.deleteAsync(PROJECT_ID, image.getName());
operation.get();
}
}
use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.
the class CreateEncryptedInstance method createEncryptedInstance.
// Create a new encrypted instance with the provided "instanceName" value and encryption key
// in the specified project and zone.
public static void createEncryptedInstance(String project, String zone, String instanceName, String diskEncryptionKey) throws IOException, InterruptedException, ExecutionException {
/* Below are sample values that can be replaced.
machineType: machine type of the VM being created.
(This value uses the format zones/{zone}/machineTypes/{type_name}.
For a list of machine types, see https://cloud.google.com/compute/docs/machine-types)
sourceImage: path to the operating system image to mount.
(For details about images you can mount, see https://cloud.google.com/compute/docs/images)
diskSizeGb: storage size of the boot disk to attach to the instance.
networkName: network interface to associate with the instance. */
String machineType = String.format("zones/%s/machineTypes/n1-standard-1", zone);
String sourceImage = String.format("projects/debian-cloud/global/images/family/%s", "debian-11");
long diskSizeGb = 10L;
String networkName = "default";
/* Initialize client that will be used to send requests. This client only needs to be created
once, and can be reused for multiple requests. After completing all of your requests, call
the `instancesClient.close()` method on the client to safely
clean up any remaining background resources. */
try (InstancesClient instancesClient = InstancesClient.create()) {
// Instance creation requires at least one persistent disk and one network interface.
AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(Type.PERSISTENT.toString()).setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).setDiskEncryptionKey(CustomerEncryptionKey.newBuilder().setRawKey(diskEncryptionKey).build()).build();
// Use the network interface provided in the networkName argument.
NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
// Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
Instance instanceResource = Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).build();
System.out.printf("Creating instance: %s at %s ", instanceName, zone);
// Insert the instance in the specified project and zone.
InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstanceResource(instanceResource).build();
OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(insertInstanceRequest);
// Wait for the operation to complete.
Operation response = operation.get();
if (response.hasError()) {
System.out.println("Instance creation failed ! ! " + response);
return;
}
System.out.println("Operation Status: " + response.getStatus());
}
}
Aggregations