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;
}
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));
}
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));
}
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());
}
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));
}
Aggregations