com.google.api.client.googleapis.GoogleUtils Java Examples

The following examples show how to use com.google.api.client.googleapis.GoogleUtils. 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: HttpTransportFactory.java    From hadoop-connectors with Apache License 2.0 7 votes vote down vote up
/**
 * Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
 *
 * @param proxyUri Optional HTTP proxy URI to use with the transport.
 * @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
 *     proxy.
 * @return The resulting HttpTransport.
 * @throws IOException If there is an issue connecting to Google's certification server.
 * @throws GeneralSecurityException If there is a security issue with the keystore.
 */
public static ApacheHttpTransport createApacheHttpTransport(
    @Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
    throws IOException, GeneralSecurityException {
  checkArgument(
      proxyUri != null || proxyCredentials == null,
      "if proxyUri is null than proxyCredentials should be null too");

  ApacheHttpTransport transport =
      new ApacheHttpTransport.Builder()
          .trustCertificates(GoogleUtils.getCertificateTrustStore())
          .setProxy(
              proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
          .build();

  if (proxyCredentials != null) {
    ((DefaultHttpClient) transport.getHttpClient())
        .getCredentialsProvider()
        .setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
  }

  return transport;
}
 
Example #2
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * @param abstractGoogleClient Google client
 * @param requestMethod HTTP Method
 * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/"
 *        the base path from the base URL will be stripped out. The URI template can also be a
 *        full URL. URI template expansion is done using
 *        {@link UriTemplate#expand(String, String, Object, boolean)}
 * @param httpContent HTTP content or {@code null} for none
 * @param responseClass response class to parse into
 */
protected AbstractGoogleClientRequest(AbstractGoogleClient abstractGoogleClient,
    String requestMethod, String uriTemplate, HttpContent httpContent, Class<T> responseClass) {
  this.responseClass = Preconditions.checkNotNull(responseClass);
  this.abstractGoogleClient = Preconditions.checkNotNull(abstractGoogleClient);
  this.requestMethod = Preconditions.checkNotNull(requestMethod);
  this.uriTemplate = Preconditions.checkNotNull(uriTemplate);
  this.httpContent = httpContent;
  // application name
  String applicationName = abstractGoogleClient.getApplicationName();
  if (applicationName != null) {
    requestHeaders.setUserAgent(applicationName + " " + USER_AGENT_SUFFIX + "/"
            + GoogleUtils.VERSION);
  } else {
    requestHeaders.setUserAgent(USER_AGENT_SUFFIX + "/" + GoogleUtils.VERSION);
  }
  // Set the header for the Api Client version (Java and OS version)
  requestHeaders.set(API_VERSION_HEADER, ApiClientVersion.DEFAULT_VERSION);
}
 
Example #3
Source File: GoogleProxy.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/** Gets an {@link HttpTransport} that contains the proxy configuration. */
public HttpTransport getHttpTransport() throws IOException, GeneralSecurityException {
  return new NetHttpTransport.Builder()
      .trustCertificates(GoogleUtils.getCertificateTrustStore())
      .setProxy(proxy)
      .build();
}
 
Example #4
Source File: GoogleCommon.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Provides HttpTransport. If both proxyUrl and postStr is defined, it provides transport with Proxy.
 * @param proxyUrl Optional.
 * @param portStr Optional. String type for port so that user can easily pass null. (e.g: state.getProp(key))
 * @return
 * @throws NumberFormatException
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static HttpTransport newTransport(String proxyUrl, String portStr) throws NumberFormatException, GeneralSecurityException, IOException {
  if (!StringUtils.isEmpty(proxyUrl) && !StringUtils.isEmpty(portStr)) {
    return new NetHttpTransport.Builder()
                               .trustCertificates(GoogleUtils.getCertificateTrustStore())
                               .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, Integer.parseInt(portStr))))
                               .build();
  }
  return GoogleNetHttpTransport.newTrustedTransport();
}
 
Example #5
Source File: HttpTransportFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * Create an {@link NetHttpTransport} for calling Google APIs with an optional HTTP proxy.
 *
 * @param proxyUri Optional HTTP proxy URI to use with the transport.
 * @param proxyAuth Optional HTTP proxy credentials to authenticate with the transport proxy.
 * @return The resulting HttpTransport.
 * @throws IOException If there is an issue connecting to Google's certification server.
 * @throws GeneralSecurityException If there is a security issue with the keystore.
 */
