Java Code Examples for com.google.api.client.http.HttpRequest#setConnectTimeout()

The following examples show how to use com.google.api.client.http.HttpRequest#setConnectTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoogleClientFactory.java    From kayenta with Apache License 2.0 5 votes vote down vote up
static HttpRequestInitializer setHttpTimeout(final GoogleCredentials credentials) {
  return new HttpCredentialsAdapter(credentials) {
    @Override
    public void initialize(HttpRequest httpRequest) throws IOException {
      super.initialize(httpRequest);
      httpRequest.setConnectTimeout(2 * 60000); // 2 minutes connect timeout
      httpRequest.setReadTimeout(2 * 60000); // 2 minutes read timeout
    }
  };
}
 
Example 2
Source File: GoogleCredentials.java    From halyard with Apache License 2.0 5 votes vote down vote up
public static HttpRequestInitializer setHttpTimeout(
    final com.google.auth.oauth2.GoogleCredentials credentials) {
  return new HttpCredentialsAdapter(credentials) {
    public void initialize(HttpRequest request) throws IOException {
      super.initialize(request);
      request.setConnectTimeout((int) TimeUnit.MINUTES.toMillis(2));
      request.setReadTimeout((int) TimeUnit.MINUTES.toMillis(2));
      request.setUnsuccessfulResponseHandler(
          new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
    }
  };
}
 
Example 3
Source File: GoogleUtils.java    From kork with Apache License 2.0 5 votes vote down vote up
static HttpRequestInitializer setTimeoutsAndRetryBehavior(final GoogleCredentials credentials) {
  return new HttpCredentialsAdapter(credentials) {
    public void initialize(HttpRequest request) throws IOException {
      super.initialize(request);
      request.setConnectTimeout(CONNECT_TIMEOUT);
      request.setReadTimeout(READ_TIMEOUT);
      HttpBackOffUnsuccessfulResponseHandler unsuccessfulResponseHandler =
          new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff());
      unsuccessfulResponseHandler.setBackOffRequired(
          HttpBackOffUnsuccessfulResponseHandler.BackOffRequired.ON_SERVER_ERROR);
      request.setUnsuccessfulResponseHandler(unsuccessfulResponseHandler);
    }
  };
}
 
Example 4
Source File: GoogleAnalyticsUtils.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static Analytics buildClient(GoogleAnalytics googleAnalytics) {
	Analytics analytics;
	try {
		PrivateKey privateKey= SecurityUtils.loadPrivateKeyFromKeyStore(
				SecurityUtils.getPkcs12KeyStore(), new ByteArrayInputStream(googleAnalytics.getServiceAccountP12FileContent()),
				"notasecret", "privatekey", "notasecret");

		HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
		JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

		Set<String> scopes = new HashSet<>();
		scopes.add(AnalyticsScopes.ANALYTICS_READONLY);

		final GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
				.setJsonFactory(jsonFactory)
				.setServiceAccountId(googleAnalytics.getServiceAccountId())
				.setServiceAccountScopes(scopes)
				.setServiceAccountPrivateKey(privateKey)
				.build();

		HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
			@Override
			public void initialize(HttpRequest httpRequest) throws IOException {
				credential.initialize(httpRequest);
				httpRequest.setConnectTimeout(3 * 60000);  // 3 minutes connect timeout
				httpRequest.setReadTimeout(3 * 60000);  // 3 minutes read timeout
			}
		};
		analytics = new Analytics.Builder(httpTransport, jsonFactory, httpRequestInitializer)
				.setApplicationName("WallRide")
				.build();
	} catch (Exception e) {
		logger.warn("Failed to synchronize with Google Analytics", e);
		throw new GoogleAnalyticsException(e);
	}

	return analytics;
}
 
Example 5
Source File: OAuth2Utils.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
static boolean runningOnComputeEngine(HttpTransport transport,
    SystemEnvironmentProvider environment) {
  // If the environment has requested that we do no GCE checks, return immediately.
  if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
    return false;
  }

  GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
  for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
    try {
      HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
      request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
      request.getHeaders().set("Metadata-Flavor", "Google");
      HttpResponse response = request.execute();
      try {
        HttpHeaders headers = response.getHeaders();
        return headersContainValue(headers, "Metadata-Flavor", "Google");
      } finally {
        response.disconnect();
      }
    } catch (SocketTimeoutException expected) {
      // Ignore logging timeouts which is the expected failure mode in non GCE environments.
    } catch (IOException e) {
      LOGGER.log(
          Level.WARNING,
          "Failed to detect whether we are running on Google Compute Engine.",
          e);
    }
  }
  return false;
}
 
Example 6
Source File: HttpHandler.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP request based on the message context.
 *
 * @param msgContext the Axis message context
 * @return a new {@link HttpRequest} with content and headers populated
 */
