Search in sources :

Example 6 with HttpBackOffUnsuccessfulResponseHandler

use of com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler in project ddf by codice.

the class MetadataConfigurationParser method generateHttpRequest.

private HttpRequest generateHttpRequest(PropertyResolver propertyResolver, HttpTransport httpTransport) throws IOException {
    HttpRequest httpRequest = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(propertyResolver.getResolvedString()));
    httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setBackOffRequired(HttpBackOffUnsuccessfulResponseHandler.BackOffRequired.ALWAYS));
    httpRequest.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
    return httpRequest;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) GenericUrl(com.google.api.client.http.GenericUrl) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff)

Example 7 with HttpBackOffUnsuccessfulResponseHandler

use of com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler in project gradle by gradle.

the class RetryHttpInitializerWrapper method initialize.

@Override
public void initialize(HttpRequest request) {
    // Turn off request logging, this can end up logging OAUTH
    // tokens which should not ever be in a build log
    final boolean loggingEnabled = false;
    request.setLoggingEnabled(loggingEnabled);
    request.setCurlLoggingEnabled(loggingEnabled);
    disableHttpTransportLogging();
    request.setReadTimeout((int) DEFAULT_READ_TIMEOUT_MILLIS);
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
    final Credential credential = credentialSupplier.get();
    request.setInterceptor(credential);
    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {

        @Override
        public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
            // Turn off request logging unless debug mode is enabled
            request.setLoggingEnabled(loggingEnabled);
            request.setCurlLoggingEnabled(loggingEnabled);
            if (credential.handleResponse(request, response, supportsRetry)) {
                // something specific to authentication, 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());
                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) Credential(com.google.api.client.auth.oauth2.Credential) 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)

Example 8 with HttpBackOffUnsuccessfulResponseHandler

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

the class RetryHttpInitializerWrapper method initialize.

@Override
public void initialize(HttpRequest httpRequest) {
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(((int) maxWait.getMillis())).build()).setSleeper(sleeper);
    httpRequest.setInterceptor(wrappedCredential);
    httpRequest.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {

        int retry = 0;

        @Override
        public boolean handleResponse(HttpRequest request, HttpResponse response, 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.
                logger.debug("Retrying [{}] times : [{}]", retry, request.getUrl());
                return true;
            } else {
                return false;
            }
        }
    });
    httpRequest.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(((int) maxWait.getMillis())).build()).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)

Example 9 with HttpBackOffUnsuccessfulResponseHandler

use of com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler in project java-docs-samples by GoogleCloudPlatform.

the class HttpExample method publishMessage.

// [END iot_http_getconfig]
// [START iot_http_publish]
/**
 * Publish an event or state message using Cloud IoT Core via the HTTP API.
 */
public static void publishMessage(String payload, String urlPath, String messageType, String token, String projectId, String cloudRegion, String registryId, String deviceId) throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
    // Build the resource path of the device that is going to be authenticated.
    String devicePath = String.format("projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryId, deviceId);
    String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";
    // Data sent through the wire has to be base64 encoded.
    Base64.Encoder encoder = Base64.getEncoder();
    String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));
    urlPath = urlPath + devicePath + ":" + urlSuffix;
    final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    HttpHeaders heads = new HttpHeaders();
    heads.setAuthorization(String.format("Bearer %s", token));
    heads.setContentType("application/json; charset=UTF-8");
    heads.setCacheControl("no-cache");
    // Add post data. The data sent depends on whether we're updating state or publishing events.
    JSONObject data = new JSONObject();
    if (messageType.equals("event")) {
        data.put("binary_data", encPayload);
    } else {
        JSONObject state = new JSONObject();
        state.put("binary_data", encPayload);
        data.put("state", state);
    }
    ByteArrayContent content = new ByteArrayContent("application/json", data.toString().getBytes("UTF-8"));
    final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
    req.setHeaders(heads);
    req.setContent(content);
    req.setRequestMethod("POST");
    ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
    req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
    HttpResponse res = req.execute();
    System.out.println(res.getStatusCode());
    System.out.println(res.getStatusMessage());
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Base64(java.util.Base64) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JwtBuilder(io.jsonwebtoken.JwtBuilder) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) JSONObject(org.json.JSONObject) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 10 with HttpBackOffUnsuccessfulResponseHandler

use of com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler in project google-auth-library-java by google.

the class ServiceAccountCredentials method refreshAccessToken.

/**
 * Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT).
 */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (createScopedRequired()) {
        throw new IOException("Scopes not configured for service account. Scoped should be specified" + " by calling createScoped or passing scopes to constructor.");
    }
    JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
    long currentTime = clock.currentTimeMillis();
    String assertion = createAssertion(jsonFactory, currentTime);
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("grant_type", GRANT_TYPE);
    tokenRequest.set("assertion", assertion);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
    request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setBackOffRequired(new BackOffRequired() {

        public boolean isRequired(HttpResponse response) {
            int code = response.getStatusCode();
            return (// Server error --- includes timeout errors, which use 500 instead of 408
            code / 100 == 5 || // https://github.com/google/google-api-java-client/issues/662
            code == 403);
        }
    }));
    HttpResponse response;
    try {
        response = request.execute();
    } catch (IOException e) {
        throw new IOException("Error getting access token for service account: ", e);
    }
    GenericData responseData = response.parseAs(GenericData.class);
    String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
    int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000L;
    return new AccessToken(accessToken, new Date(expiresAtMilliseconds));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonFactory(com.google.api.client.json.JsonFactory) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) IOException(java.io.IOException) GenericUrl(com.google.api.client.http.GenericUrl) BackOffRequired(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired) GenericData(com.google.api.client.util.GenericData) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) Date(java.sql.Date) JsonObjectParser(com.google.api.client.json.JsonObjectParser)

Aggregations

HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)14 HttpRequest (com.google.api.client.http.HttpRequest)13 ExponentialBackOff (com.google.api.client.util.ExponentialBackOff)13 HttpResponse (com.google.api.client.http.HttpResponse)10 HttpBackOffIOExceptionHandler (com.google.api.client.http.HttpBackOffIOExceptionHandler)9 IOException (java.io.IOException)7 HttpUnsuccessfulResponseHandler (com.google.api.client.http.HttpUnsuccessfulResponseHandler)6 GenericUrl (com.google.api.client.http.GenericUrl)5 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)4 JsonObjectParser (com.google.api.client.json.JsonObjectParser)4 HttpHeaders (com.google.api.client.http.HttpHeaders)2 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)2 JwtBuilder (io.jsonwebtoken.JwtBuilder)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 Credential (com.google.api.client.auth.oauth2.Credential)1 ByteArrayContent (com.google.api.client.http.ByteArrayContent)1 BackOffRequired (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired)1 HttpContent (com.google.api.client.http.HttpContent)1 HttpTransport (com.google.api.client.http.HttpTransport)1