public static NetHttpTransport createNetHttpTransport(
    @Nullable URI proxyUri, @Nullable PasswordAuthentication proxyAuth)
    throws IOException, GeneralSecurityException {
  checkArgument(
      proxyUri != null || proxyAuth == null,
      "if proxyUri is null than proxyAuth should be null too");

  if (proxyAuth != null) {
    // Enable "Basic" authentication on JDK 8+
    System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
    Authenticator.setDefault(
        new Authenticator() {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
            if (getRequestorType() == RequestorType.PROXY
                && getRequestingHost().equalsIgnoreCase(proxyUri.getHost())
                && getRequestingPort() == proxyUri.getPort()) {
              return proxyAuth;
            }
            return null;
          }
        });
  }

  return new NetHttpTransport.Builder()
      .trustCertificates(GoogleUtils.getCertificateTrustStore())
      .setProxy(
          proxyUri == null
              ? null
              : new Proxy(
                  Proxy.Type.HTTP, new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort())))
      .build();
}
 
Example #6
Source File: GoogleApacheHttpTransport.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link ApacheHttpTransport} that uses
 * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates.
 */
public static ApacheHttpTransport newTrustedTransport() throws GeneralSecurityException,
    IOException {
  // Set socket buffer sizes to 8192
  SocketConfig socketConfig =
      SocketConfig.custom()
          .setRcvBufSize(8192)
          .setSndBufSize(8192)
          .build();

  PoolingHttpClientConnectionManager connectionManager =
      new PoolingHttpClientConnectionManager(-1, TimeUnit.MILLISECONDS);

  // Disable the stale connection check (previously configured in the HttpConnectionParams
  connectionManager.setValidateAfterInactivity(-1);

  // Use the included trust store
  KeyStore trustStore = GoogleUtils.getCertificateTrustStore();
  SSLContext sslContext = SslUtils.getTlsSslContext();
  SslUtils.initSslContext(sslContext, trustStore, SslUtils.getPkixTrustManagerFactory());
  LayeredConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

  HttpClient client = HttpClientBuilder.create()
      .useSystemProperties()
      .setSSLSocketFactory(socketFactory)
      .setDefaultSocketConfig(socketConfig)
      .setMaxConnTotal(200)
      .setMaxConnPerRoute(20)
      .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
      .setConnectionManager(connectionManager)
      .disableRedirectHandling()
      .disableAutomaticRetries()
      .build();
  return new ApacheHttpTransport(client);
}
 
Example #7
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUserAgentSuffix() throws Exception {
  AssertUserAgentTransport transport = new AssertUserAgentTransport();
  // Specify an Application Name.
  String applicationName = "Test Application";
  transport.expectedUserAgent = applicationName + " "
      + "Google-API-Java-Client/" + GoogleUtils.VERSION + " "
      + HttpRequest.USER_AGENT_SUFFIX;
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
          applicationName).build();
  MockGoogleClientRequest<Void> request =
      new MockGoogleClientRequest<Void>(client, HttpMethods.GET, URI_TEMPLATE, null, Void.class);
  request.executeUnparsed();
}
 
Example #8
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUserAgent() throws IOException {
  AssertUserAgentTransport transport = new AssertUserAgentTransport();
  transport.expectedUserAgent = "Google-API-Java-Client/" + GoogleUtils.VERSION + " "
      + HttpRequest.USER_AGENT_SUFFIX;
  // Don't specify an Application Name.
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).build();
  MockGoogleClientRequest<Void> request =
      new MockGoogleClientRequest<>(client, HttpMethods.GET, URI_TEMPLATE, null, Void.class);
  request.executeUnparsed();
}
 
Example #9
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
ApiClientVersion() {
  this(getJavaVersion(), OS_NAME.value(), OS_VERSION.value(), GoogleUtils.VERSION);
}
 
Example #10
Source File: GoogleNetHttpTransport.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a new instance of {@link NetHttpTransport} that uses
 * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates using
 * {@link com.google.api.client.http.javanet.NetHttpTransport.Builder#trustCertificates(KeyStore)}
 * .
 *
 * <p>
 * This helper method doesn't provide for customization of the {@link NetHttpTransport}, such as
 * the ability to specify a proxy. To do use, use
 * {@link com.google.api.client.http.javanet.NetHttpTransport.Builder}, for example:
 * </p>
 *
 * <pre>
static HttpTransport newProxyTransport() throws GeneralSecurityException, IOException {
  NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
  builder.trustCertificates(GoogleUtils.getCertificateTrustStore());
  builder.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128)));
  return builder.build();
}
 * </pre>
 */
public static NetHttpTransport newTrustedTransport()
    throws GeneralSecurityException, IOException {
  return new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore())
      .build();
}