Example usage for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport

List of usage examples for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport.

Prototype

public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException 

Source Link

Document

Returns a new instance of NetHttpTransport that uses GoogleUtils#getCertificateTrustStore() for the trusted certificates using com.google.api.client.http.javanet.NetHttpTransport.Builder#trustCertificates(KeyStore) .

Usage

From source file:com.google.cloud.trace.sdk.InstalledAppCredentialProvider.java

License:Open Source License

public InstalledAppCredentialProvider() throws GeneralSecurityException, IOException {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(dataStoreDir);
}

From source file:com.google.cloud.trace.sdk.ServiceAccountCredentialProvider.java

License:Open Source License

@Override
public Credential getCredential(List<String> scopes) throws CloudTraceException {
    if (p12File == null) {
        throw new IllegalStateException("P12 file must be set");
    }/*ww w.j  ava  2  s . c  o  m*/
    if (emailAddress == null || emailAddress.isEmpty()) {
        throw new IllegalStateException("Email address must be set");
    }

    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(emailAddress)
                .setServiceAccountPrivateKeyFromP12File(p12File).setServiceAccountScopes(scopes).build();
        credential.refreshToken();
        return credential;
    } catch (GeneralSecurityException | IOException e) {
        throw new CloudTraceException("Exception getting oauth2 credential", e);
    }
}

From source file:com.google.datastore.v1.client.DatastoreHelper.java

License:Open Source License

private static HttpTransport newTransport() throws GeneralSecurityException, IOException {
    return GoogleNetHttpTransport.newTrustedTransport();
}

From source file:com.google.devtools.cdbg.debuglets.java.ServiceAccountAuth.java

License:Open Source License

/**
 * Class constructor//from www.  j  a  v a  2  s  . c o m
 * @param serviceAccountEmail service account identifier
 * @param serviceAccountP12File file with the private key of the service account
 */
public ServiceAccountAuth(String projectId, String projectNumber, String serviceAccountEmail,
        String serviceAccountP12File) throws GeneralSecurityException, IOException {
    Objects.requireNonNull(projectId);
    Objects.requireNonNull(projectNumber);
    Objects.requireNonNull(serviceAccountEmail);
    Objects.requireNonNull(serviceAccountP12File);

    this.projectId = projectId;
    this.projectNumber = projectNumber;
    this.credential = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport())
            .setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(serviceAccountEmail)
            .setServiceAccountPrivateKeyFromP12File(new File(serviceAccountP12File))
            .setServiceAccountScopes(Collections.singleton(CLOUD_PLATFORM_SCOPE)).build();
}

From source file:com.google.gcloud.AuthConfig.java

License:Open Source License

static ComputeCredential getComputeCredential() throws IOException, GeneralSecurityException {
    NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    // Try to connect using Google Compute Engine service account credentials.
    ComputeCredential credential = new ComputeCredential(transport, new JacksonFactory());
    // Force token refresh to detect if we are running on Google Compute Engine.
    credential.refreshToken();/* w w  w .j  av  a2  s . com*/
    return credential;
}

From source file:com.google.gcloud.CredentialUtils.java

License:Open Source License

/**
 * Creates a GoogleCredential for a Service Account.
 * It requires that the/* ww w.ja  v a2s . com*/
 * GOOGLE_APPLICATION_CREDENTIALS environment variable is correctly set. Scopes are not
 * required in the sense that you 'could' pass in null, but most RPC calls will fail if scopes
 * are not defines we require them here.
 * @param scopes (required)
 * @return a GoogleCredentials
 * @throws GeneralSecurityException on Transport error
 * @throws IOException on loading credentials error
 */
public static GoogleCredential getServiceAccountCredential(final Set<String> scopes)
        throws GeneralSecurityException, IOException {

    Preconditions.checkArgument(scopes != null && scopes.size() > 0, "You must specify scopes");

    ServiceAccountCredentials serviceAccountCredentials = getDefaultServiceAccountCredentials();
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    return new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(transport)
            .setServiceAccountScopes(scopes).setServiceAccountId(serviceAccountCredentials.getClientEmail())
            .setServiceAccountPrivateKey(serviceAccountCredentials.getPrivateKey()).build();
}

From source file:com.google.gcloud.CredentialUtils.java

License:Open Source License

