1 /* 2 * Copyright 2016 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.cloud.examples.compute.snippets; 18 19 import com.google.cloud.ServiceOptions; 20 import com.google.cloud.compute.v1.CreateSnapshotDiskRequest; 21 import com.google.cloud.compute.v1.DisksClient; 22 import com.google.cloud.compute.v1.Operation; 23 import com.google.cloud.compute.v1.Snapshot; 24 import java.io.IOException; 25 26 /** 27 * A snippet for Google Cloud Compute Engine showing how to create a snapshot of a disk if the disk 28 * exists. 29 */ 30 public class CreateSnapshot { 31 private static final String DISK_NAME = "test-disk"; 32 private static final String DEFAULT_PROJECT = ServiceOptions.getDefaultProjectId(); 33 private static final String ZONE = "us-central1-a"; 34 main(String... args)35 public static void main(String... args) throws IOException { 36 Snapshot snapshotResource = Snapshot.newBuilder().setName("test-snapshot").build(); 37 CreateSnapshotDiskRequest diskRequest = 38 CreateSnapshotDiskRequest.newBuilder() 39 .setDisk(DISK_NAME) 40 .setGuestFlush(Boolean.FALSE) 41 .setSnapshotResource(snapshotResource) 42 .build(); 43 try (DisksClient disksClient = DisksClient.create()) { 44 Operation snapshotDisk = disksClient.createSnapshot(diskRequest); 45 if (snapshotDisk.getError() == null) { 46 System.out.println("Snapshot was successfully created"); 47 } else { 48 // inspect operation.getErrors() 49 throw new RuntimeException("Snapshot creation failed"); 50 } 51 } 52 } 53 } 54