Search in sources :

Example 21 with Image

use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.

the class ListImages method listImagesByPage.

// [END compute_images_list]
// [START compute_images_list_page]
// Prints a list of all non-deprecated image names available in a given project,
// divided into pages as returned by the Compute Engine API.
public static void listImagesByPage(String project, int pageSize) throws IOException {
    // safely clean up any remaining background resources.
    try (ImagesClient imagesClient = ImagesClient.create()) {
        // Listing only non-deprecated images to reduce the size of the reply.
        ListImagesRequest imagesRequest = ListImagesRequest.newBuilder().setProject(project).setMaxResults(pageSize).setFilter("deprecated.state != DEPRECATED").build();
        // Use the `iteratePages` attribute of returned iterable to have more granular control of
        // iteration over paginated results from the API. Each time you want to access the
        // next page, the library retrieves that page from the API.
        int pageNumber = 1;
        for (ListPage page : imagesClient.list(imagesRequest).iteratePages()) {
            System.out.println("Page Number: " + pageNumber++);
            for (Image image : page.getValues()) {
                System.out.println(image.getName());
            }
        }
    }
}
Also used : ListPage(com.google.cloud.compute.v1.ImagesClient.ListPage) ImagesClient(com.google.cloud.compute.v1.ImagesClient) ListImagesRequest(com.google.cloud.compute.v1.ListImagesRequest) Image(com.google.cloud.compute.v1.Image)

Example 22 with Image

use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.

the class ListImages method listImages.

// [START compute_images_list]
// Prints a list of all non-deprecated image names available in given project.
public static void listImages(String project) throws IOException {
    // safely clean up any remaining background resources.
    try (ImagesClient imagesClient = ImagesClient.create()) {
        // Listing only non-deprecated images to reduce the size of the reply.
        ListImagesRequest imagesRequest = ListImagesRequest.newBuilder().setProject(project).setMaxResults(100).setFilter("deprecated.state != DEPRECATED").build();
        // Although the `setMaxResults` parameter is specified in the request, the iterable returned
        // by the `list()` method hides the pagination mechanic. The library makes multiple
        // requests to the API for you, so you can simply iterate over all the images.
        int imageCount = 0;
        for (Image image : imagesClient.list(imagesRequest).iterateAll()) {
            imageCount++;
            System.out.println(image.getName());
        }
        System.out.printf("Image count in %s is: %s", project, imageCount);
    }
}
Also used : ImagesClient(com.google.cloud.compute.v1.ImagesClient) ListImagesRequest(com.google.cloud.compute.v1.ListImagesRequest) Image(com.google.cloud.compute.v1.Image)

Example 23 with Image

use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.

the class ImageMagick method accept.

// [END functions_imagemagick_setup]
// [START functions_imagemagick_analyze]
@Override
public // Blurs uploaded images that are flagged as Adult or Violence.
void accept(GcsEvent event, Context context) {
    // Validate parameters
    if (event.getBucket() == null || event.getName() == null) {
        logger.severe("Error: Malformed GCS event.");
        return;
    }
    BlobInfo blobInfo = BlobInfo.newBuilder(event.getBucket(), event.getName()).build();
    // Construct URI to GCS bucket and file.
    String gcsPath = String.format("gs://%s/%s", event.getBucket(), event.getName());
    logger.info(String.format("Analyzing %s", event.getName()));
    // Construct request.
    ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature feature = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(img).build();
    List<AnnotateImageRequest> requests = List.of(request);
    // Send request to the Vision API.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();
        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                logger.info(String.format("Error: %s", res.getError().getMessage()));
                return;
            }
            // Get Safe Search Annotations
            SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
            if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) {
                logger.info(String.format("Detected %s as inappropriate.", event.getName()));
                blur(blobInfo);
            } else {
                logger.info(String.format("Detected %s as OK.", event.getName()));
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e);
    }
}
Also used : SafeSearchAnnotation(com.google.cloud.vision.v1.SafeSearchAnnotation) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) BlobInfo(com.google.cloud.storage.BlobInfo) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 24 with Image

use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstanceWithCustomHostname method createInstanceWithCustomHostname.

// Creates an instance with custom hostname.
public static void createInstanceWithCustomHostname(String projectId, String zone, String instanceName, String hostName) throws IOException, ExecutionException, InterruptedException {
    // machineType - Machine type for the VM instance specified in the following format:
    // *    "zones/{zone}/machineTypes/{type_name}". For example:
    // *    "zones/europe-west3-c/machineTypes/f1-micro"
    // *    You can find the list of available machine types by using this gcloud command:
    // *    $ gcloud compute machine-types list
    // sourceImage - Path of the disk image you want to use for your boot
    // *    disk. This image can be one of the public images
    // *    eg: "projects/...
    // *    or a private image you have access to.
    // *    You can check the list of available public images using:
    // *    $ gcloud compute images list
    // networkName - Name of the network you want the new instance to use.
    // *    For example: global/networks/default - if you want to use the default network.
    String machineType = "n1-standard-1";
    String sourceImage = String.format("projects/%s/global/images/family/%s", "debian-cloud", "debian-11");
    String networkName = "global/networks/default";
    try (InstancesClient instancesClient = InstancesClient.create()) {
        System.out.printf("Creating the %s instance in %s with hostname %s...", instanceName, zone, hostName);
        AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setInitializeParams(// Describe the size and source image of the boot disk to attach to the instance.
        AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(10).build()).build();
        // Use the network interface provided in the networkName argument.
        NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
        Instance instanceResource = Instance.newBuilder().setName(instanceName).setHostname(hostName).addDisks(disk).setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType)).addNetworkInterfaces(networkInterface).build();
        InsertInstanceRequest request = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();
        // Wait for the create operation to complete.
        Operation response = instancesClient.insertAsync(request).get();
        if (response.hasError()) {
            System.out.printf("Instance creation failed for instance: %s ; Response: %s ! ! ", instanceName, response);
            return;
        }
        System.out.printf("Instance created : %s", instanceName);
        System.out.printf("Operation Status for instance %s is %s: ", instanceName, 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)

Example 25 with Image

use of com.google.cloud.compute.v1.Image in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstanceDeleteProtection method createInstanceDeleteProtection.

// Send an instance creation request to the Compute Engine API and wait for it to complete.
public static void createInstanceDeleteProtection(String projectId, String zone, String instanceName, boolean deleteProtection) throws IOException, ExecutionException, InterruptedException {
    String machineType = String.format("zones/%s/machineTypes/e2-small", zone);
    String sourceImage = String.format("projects/debian-cloud/global/images/family/%s", "debian-11");
    long diskSizeGb = 10L;
    String networkName = "default";
    // Instance creation requires at least one persistent disk and one network interface.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setInitializeParams(// Describe the size and source image of the boot disk to attach to the instance.
        AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();
        // Use the default VPC network.
        NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
        // Collect information into the Instance object.
        Instance instanceResource = Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setDeletionProtection(deleteProtection).build();
        System.out.printf("Creating instance: %s at %s %n", instanceName, zone);
        // Prepare the request to insert an instance.
        InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();
        // Wait for the create operation to complete.
        Operation response = instancesClient.insertAsync(insertInstanceRequest).get();
        if (response.hasError()) {
            System.out.println("Instance creation failed ! ! " + response);
            return;
        }
        System.out.printf("Instance created : %s", instanceName);
        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