/**
 * Creates a Compute Engine Credential.//from   ww  w  .j av  a  2  s.  c o  m
 * @return ComputeCredential
 * @throws GeneralSecurityException on Transport error
 * @throws IOException if credential cannot be loaded
 */
public static ComputeCredential getComputeEngineCredential() throws GeneralSecurityException, IOException {

    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    return new ComputeCredential.Builder(transport, JSON_FACTORY).build();
}

From source file:com.google.gct.idea.debugger.CloudDebuggerClient.java

License:Apache License

/**
 * Returns a cloud debugger connection given a user email to indicate the credentials to use. The function may return
 * null if the user is not logged in.//from   w w  w.ja  v a 2  s  . c om
 */
@Nullable
public static Debugger getCloudDebuggerClient(final @Nullable String userEmail) {
    if (Strings.isNullOrEmpty(userEmail)) {
        LOG.warn("unexpected null email in controller initialize.");
        return null;
    }
    Debugger cloudDebuggerClient = myDebuggerClientsFromUserEmail.get(userEmail);

    if (cloudDebuggerClient == null) {
        try {
            final CredentialedUser user = GoogleLogin.getInstance().getAllUsers().get(userEmail);
            final Credential credential = (user != null ? user.getCredential() : null);
            if (credential != null) {
                user.getGoogleLoginState().addLoginListener(new LoginListener() {
                    @Override
                    public void statusChanged(boolean login) {
                        //aggresively remove the cached item on any status change.
                        myDebuggerClientsFromUserEmail.remove(userEmail);
                    }
                });
                HttpRequestInitializer initializer = new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest httpRequest) throws IOException {
                        httpRequest.setConnectTimeout(CONNECTION_TIMEOUT_MS);
                        httpRequest.setReadTimeout(CONNECTION_TIMEOUT_MS);
                        credential.initialize(httpRequest);
                    }
                };

                HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
                cloudDebuggerClient = new Debugger.Builder(httpTransport, JSON_FACTORY, initializer)
                        .setRootUrl(ROOT_URL).setApplicationName("Android Studio").build();
            }
        } catch (IOException ex) {
            LOG.warn("Error connecting to Cloud Debugger API", ex);
        } catch (GeneralSecurityException ex) {
            LOG.warn("Error connecting to Cloud Debugger API", ex);
        }

        if (cloudDebuggerClient != null) {
            myDebuggerClientsFromUserEmail.put(userEmail, cloudDebuggerClient);
        }
    }
    return cloudDebuggerClient;
}

From source file:com.google.play.developerapi.publisher.samples.AndroidPublisherHelper.java

License:Open Source License

private static void newTrustedTransport() throws GeneralSecurityException, IOException {
    if (null == HTTP_TRANSPORT) {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    }/*from  w ww . ja va  2  s .co  m*/
}

From source file:com.google.pubsub.clients.common.MetricsHandler.java

License:Apache License

private void initialize() {
    synchronized (this) {
        try {/*from ww  w.ja va 2 s.co  m*/
            HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
            if (credential.createScopedRequired()) {
                credential = credential.createScoped(
                        Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
            }
            monitoring = new Monitoring.Builder(transport, jsonFactory, credential)
                    .setApplicationName("Cloud Pub/Sub Loadtest Framework").build();
            String zoneId;
            String instanceId;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.addRequestInterceptor(new RequestAcceptEncoding());
                httpClient.addResponseInterceptor(new ResponseContentEncoding());

                HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true);
                HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false);
                HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true);

                SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
                schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
                schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
                httpClient.setKeepAliveStrategy((response, ctx) -> 30);
                HttpGet zoneIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/zone");
                zoneIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest);
                String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity());
                if (tempZoneId.lastIndexOf("/") >= 0) {
                    zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1);
                } else {
                    zoneId = tempZoneId;
                }
                HttpGet instanceIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/id");
                instanceIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest);
                instanceId = EntityUtils.toString(instanceIdResponse.getEntity());
            } catch (IOException e) {
                log.info("Unable to connect to metadata server, assuming not on GCE, setting "
                        + "defaults for instance and zone.");
                instanceId = "local";
                zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local.
            }

            monitoredResource.setLabels(
                    ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId));
            createMetrics();
        } catch (IOException e) {
            log.error("Unable to initialize MetricsHandler, trying again.", e);
            executor.execute(this::initialize);
        } catch (GeneralSecurityException e) {
            log.error("Unable to initialize MetricsHandler permanently, credentials error.", e);
        }
    }
}