Search in sources :

Example 31 with GoogleJsonResponseException

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

the class GeolocationSearch 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 = GeolocationSearch.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() {

            @Override
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-geolocationsearch-sample").build();
        // Prompt the user to enter a query term.
        String queryTerm = getInputQuery();
        // Prompt the user to enter location coordinates.
        String location = getInputLocation();
        // Prompt the user to enter a location radius.
        String locationRadius = getInputLocationRadius();
        // 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);
        search.setLocation(location);
        search.setLocationRadius(locationRadius);
        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");
        // As a best practice, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/videoId)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        // Call the API and print results.
        SearchListResponse searchResponse = search.execute();
        List<SearchResult> searchResultList = searchResponse.getItems();
        List<String> videoIds = new ArrayList<String>();
        if (searchResultList != null) {
            // Merge video IDs
            for (SearchResult searchResult : searchResultList) {
                videoIds.add(searchResult.getId().getVideoId());
            }
            Joiner stringJoiner = Joiner.on(',');
            String videoId = stringJoiner.join(videoIds);
            // Call the YouTube Data API's youtube.videos.list method to
            // retrieve the resources that represent the specified videos.
            YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet, recordingDetails").setId(videoId);
            VideoListResponse listResponse = listVideosRequest.execute();
            List<Video> videoList = listResponse.getItems();
            if (videoList != null) {
                prettyPrint(videoList.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) Joiner(com.google.api.client.util.Joiner) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) 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) Video(com.google.api.services.youtube.model.Video) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) VideoListResponse(com.google.api.services.youtube.model.VideoListResponse)

Example 32 with GoogleJsonResponseException

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

the class ChannelSectionLocalizations method main.

/**
 * Set and retrieve localized metadata for a channel section.
 *
 * @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, "localizations");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-localizations-sample").build();
        // Prompt the user to specify the action of the be achieved.
        String actionString = getActionFromUser();
        System.out.println("You chose " + actionString + ".");
        // Map the user input to the enum values.
        Action action = Action.valueOf(actionString.toUpperCase());
        switch(action) {
            case SET:
                setChannelSectionLocalization(getId("channel section"), getDefaultLanguage(), getLanguage(), getMetadata("title"));
                break;
            case GET:
                getChannelSectionLocalization(getId("channel section"), getLanguage());
                break;
            case LIST:
                listChannelSectionLocalizations(getId("channel section"));
                break;
        }
    } 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();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube)

Example 33 with GoogleJsonResponseException

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

the class CreateReportingJob method main.

/**
 * Create a reporting job.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {
    /*
         * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
         * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
         * use this scope.
         */
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "createreportingjob");
        // This object is used to make YouTube Reporting API requests.
        youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-createreportingjob-sample").build();
        // Prompt the user to specify the name of the job to be created.
        String name = getNameFromUser();
        if (listReportTypes()) {
            createReportingJob(getReportTypeIdFromUser(), name);
        }
    } 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();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) YouTubeReporting(com.google.api.services.youtubereporting.YouTubeReporting) IOException(java.io.IOException)

Example 34 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project beam by apache.

the class GcsUtilTest method testAccessDeniedObjectThrowsIOException.

// GCSUtil.expand() should fail for other errors such as access denied.
@Test
public void testAccessDeniedObjectThrowsIOException() throws IOException {
    GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
    GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
    Storage mockStorage = Mockito.mock(Storage.class);
    gcsUtil.setStorageClient(mockStorage);
    Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class);
    Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class);
    GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/accessdeniedfile");
    GoogleJsonResponseException expectedException = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Waves hand mysteriously", "These aren't the buckets you're looking for");
    when(mockStorage.objects()).thenReturn(mockStorageObjects);
    when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject())).thenReturn(mockStorageGet);
    when(mockStorageGet.execute()).thenThrow(expectedException);
    thrown.expect(IOException.class);
    thrown.expectMessage("Unable to get the file object for path");
    gcsUtil.expand(pattern);
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Storage(com.google.api.services.storage.Storage) GoogleCloudStorage(com.google.cloud.hadoop.gcsio.GoogleCloudStorage) Objects(com.google.api.services.storage.model.Objects) GcsPath(org.apache.beam.sdk.extensions.gcp.util.gcsfs.GcsPath) GcsOptions(org.apache.beam.sdk.extensions.gcp.options.GcsOptions) Test(org.junit.Test)

Example 35 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project beam by apache.

the class GcsUtilTest method testCreateBucketAccessErrors.

@Test
public void testCreateBucketAccessErrors() throws IOException {
    GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
    GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
    Storage mockStorage = Mockito.mock(Storage.class);
    gcsUtil.setStorageClient(mockStorage);
    Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class);
    Storage.Buckets.Insert mockStorageInsert = Mockito.mock(Storage.Buckets.Insert.class);
    BackOff mockBackOff = BackOffAdapter.toGcpBackOff(FluentBackoff.DEFAULT.backoff());
    GoogleJsonResponseException expectedException = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Waves hand mysteriously", "These aren't the buckets you're looking for");
    when(mockStorage.buckets()).thenReturn(mockStorageObjects);
    when(mockStorageObjects.insert(any(String.class), any(Bucket.class))).thenReturn(mockStorageInsert);
    when(mockStorageInsert.execute()).thenThrow(expectedException);
    thrown.expect(AccessDeniedException.class);
    gcsUtil.createBucket("a", new Bucket(), mockBackOff, new FastNanoClockAndSleeper());
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Storage(com.google.api.services.storage.Storage) GoogleCloudStorage(com.google.cloud.hadoop.gcsio.GoogleCloudStorage) Bucket(com.google.api.services.storage.model.Bucket) GcsOptions(org.apache.beam.sdk.extensions.gcp.options.GcsOptions) BackOff(com.google.api.client.util.BackOff) Test(org.junit.Test)

Aggregations

GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)90 IOException (java.io.IOException)45 YouTube (com.google.api.services.youtube.YouTube)26 Credential (com.google.api.client.auth.oauth2.Credential)25 Operation (com.google.api.services.compute.model.Operation)12 ArrayList (java.util.ArrayList)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