Search in sources :

Example 76 with Image

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.");
    }
}
Also used : Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) ByteString(com.google.protobuf.ByteString) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 77 with Image

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;
}
Also used : OpenStackResponseException(com.woorea.openstack.base.client.OpenStackResponseException) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage) Image(com.woorea.openstack.glance.model.v2.Image) RepoImage(org.ovirt.engine.core.common.businessentities.storage.RepoImage) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage)

Example 78 with Image

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());
    }
}
Also used : InstanceProperties(com.google.cloud.compute.v1.InstanceProperties) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) NetworkInterface(com.google.cloud.compute.v1.NetworkInterface) Operation(com.google.cloud.compute.v1.Operation) InsertInstanceTemplateRequest(com.google.cloud.compute.v1.InsertInstanceTemplateRequest) InstanceTemplatesClient(com.google.cloud.compute.v1.InstanceTemplatesClient)

Example 79 with Image

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();
    }
}
Also used : Operation(com.google.cloud.compute.v1.Operation) ImagesClient(com.google.cloud.compute.v1.ImagesClient)

Example 80 with Image

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());
    }
}
Also used : InsertInstanceRequest(com.google.cloud.compute.v1.InsertInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) NetworkInterface(com.google.cloud.compute.v1.NetworkInterface) Operation(com.google.cloud.compute.v1.Operation)

Aggregations

AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)72 Image (com.google.cloud.vision.v1.Image)72 Feature (com.google.cloud.vision.v1.Feature)70 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)69 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)66 ArrayList (java.util.ArrayList)64 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)63 ByteString (com.google.protobuf.ByteString)51 ImageSource (com.google.cloud.vision.v1.ImageSource)39 FileInputStream (java.io.FileInputStream)31 EntityAnnotation (com.google.cloud.vision.v1.EntityAnnotation)27 WebImage (com.google.cloud.vision.v1.WebDetection.WebImage)26 IOException (java.io.IOException)17 ImageContext (com.google.cloud.vision.v1.ImageContext)14 WebDetection (com.google.cloud.vision.v1.WebDetection)11 LocationInfo (com.google.cloud.vision.v1.LocationInfo)10 SafeSearchAnnotation (com.google.cloud.vision.v1.SafeSearchAnnotation)10 Arrays (java.util.Arrays)10 AttachedDisk (com.google.cloud.compute.v1.AttachedDisk)9 CropHint (com.google.cloud.vision.v1.CropHint)9