Search in sources :

Example 1 with HttpRequest

use of com.google.api.client.http.HttpRequest in project elasticsearch by elastic.

the class RetryHttpInitializerWrapperTests method testIOExceptionRetry.

public void testIOExceptionRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueMillis(500));
    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();
    assertThat(mockSleeper.getCount(), equalTo(1));
    assertThat(response.getStatusCode(), equalTo(200));
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Compute(com.google.api.services.compute.Compute) MockGoogleCredential(com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockSleeper(com.google.api.client.testing.util.MockSleeper)

Example 2 with HttpRequest

use of com.google.api.client.http.HttpRequest in project AndroidSDK-RecipeBook by gabu.

the class EditActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit);
    mEditText = (EditText) findViewById(R.id.edit_text);
    // インテントからIDを取得
    Intent intent = getIntent();
    mDocId = intent.getStringExtra("docId");
    // GoogleTransportを取得して
    mTransport = Recipe098.getTransport();
    // URLを生成して
    String url = GOOGLE_DOCS_API_URL + "download/documents/Export?docId=" + mDocId + "&exportFormat=txt";
    // GoogleTransportからGETリクエストを生成
    HttpRequest request = mTransport.buildGetRequest();
    // URLをセット
    request.setUrl(url);
    HttpResponse response;
    try {
        // HTTPリクエストを実行!
        response = request.execute();
        // HTTPレスポンスをStringにパースします。
        // Googleドキュメントの文書をtxtでダウンロードすると
        // 改行コードが"\r\n"なので"\n"に置換します。
        mEditText.setText(response.parseAsString().replaceAll("\r\n", "\n"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpResponse(com.google.api.client.http.HttpResponse) Intent(android.content.Intent) IOException(java.io.IOException)

Example 3 with HttpRequest

use of com.google.api.client.http.HttpRequest 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 4 with HttpRequest

use of com.google.api.client.http.HttpRequest in project beam by apache.

the class GcsUtilTest method googleJsonResponseException.

/**
   * Builds a fake GoogleJsonResponseException for testing API error handling.
   */
private static GoogleJsonResponseException googleJsonResponseException(final int status, final String reason, final String message) throws IOException {
    final JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.setReason(reason);
            errorInfo.setMessage(message);
            errorInfo.setFactory(jsonFactory);
            GenericJson error = new GenericJson();
            error.set("code", status);
            error.set("errors", Arrays.asList(errorInfo));
            error.setFactory(jsonFactory);
            GenericJson errorResponse = new GenericJson();
            errorResponse.set("error", error);
            errorResponse.setFactory(jsonFactory);
            return new MockLowLevelHttpRequest().setResponse(new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()).setContentType(Json.MEDIA_TYPE).setStatusCode(status));
        }
    };
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    return GoogleJsonResponseException.from(jsonFactory, response);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) HttpTransport(com.google.api.client.http.HttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) ErrorInfo(com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo) JsonFactory(com.google.api.client.json.JsonFactory) HttpResponse(com.google.api.client.http.HttpResponse) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 5 with HttpRequest

use of com.google.api.client.http.HttpRequest in project beam by apache.

the class RetryHttpInitializerWrapper method initialize.

/**
     * Initializes the given request.
     */
@Override
public final void initialize(final HttpRequest request) {
    // 2 minutes read timeout
    request.setReadTimeout(2 * ONEMINITUES);
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
    request.setInterceptor(wrappedCredential);
    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {

        @Override
        public boolean handleResponse(final HttpRequest request, final HttpResponse response, final boolean supportsRetry) throws IOException {
            if (wrappedCredential.handleResponse(request, response, supportsRetry)) {
                // and no backoff is desired.
                return true;
            } else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
                // Otherwise, we defer to the judgement of
                // our internal backoff handler.
                LOG.info("Retrying " + request.getUrl().toString());
                return true;
            } else {
                return false;
            }
        }
    });
    request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) HttpResponse(com.google.api.client.http.HttpResponse) IOException(java.io.IOException) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff)

Aggregations

HttpRequest (com.google.api.client.http.HttpRequest)31 IOException (java.io.IOException)21 HttpResponse (com.google.api.client.http.HttpResponse)19 GenericUrl (com.google.api.client.http.GenericUrl)15 HttpTransport (com.google.api.client.http.HttpTransport)9 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)8 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)8 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)7 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)6 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)5 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)5 JsonFactory (com.google.api.client.json.JsonFactory)5 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)5 HttpBackOffIOExceptionHandler (com.google.api.client.http.HttpBackOffIOExceptionHandler)4 HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)4 HttpResponseException (com.google.api.client.http.HttpResponseException)4 HttpUnsuccessfulResponseHandler (com.google.api.client.http.HttpUnsuccessfulResponseHandler)4 JsonHttpContent (com.google.api.client.http.json.JsonHttpContent)4 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)4 ExponentialBackOff (com.google.api.client.util.ExponentialBackOff)4