Search in sources :

Example 71 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project cloudbreak by hortonworks.

the class GcpSubnetResourceBuilder method delete.

@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource, Network network) throws Exception {
    if (isNewNetworkAndSubnet(network) || isNewSubnetInExistingNetwork(network)) {
        Compute compute = context.getCompute();
        String projectId = context.getProjectId();
        try {
            Operation operation = compute.subnetworks().delete(projectId, context.getLocation().getRegion().value(), resource.getName()).execute();
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            exceptionHandler(e, resource.getName(), resourceType());
            return null;
        }
    }
    return null;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Compute(com.google.api.services.compute.Compute) Operation(com.google.api.services.compute.model.Operation)

Example 72 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project cloudbreak by hortonworks.

the class GcpInstanceConnector method check.

@Override
public List<CloudVmInstanceStatus> check(AuthenticatedContext ac, List<CloudInstance> vms) {
    List<CloudVmInstanceStatus> statuses = new ArrayList<>();
    CloudCredential credential = ac.getCloudCredential();
    CloudContext cloudContext = ac.getCloudContext();
    Compute compute = GcpStackUtil.buildCompute(credential);
    for (CloudInstance instance : vms) {
        InstanceStatus status = InstanceStatus.UNKNOWN;
        try {
            Instance executeInstance = getInstance(cloudContext, credential, compute, instance.getInstanceId());
            if ("RUNNING".equals(executeInstance.getStatus())) {
                status = InstanceStatus.STARTED;
            } else if ("TERMINATED".equals(executeInstance.getStatus())) {
                status = InstanceStatus.STOPPED;
            }
        } catch (GoogleJsonResponseException e) {
            if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                status = InstanceStatus.TERMINATED;
            } else {
                LOGGER.warn(String.format("Instance %s is not reachable", instance), e);
            }
        } catch (IOException e) {
            LOGGER.warn(String.format("Instance %s is not reachable", instance), e);
        }
        statuses.add(new CloudVmInstanceStatus(instance, status));
    }
    return statuses;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) CloudCredential(com.sequenceiq.cloudbreak.cloud.model.CloudCredential) Instance(com.google.api.services.compute.model.Instance) CloudInstance(com.sequenceiq.cloudbreak.cloud.model.CloudInstance) InstanceStatus(com.sequenceiq.cloudbreak.cloud.model.InstanceStatus) CloudVmInstanceStatus(com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus) CloudVmInstanceStatus(com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus) CloudContext(com.sequenceiq.cloudbreak.cloud.context.CloudContext) Compute(com.google.api.services.compute.Compute) ArrayList(java.util.ArrayList) CloudInstance(com.sequenceiq.cloudbreak.cloud.model.CloudInstance) IOException(java.io.IOException)

Example 73 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project cloudbreak by hortonworks.

the class GcpReservedIpResourceBuilder method delete.

@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource) throws Exception {
    Compute compute = context.getCompute();
    String projectId = context.getProjectId();
    String region = context.getLocation().getRegion().value();
    try {
        Operation operation = compute.addresses().delete(projectId, region, resource.getName()).execute();
        return createOperationAwareCloudResource(resource, operation);
    } catch (GoogleJsonResponseException e) {
        exceptionHandler(e, resource.getName(), resourceType());
        return null;
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Compute(com.google.api.services.compute.Compute) Operation(com.google.api.services.compute.model.Operation)

Example 74 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class Search method main.

/**
 * Initialize a YouTube object to search for videos on YouTube. Then
 * display the name and thumbnail image of each video in the result set.
 *
 * @param args command line args.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);
    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : " + e.getMessage());
        System.exit(1);
    }
    try {
        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {

            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();
        // Prompt the user to enter a query term.
        String queryTerm = getInputQuery();
        // Define the API request for retrieving search results.
        YouTube.Search.List search = youtube.search().list("id,snippet");
        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");
        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        // Call the API and print results.
        SearchListResponse searchResponse = search.execute();
        List<SearchResult> searchResultList = searchResponse.getItems();
        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm);
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) SearchListResponse(com.google.api.services.youtube.model.SearchListResponse) InputStream(java.io.InputStream) SearchResult(com.google.api.services.youtube.model.SearchResult) IOException(java.io.IOException) Properties(java.util.Properties) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 75 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class UploadThumbnail method main.

/**
 * Prompt the user to specify a video ID and the path for a thumbnail
 * image. Then call the API to set the image as the thumbnail for the video.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadthumbnail");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadthumbnail-sample").build();
        // Prompt the user to enter the video ID of the video being updated.
        String videoId = getVideoIdFromUser();
        System.out.println("You chose " + videoId + " to upload a thumbnail.");
        // Prompt the user to specify the location of the thumbnail image.
        File imageFile = getImageFromUser();
        System.out.println("You chose " + imageFile + " to upload.");
        // Create an object that contains the thumbnail image file's
        // contents.
        InputStreamContent mediaContent = new InputStreamContent(IMAGE_FILE_FORMAT, new BufferedInputStream(new FileInputStream(imageFile)));
        mediaContent.setLength(imageFile.length());
        // Create an API request that specifies that the mediaContent
        // object is the thumbnail of the specified video.
        Set thumbnailSet = youtube.thumbnails().set(videoId, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = thumbnailSet.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        // Set the upload state for the thumbnail image.
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    // sent.
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    // completes.
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    // uploaded.
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    // been successfully uploaded.
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    // not started yet.
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Upload the image and set it as the specified video's thumbnail.
        ThumbnailSetResponse setResponse = thumbnailSet.execute();
        // Print the URL for the updated video's thumbnail image.
        System.out.println("\n================== Uploaded Thumbnail ==================\n");
        System.out.println("  - Url: " + setResponse.getItems().get(0).getDefault().getUrl());
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) Set(com.google.api.services.youtube.YouTube.Thumbnails.Set) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) ThumbnailSetResponse(com.google.api.services.youtube.model.ThumbnailSetResponse) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) InputStreamContent(com.google.api.client.http.InputStreamContent)

Aggregations

GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)94 IOException (java.io.IOException)48 YouTube (com.google.api.services.youtube.YouTube)26 Credential (com.google.api.client.auth.oauth2.Credential)25 ArrayList (java.util.ArrayList)13 Operation (com.google.api.services.compute.model.Operation)12 Test (org.junit.Test)12 Compute (com.google.api.services.compute.Compute)11 Storage (com.google.api.services.storage.Storage)10 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)8 GcsOptions (org.apache.beam.sdk.extensions.gcp.options.GcsOptions)7 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)5 InputStreamContent (com.google.api.client.http.InputStreamContent)5 BackOff (com.google.api.client.util.BackOff)5 HashMap (java.util.HashMap)5 Objects (com.google.api.services.storage.model.Objects)4 GoogleCloudStorage (com.google.cloud.hadoop.gcsio.GoogleCloudStorage)4 HalException (com.netflix.spinnaker.halyard.core.error.v1.HalException)4 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3