private HttpRequest createHttpRequest(MessageContext msgContext)
    throws SOAPException, IOException {
  Message requestMessage =
      Preconditions.checkNotNull(
          msgContext.getRequestMessage(), "Null request message on message context");
  
  // Construct the output stream.
  String contentType = requestMessage.getContentType(msgContext.getSOAPConstants());
  ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE);

  if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
    logger.debug("Compressing request");
    try (GZIPOutputStream gzipOs = new GZIPOutputStream(bos, BUFFER_SIZE)) {
      requestMessage.writeTo(gzipOs);
    }
  } else {
    logger.debug("Not compressing request");
    requestMessage.writeTo(bos);
  }

  HttpRequest httpRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(msgContext.getStrProp(MessageContext.TRANS_URL)),
          new ByteArrayContent(contentType, bos.toByteArray()));

  int timeoutMillis = msgContext.getTimeout();
  if (timeoutMillis >= 0) {
    logger.debug("Setting read and connect timeout to {} millis", timeoutMillis);
    // These are not the same, but MessageContext has only one definition of timeout.
    httpRequest.setReadTimeout(timeoutMillis);
    httpRequest.setConnectTimeout(timeoutMillis);
  }

  // Copy the request headers from the message context to the post request.
  setHttpRequestHeaders(msgContext, httpRequest);

  return httpRequest;
}
 
Example 7
Source File: FirebaseRequestInitializer.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) {
  request.setConnectTimeout(connectTimeoutMillis);
  request.setReadTimeout(readTimeoutMillis);
}
 
Example 8
Source File: SplunkHttpSinkTask.java    From kafka-connect-splunk with Apache License 2.0 4 votes vote down vote up
@Override
  public void start(Map<String, String> map) {
    this.config = new SplunkHttpSinkConnectorConfig(map);

    java.util.logging.Logger logger = java.util.logging.Logger.getLogger(HttpTransport.class.getName());
    logger.addHandler(new RequestLoggingHandler(log));
    if (this.config.curlLoggingEnabled) {
      logger.setLevel(Level.ALL);
    } else {
      logger.setLevel(Level.WARNING);
    }

    log.info("Starting...");

    NetHttpTransport.Builder transportBuilder = new NetHttpTransport.Builder();

    if (!this.config.validateCertificates) {
      log.warn("Disabling ssl certificate verification.");
      try {
        transportBuilder.doNotValidateCertificate();
      } catch (GeneralSecurityException e) {
        throw new IllegalStateException("Exception thrown calling transportBuilder.doNotValidateCertificate()", e);
      }
    }

    if (this.config.hasTrustStorePath) {
      log.info("Loading trust store from {}.", this.config.trustStorePath);
      try (FileInputStream inputStream = new FileInputStream(this.config.trustStorePath)) {
        transportBuilder.trustCertificatesFromJavaKeyStore(inputStream, this.config.trustStorePassword);
      } catch (GeneralSecurityException | IOException ex) {
        throw new IllegalStateException("Exception thrown while setting up trust certificates.", ex);
      }
    }

    this.transport = transportBuilder.build();
    final String authHeaderValue = String.format("Splunk %s", this.config.authToken);
    final JsonObjectParser jsonObjectParser = new JsonObjectParser(jsonFactory);

    final String userAgent = String.format("kafka-connect-splunk/%s", version());
    final boolean curlLogging = this.config.curlLoggingEnabled;
    this.httpRequestInitializer = new HttpRequestInitializer() {
      @Override
      public void initialize(HttpRequest httpRequest) throws IOException {
        httpRequest.getHeaders().setAuthorization(authHeaderValue);
        httpRequest.getHeaders().setAccept(Json.MEDIA_TYPE);
        httpRequest.getHeaders().setUserAgent(userAgent);
        httpRequest.setParser(jsonObjectParser);
        httpRequest.setEncoding(new GZipEncoding());
        httpRequest.setThrowExceptionOnExecuteError(false);
        httpRequest.setConnectTimeout(config.connectTimeout);
        httpRequest.setReadTimeout(config.readTimeout);
        httpRequest.setCurlLoggingEnabled(curlLogging);
//        httpRequest.setLoggingEnabled(curlLogging);
      }
    };

    this.httpRequestFactory = this.transport.createRequestFactory(this.httpRequestInitializer);

    this.eventCollectorUrl = new GenericUrl();
    this.eventCollectorUrl.setRawPath("/services/collector/event");
    this.eventCollectorUrl.setPort(this.config.splunkPort);
    this.eventCollectorUrl.setHost(this.config.splunkHost);

    if (this.config.ssl) {
      this.eventCollectorUrl.setScheme("https");
    } else {
      this.eventCollectorUrl.setScheme("http");
    }

    log.info("Setting Splunk Http Event Collector Url to {}", this.eventCollectorUrl);
  }
 
