Search in sources :

Example 1 with HttpBackOffUnsuccessfulResponseHandler

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

the class MetadataConfigurationParser method buildEntityDescriptor.

private void buildEntityDescriptor(String entityDescription) throws IOException {
    EntityDescriptor entityDescriptor = null;
    entityDescription = entityDescription.trim();
    if (entityDescription.startsWith(HTTPS) || entityDescription.startsWith(HTTP)) {
        if (entityDescription.startsWith(HTTP)) {
            LOGGER.warn("Retrieving metadata via HTTP instead of HTTPS. The metadata configuration is unsafe!!!");
        }
        PropertyResolver propertyResolver = new PropertyResolver(entityDescription);
        HttpTransport httpTransport = new NetHttpTransport();
        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()));
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
        ListenableFuture<HttpResponse> httpResponseFuture = service.submit(httpRequest::execute);
        Futures.addCallback(httpResponseFuture, new FutureCallback<HttpResponse>() {

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse != null) {
                    try {
                        String parsedResponse = httpResponse.parseAsString();
                        buildEntityDescriptor(parsedResponse);
                    } catch (IOException e) {
                        LOGGER.info("Unable to parse metadata from: {}", httpResponse.getRequest().getUrl().toString(), e);
                    }
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                LOGGER.info("Unable to retrieve metadata.", throwable);
            }
        });
        service.shutdown();
    } else if (entityDescription.startsWith(FILE + System.getProperty("ddf.home"))) {
        String pathStr = StringUtils.substringAfter(entityDescription, FILE);
        Path path = Paths.get(pathStr);
        if (Files.isReadable(path)) {
            try (InputStream fileInputStream = Files.newInputStream(path)) {
                entityDescriptor = readEntityDescriptor(new InputStreamReader(fileInputStream, "UTF-8"));
            }
        }
    } else if (entityDescription.startsWith("<") && entityDescription.endsWith(">")) {
        entityDescriptor = readEntityDescriptor(new StringReader(entityDescription));
    } else {
        LOGGER.info("Skipping unknown metadata configuration value: {}", entityDescription);
    }
    if (entityDescriptor != null) {
        entityDescriptorMap.put(entityDescriptor.getEntityID(), entityDescriptor);
        if (updateCallback != null) {
            updateCallback.accept(entityDescriptor);
        }
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Path(java.nio.file.Path) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) PropertyResolver(org.codice.ddf.configuration.PropertyResolver) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) StringReader(java.io.StringReader) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService)

Example 2 with HttpBackOffUnsuccessfulResponseHandler

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

the class RetryHttpInitializerWrapper method initialize.

/**
 * Initialize an HttpRequest.
 *
 * @param request
 *          an HttpRequest that should be initialized
 */
public void initialize(HttpRequest request) {
    // 2 minutes read timeout
    request.setReadTimeout(2 * MILLIS_PER_MINUTE);
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
    request.setInterceptor(wrappedCredential);
    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {

        public boolean handleResponse(final HttpRequest request, final HttpResponse response, final boolean supportsRetry) throws IOException {
            if (wrappedCredential.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().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)

Example 3 with HttpBackOffUnsuccessfulResponseHandler

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

the class HttpExample method getConfig.

// [END iot_http_jwt]
// [START iot_http_getconfig]
/**
 * Publish an event or state message using Cloud IoT Core via the HTTP API.
 */
public static void getConfig(String urlPath, String token, String projectId, String cloudRegion, String registryId, String deviceId, String version) 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);
    urlPath = urlPath + devicePath + "/config?local_version=" + version;
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
    HttpHeaders heads = new HttpHeaders();
    heads.setAuthorization(String.format("Bearer %s", token));
    heads.setContentType("application/json; charset=UTF-8");
    heads.setCacheControl("no-cache");
    req.setHeaders(heads);
    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());
    InputStream in = res.getContent();
    System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) InputStreamReader(java.io.InputStreamReader) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) InputStream(java.io.InputStream) 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) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 4 with HttpBackOffUnsuccessfulResponseHandler

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

the class RetryHttpInitializerWrapper method initialize.

/**
 * Initializes the given request.
 */
@Override
public final void initialize(final HttpRequest request) {
    // 2 minutes read timeout
    request.setReadTimeout(2 * ONE_MINUTE_MILLIS);
    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)) {
                // something specific to authentication, and no backoff is desired.
                return true;
            } else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
                // Otherwise, we defer to the judgment 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)

Example 5 with HttpBackOffUnsuccessfulResponseHandler

use of com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler 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((request1, response, supportsRetry) -> {
        if (wrappedCredential.handleResponse(request1, response, supportsRetry)) {
            // something specific to authentication, and no backoff is desired.
            return true;
        } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) {
            // Otherwise, we defer to the judgement of our internal backoff handler.
            LOG.info("Retrying " + request1.getUrl().toString());
            return true;
        } else {
            return false;
        }
    });
    request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
Also used : HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff)

Aggregations

HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)13 HttpRequest (com.google.api.client.http.HttpRequest)12 ExponentialBackOff (com.google.api.client.util.ExponentialBackOff)12 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