Search in sources :

Example 21 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project java-docs-samples by GoogleCloudPlatform.

the class SnippetsIT method setUpClass.

@BeforeClass
public static void setUpClass() throws Exception {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bout);
    realOut = System.out;
    System.setOut(out);
    // Use the snippets functions to create them.
    try {
        Snippets.createKeyRing(PROJECT_ID, LOCATION_ID, KEY_RING_ID);
        // Since there's no way to delete keyrings atm, have two branches - one for the first time the
        // test is run, one for after the key already exists
        assertThat(bout.toString()).contains("keyRings/" + KEY_RING_ID);
    } catch (GoogleJsonResponseException e) {
        GoogleJsonError error = e.getDetails();
        assertThat(error.getCode()).isEqualTo(409);
        assertThat(error.getMessage()).contains("keyRings/" + KEY_RING_ID);
    }
    try {
        Snippets.createCryptoKey(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
        // Since there's no way to delete keyrings atm, have two branches - one for the first time the
        // test is run, one for after the key already exists
        assertThat(bout.toString()).contains(String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
    } catch (GoogleJsonResponseException e) {
        GoogleJsonError error = e.getDetails();
        assertThat(error.getCode()).isEqualTo(409);
        assertThat(error.getMessage()).contains(String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
    }
    // Create a CryptoKeyVersion and set it as primary.
    Snippets.createCryptoKeyVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
    Matcher matcher = Pattern.compile(".*cryptoKeyVersions/(\\d+)\",\"state\":\"ENABLED\".*", Pattern.DOTALL | Pattern.MULTILINE).matcher(bout.toString().trim());
    assertTrue(matcher.matches());
    String primaryVersion = matcher.group(1);
    Snippets.setPrimaryVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, primaryVersion);
}
Also used : PrintStream(java.io.PrintStream) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Matcher(java.util.regex.Matcher) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BeforeClass(org.junit.BeforeClass)

Example 22 with GoogleJsonResponseException

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

the class AbstractGoogleJsonClientTest method testExecuteUnparsed_error.

public void testExecuteUnparsed_error() throws Exception {
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String name, String url) {
            return new MockLowLevelHttpRequest() {

                @Override
                public LowLevelHttpResponse execute() {
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
                    result.setContentType(Json.MEDIA_TYPE);
                    result.setContent("{\"error\":{\"code\":401,\"errors\":[{\"domain\":\"global\"," + "\"location\":\"Authorization\",\"locationType\":\"header\"," + "\"message\":\"me\",\"reason\":\"authError\"}],\"message\":\"me\"}}");
                    return result;
                }
            };
        }
    };
    JsonFactory jsonFactory = new JacksonFactory();
    MockGoogleJsonClient client = new MockGoogleJsonClient.Builder(transport, jsonFactory, HttpTesting.SIMPLE_URL, "", null, false).setApplicationName("Test Application").build();
    MockGoogleJsonClientRequest<String> request = new MockGoogleJsonClientRequest<String>(client, "GET", "foo", null, String.class);
    try {
        request.executeUnparsed();
        fail("expected " + GoogleJsonResponseException.class);
    } catch (GoogleJsonResponseException e) {
        // expected
        GoogleJsonError details = e.getDetails();
        assertEquals("me", details.getMessage());
        assertEquals("me", details.getErrors().get(0).getMessage());
    }
}
Also used : MockGoogleJsonClientRequest(com.google.api.client.googleapis.testing.services.json.MockGoogleJsonClientRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JsonFactory(com.google.api.client.json.JsonFactory) MockGoogleJsonClient(com.google.api.client.googleapis.testing.services.json.MockGoogleJsonClient) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError)

Example 23 with GoogleJsonResponseException

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

the class GoogleJsonResponseExceptionFactoryTestingTest method testCreateException.

public void testCreateException() throws IOException {
    GoogleJsonResponseException exception = GoogleJsonResponseExceptionFactoryTesting.newMock(JSON_FACTORY, HTTP_CODE_NOT_FOUND, REASON_PHRASE_NOT_FOUND);
    assertEquals(HTTP_CODE_NOT_FOUND, exception.getStatusCode());
    assertEquals(REASON_PHRASE_NOT_FOUND, exception.getStatusMessage());
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException)

Example 24 with GoogleJsonResponseException

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

the class Quickstart method main.

public static void main(String[] args) throws IOException {
    YouTube youtube = getYouTubeService();
    try {
        YouTube.Channels.List channelsListByUsernameRequest = youtube.channels().list("snippet,contentDetails,statistics");
        channelsListByUsernameRequest.setForUsername("GoogleDevelopers");
        ChannelListResponse response = channelsListByUsernameRequest.execute();
        Channel channel = response.getItems().get(0);
        System.out.printf("This channel's ID is %s. Its title is '%s', and it has %s views.\n", channel.getId(), channel.getSnippet().getTitle(), channel.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        e.printStackTrace();
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) YouTube(com.google.api.services.youtube.YouTube)

Example 25 with GoogleJsonResponseException

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

the class UpdateVideo method main.

/**
 * Add a keyword tag to a video that the user specifies. Use OAuth 2.0 to
 * authorize the API request.
 *
 * @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, "updatevideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-updatevideo-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 update.");
        // Prompt the user to enter a keyword tag to add to the video.
        String tag = getTagFromUser();
        System.out.println("You chose " + tag + " as a tag.");
        // Call the YouTube Data API's youtube.videos.list method to
        // retrieve the resource that represents the specified video.
        YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet").setId(videoId);
        VideoListResponse listResponse = listVideosRequest.execute();
        // Since the API request specified a unique video ID, the API
        // response should return exactly one video. If the response does
        // not contain a video, then the specified video ID was not found.
        List<Video> videoList = listResponse.getItems();
        if (videoList.isEmpty()) {
            System.out.println("Can't find a video with ID: " + videoId);
            return;
        }
        // Extract the snippet from the video resource.
        Video video = videoList.get(0);
        VideoSnippet snippet = video.getSnippet();
        // Preserve any tags already associated with the video. If the
        // video does not have any tags, create a new array. Append the
        // provided tag to the list of tags associated with the video.
        List<String> tags = snippet.getTags();
        if (tags == null) {
            tags = new ArrayList<String>(1);
            snippet.setTags(tags);
        }
        tags.add(tag);
        // Update the video resource by calling the videos.update() method.
        YouTube.Videos.Update updateVideosRequest = youtube.videos().update("snippet", video);
        Video videoResponse = updateVideosRequest.execute();
        // Print information from the updated resource.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Title: " + videoResponse.getSnippet().getTitle());
        System.out.println("  - Tags: " + videoResponse.getSnippet().getTags());
    } 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 : VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) VideoListResponse(com.google.api.services.youtube.model.VideoListResponse)

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