Example 9
Source File: HttpClientRequestInitializer.java    From steem-java-api-wrapper with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
    request.setConnectTimeout(SteemJConfig.getInstance().getIdleTimeout());
    request.setReadTimeout(SteemJConfig.getInstance().getResponseTimeout());
    request.setNumberOfRetries(0);
}
 
Example 10
Source File: RetryHttpInitializer.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) {
  // Credential must be the interceptor to fill in accessToken fields.
  request.setInterceptor(credential);

  // Request will be retried if server errors (5XX) or I/O errors are encountered.
  request.setNumberOfRetries(options.getMaxRequestRetries());

  // Set the timeout configurations.
  request.setConnectTimeout(Math.toIntExact(options.getConnectTimeout().toMillis()));
  request.setReadTimeout(Math.toIntExact(options.getReadTimeout().toMillis()));

  // IOExceptions such as "socket timed out" of "insufficient bytes written" will follow a
  // straightforward backoff.
  HttpBackOffIOExceptionHandler exceptionHandler =
      new HttpBackOffIOExceptionHandler(new ExponentialBackOff());
  if (sleeperOverride != null) {
    exceptionHandler.setSleeper(sleeperOverride);
  }

  // Supply a new composite handler for unsuccessful return codes. 401 Unauthorized will be
  // handled by the Credential, 410 Gone will be logged, and 5XX will be handled by a backoff
  // handler.
  LoggingResponseHandler loggingResponseHandler =
      new LoggingResponseHandler(
          new CredentialOrBackoffResponseHandler(),
          exceptionHandler,
          ImmutableSet.of(HttpStatus.SC_GONE, HttpStatus.SC_SERVICE_UNAVAILABLE),
          ImmutableSet.of(HTTP_SC_TOO_MANY_REQUESTS));
  request.setUnsuccessfulResponseHandler(loggingResponseHandler);
  request.setIOExceptionHandler(loggingResponseHandler);

  if (isNullOrEmpty(request.getHeaders().getUserAgent())
      && !isNullOrEmpty(options.getDefaultUserAgent())) {
    logger.atFiner().log(
        "Request is missing a user-agent, adding default value of '%s'",
        options.getDefaultUserAgent());
    request.getHeaders().setUserAgent(options.getDefaultUserAgent());
  }

  request.getHeaders().putAll(options.getHttpHeaders());
}
 
Example 11
Source File: GcsStorageService.java    From front50 with Apache License 2.0 4 votes vote down vote up
public GcsStorageService(
    String bucketName,
    String bucketLocation,
    String basePath,
    String projectName,
    String credentialsPath,
    String applicationVersion,
    String dataFilename,
    Integer connectTimeoutSec,
    Integer readTimeoutSec,
    int maxWaitInterval,
    int retryIntervalBase,
    int jitterMultiplier,
    int maxRetries,
    TaskScheduler taskScheduler,
    Registry registry) {
  Storage storage;

  try {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    GoogleCredentials credentials = loadCredential(credentialsPath);
    HttpRequestInitializer requestInitializer =
        new HttpCredentialsAdapter(credentials) {
          public void initialize(HttpRequest request) throws IOException {
            super.initialize(request);
            request.setConnectTimeout(connectTimeoutSec * 1000);
            request.setReadTimeout(readTimeoutSec * 1000);
          }
        };

    String applicationName = "Spinnaker/" + applicationVersion;
    storage =
        new Storage.Builder(httpTransport, jsonFactory, requestInitializer)
            .setApplicationName(applicationName)
            .build();
  } catch (IOException | java.security.GeneralSecurityException e) {
    throw new IllegalStateException(e);
  }

  // "google.com:" is deprecated but may be in certain old projects.
  this.bucketName = bucketName.replace("google.com:", "");
  this.bucketLocation = bucketLocation;
  this.basePath = basePath;
  this.projectName = projectName;
  this.storage = storage;
  this.obj_api = this.storage.objects();
  this.dataFilename = dataFilename;
  this.taskScheduler = taskScheduler;
  this.registry = registry;
  this.safeRetry =
      GoogleCommonSafeRetry.builder()
          .maxWaitInterval(maxWaitInterval)
          .retryIntervalBase(retryIntervalBase)
          .jitterMultiplier(jitterMultiplier)
          .maxRetries(maxRetries)
          .build();

  Id id = registry.createId("google.storage.invocation");
  deleteTimer = id.withTag("method", "delete");
  purgeTimer = id.withTag("method", "purgeTimestamp");
  loadTimer = id.withTag("method", "load");
  listTimer = id.withTag("method", "list");
  mediaDownloadTimer = id.withTag("method", "mediaDownload");
  insertTimer = id.withTag("method", "insert");
  patchTimer = id.withTag("method", "patch");
}