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

The following examples show how to use com.google.api.client.http.HttpRequest#setReadTimeout() . 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: RetryHttpInitializerWrapper.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Initializes the given request. */
@Override
public final void initialize(final HttpRequest request) {
  request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout
  final HttpUnsuccessfulResponseHandler backoffHandler =
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
  request.setInterceptor(wrappedCredential);
  request.setUnsuccessfulResponseHandler(
      (request1, response, supportsRetry) -> {
        if (wrappedCredential.handleResponse(request1, response, supportsRetry)) {
          // If credential decides it can handle it, the return code or message indicated
          // 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));
}
 
Example 2
Source File: RetryHttpInitializerWrapper.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Initializes the given request. */
@Override
public final void initialize(final HttpRequest request) {
  request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout
  final HttpUnsuccessfulResponseHandler backoffHandler =
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
  request.setInterceptor(wrappedCredential);
  request.setUnsuccessfulResponseHandler(
      (request1, response, supportsRetry) -> {
        if (wrappedCredential.handleResponse(request1, response, supportsRetry)) {
          // If credential decides it can handle it, the return code or message indicated
          // 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));
}
 
Example 3
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
<T> T makePostRequest(
    String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
    throws IOException, InvalidTokenException, PermissionDeniedException {
  // Wait for write permit before making request
  writeRateLimiter.acquire();

  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest postRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);
  postRequest.setReadTimeout(2 * 60000); // 2 minutes read timeout
  HttpResponse response;

  try {
    response = postRequest.execute();
  } catch (HttpResponseException e) {
    response =
        handleHttpResponseException(
            () ->
                requestFactory.buildPostRequest(
                    new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent),
            e);
  }

  Preconditions.checkState(response.getStatusCode() == 200);
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  if (clazz.isAssignableFrom(String.class)) {
    return (T) result;
  } else {
    return objectMapper.readValue(result, clazz);
  }
}
 
Example 4
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 5
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
public Long deleteBundle(Bundle bundle) throws IOException {
	Long deployedRevision = getDeployedRevision(bundle);

	if (deployedRevision == bundle.getRevision()) { // the same version is the active bundle deactivate first
		deactivateBundle(bundle);
	}

	GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/%s/%s/revisions/%d",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName(),
			bundle.getRevision()));

	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	headers.setContentType("application/octet-stream");
	HttpRequest deleteRestRequest = requestFactory.buildDeleteRequest(url);
	deleteRestRequest.setReadTimeout(0);
	deleteRestRequest.setHeaders(headers);

	HttpResponse response = null;
	response = executeAPI(profile, deleteRestRequest);

	//		String deleteResponse = response.parseAsString();
	AppConfig deleteResponse = response.parseAs(AppConfig.class);
	if (log.isInfoEnabled())
		log.info(PrintUtil.formatResponse(response, gson.toJson(deleteResponse).toString()));
	applyDelay();
	return deleteResponse.getRevision();
}
 
Example 6
Source File: CloudClientLibGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
      ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
  request.setReadTimeout(60000);  // 60 seconds is the max App Engine request time
  HttpResponse response = request.execute();
  if (response.getStatusCode() >= 300) {
    throw new IOException("Client Generation failed at server side: " + response.getContent());
  } else {
    return response.getContent();
  }
}
 
Example 7
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 8
Source File: RetryHttpRequestInitializer.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  // Set a timeout for hanging-gets.
  // TODO: Do this exclusively for work requests.
  request.setReadTimeout(HANGING_GET_TIMEOUT_SEC * 1000);
  request.setWriteTimeout(this.writeTimeout);

  LoggingHttpBackOffHandler loggingHttpBackOffHandler =
      new LoggingHttpBackOffHandler(
          sleeper,
          // Back off on retryable http errors and IOExceptions.
          // A back-off multiplier of 2 raises the maximum request retrying time
          // to approximately 5 minutes (keeping other back-off parameters to
          // their default values).
          new ExponentialBackOff.Builder().setNanoClock(nanoClock).setMultiplier(2).build(),
          new ExponentialBackOff.Builder().setNanoClock(nanoClock).setMultiplier(2).build(),
          ignoredResponseCodes,
          this.customHttpErrors);

  request.setUnsuccessfulResponseHandler(loggingHttpBackOffHandler);
  request.setIOExceptionHandler(loggingHttpBackOffHandler);

  // Set response initializer
  if (responseInterceptor != null) {
    request.setResponseInterceptor(responseInterceptor);
  }
}
 
Example 9
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 10
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 11
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 12
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
public void initMfa() throws IOException {

		// any simple get request can be used to - we just need to get an access token
		// whilst the mfatoken is still valid

		// trying to construct the URL like
		// https://api.enterprise.apigee.com/v1/organizations/apigee-cs/apis/taskservice/
		// success response is ignored
		if (accessToken == null) {
			log.info("initialising MFA");

			GenericUrl url = new GenericUrl(
					format("%s/%s/organizations/%s",
							profile.getHostUrl(),
							profile.getApi_version(),
							profile.getOrg()));

			HttpRequest restRequest = requestFactory.buildGetRequest(url);
			restRequest.setReadTimeout(0);
			HttpHeaders headers = new HttpHeaders();
			headers.setAccept("application/json");
			restRequest.setHeaders(headers);

			try {
				executeAPI(profile, restRequest);
				//ignore response - we just wanted the MFA initialised
				log.info("initialising MFA completed");
			} catch (HttpResponseException e) {
				log.error(e.getMessage());
				//throw error as there is no point in continuing
				throw e;
			}
		}
	}
 
Example 13
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the last revision of a given apiproxy or sharedflow.
 *
 * @param bundle the application bundle to check
 *
 * @return the highest revision number of the deployed bundle regardless of environment
 *
 * @throws IOException exception if something went wrong communicating with the rest endpoint
 */
public Long getLatestRevision(Bundle bundle) throws IOException {

	// trying to construct the URL like
	// https://api.enterprise.apigee.com/v1/organizations/apigee-cs/apis/taskservice/
	// response is like
	// {
	// "name" : "taskservice1",
	// "revision" : [ "1" ]
	// }

	GenericUrl url = new GenericUrl(
			format("%s/%s/organizations/%s/%s/%s/",
					profile.getHostUrl(),
					profile.getApi_version(),
					profile.getOrg(),
					bundle.getType().getPathName(),
					bundle.getName()));

	HttpRequest restRequest = requestFactory.buildGetRequest(url);
	restRequest.setReadTimeout(0);
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	restRequest.setHeaders(headers);

	Long revision = null;

	try {
		HttpResponse response = executeAPI(profile, restRequest);
		AppRevision apprev = response.parseAs(AppRevision.class);
		Collections.sort(apprev.revision, new StringToIntComparator());
		revision = Long.parseLong(apprev.revision.get(0));
		log.info(PrintUtil.formatResponse(response, gson.toJson(apprev)));
	} catch (HttpResponseException e) {
		log.error(e.getMessage());
	}
	return revision;
}
 
Example 14
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 15
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Update a revsion of a bunlde with the supplied content.
 *
 * @param bundleFile reference to the local bundle file
 * @param bundle     the bundle descriptor to use
 *
 * @return the revision of the uploaded bundle
 *
 * @throws IOException exception if something went wrong communicating with the rest endpoint
 */
public Long updateBundle(String bundleFile, Bundle bundle) throws IOException {

	FileContent fContent = new FileContent("application/octet-stream",
			new File(bundleFile));
	//System.out.println("\n\n\nFile path: "+ new File(bundleFile).getCanonicalPath().toString());
	log.debug("URL parameters API Version {}", profile.getApi_version());
	log.debug("URL parameters URL {}", profile.getHostUrl());
	log.debug("URL parameters Org {}", profile.getOrg());
	log.debug("URL parameters App {}", bundle.getName());

	StringBuilder url = new StringBuilder();

	url.append(format("%s/%s/organizations/%s/%s/%s/revisions/%d",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName(),
			bundle.getRevision()));

	if (getProfile().isValidate()) {
		url.append("?validate=true");
	}

	HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent);
	restRequest.setReadTimeout(0);
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	restRequest.setHeaders(headers);
	Long result;
	try {
		HttpResponse response = executeAPI(profile, restRequest);
		AppConfig appconf = response.parseAs(AppConfig.class);
		result = appconf.getRevision();
		if (log.isInfoEnabled())
			log.info(PrintUtil.formatResponse(response, gson.toJson(appconf)));
		applyDelay();
	} catch (HttpResponseException e) {
		log.error(e.getMessage());
		throw new IOException(e.getMessage());
	}

	return result;

}
 
Example 16
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Import a bundle into the Apigee gateway.
 *
 * @param bundleFile reference to the local bundle file
 * @param bundle     the bundle descriptor to use
 *
 * @return the revision of the uploaded bundle
 *
 * @throws IOException exception if something went wrong communicating with the rest endpoint
 */
public Long uploadBundle(String bundleFile, Bundle bundle) throws IOException {

	FileContent fContent = new FileContent("application/octet-stream",
			new File(bundleFile));
	//testing
	log.debug("URL parameters API Version {}", (profile.getApi_version()));
	log.debug("URL parameters URL {}", (profile.getHostUrl()));
	log.debug("URL parameters Org {}", (profile.getOrg()));
	log.debug("URL parameters App {}", bundle.getName());

	StringBuilder url = new StringBuilder();

	url.append(format("%s/%s/organizations/%s/%s?action=import&name=%s",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName()));

	if (getProfile().isValidate()) {
		url.append("&validate=true");
	}

	HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent);
	restRequest.setReadTimeout(0);
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	restRequest.setHeaders(headers);

	Long result;
	try {
		HttpResponse response = executeAPI(profile, restRequest);
		AppConfig apiResult = response.parseAs(AppConfig.class);
		result = apiResult.getRevision();
		if (log.isInfoEnabled())
			log.info(PrintUtil.formatResponse(response, gson.toJson(apiResult)));
		applyDelay();
	} catch (HttpResponseException e) {
		log.error(e.getMessage(), e);
		throw new IOException(e.getMessage(), e);
	}

	return result;

}
 
Example 17
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 18
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 19
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");
}
 
Example 20
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);
}