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.genomics.utils.OfflineAuth.java

License:Apache License

/**
 * Return the stored user credential, if applicable, or fall back to the Application Default Credential.
 *
 * @return The com.google.api.client.auth.oauth2.Credential object.
 *//*from   w  ww .j a va 2s.c  o m*/
public Credential getCredential() {
    if (hasStoredCredential()) {
        HttpTransport httpTransport;
        try {
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException("Could not create HTTPS transport for use in credential creation", e);
        }

        return new GoogleCredential.Builder().setJsonFactory(JacksonFactory.getDefaultInstance())
                .setTransport(httpTransport).setClientSecrets(getClientId(), getClientSecret()).build()
                .setRefreshToken(getRefreshToken());
    }
    return CredentialFactory.getApplicationDefaultCredential();
}

From source file:com.google.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Construct a new registry with the given name and pubsub topic inside the given project. */
public DeviceRegistryExample(String projectId, String location, String registryName, String pubsubTopicPath)
        throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    service = new CloudIot(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init);
    projectPath = "projects/" + projectId + "/locations/" + location;
    registryPath = projectPath + "/registries/" + registryName;

    NotificationConfig notificationConfig = new NotificationConfig();
    notificationConfig.setPubsubTopicName(pubsubTopicPath);

    DeviceRegistry registry = new DeviceRegistry();
    registry.setEventNotificationConfig(notificationConfig);
    registry.setId(registryName);//ww w  . j a  va2  s  .c  o m
    service.projects().locations().registries().create(projectPath, registry).execute();
}

From source file:com.google.cloud.security.scanner.primitives.GCPProject.java

License:Apache License

/**
 * Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
 * @return Projects api object used for accessing the Cloud Resource Manager Projects API
 * @throws GeneralSecurityException Thrown if there's a permissions error.
 * @throws IOException Thrown if there's an IO error initializing the API object.
 *///from   w w w. j  a  v  a2  s  .c om
public static synchronized Projects getProjectsApiStub() throws GeneralSecurityException, IOException {
    if (projectApiStub != null) {
        return projectApiStub;
    }
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
        Collection<String> scopes = CloudResourceManagerScopes.all();
        credential = credential.createScoped(scopes);
    }
    projectApiStub = new CloudResourceManager.Builder(transport, jsonFactory, credential).build().projects();
    return projectApiStub;
}

From source file:com.google.cloud.security.scanner.primitives.GCPServiceAccount.java

License:Apache License

/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection./*from   w  w w  .ja  va2  s .  co m*/
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
    if (serviceAccountsApiStub == null) {
        HttpTransport transport;
        GoogleCredential credential;
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        transport = GoogleNetHttpTransport.newTrustedTransport();
        credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
        if (credential.createScopedRequired()) {
            Collection<String> scopes = IamScopes.all();
            credential = credential.createScoped(scopes);
        }
        serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential).build().projects()
                .serviceAccounts();
    }
    return serviceAccountsApiStub;
}

From source file:com.google.cloud.security.scanner.sources.GCSFilesSource.java

License:Apache License

private static Storage constructStorageApiStub() throws GeneralSecurityException, IOException {
    JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport;/*from ww  w.j a  v a 2s .  c  o  m*/
    transport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
        Collection<String> scopes = StorageScopes.all();
        credential = credential.createScoped(scopes);
    }
    return new Storage.Builder(transport, jsonFactory, credential).setApplicationName("GCS Samples").build();
}

From source file:com.google.cloud.servicebroker.awwvision.VisionConfig.java

License:Open Source License

@Bean
HttpTransport transport() throws GeneralSecurityException, IOException {
    return GoogleNetHttpTransport.newTrustedTransport();
}

From source file:com.google.cloud.tools.intellij.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.j a va2 s . c o m
@Nullable
@SuppressFBWarnings(value = "AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION", justification = "Tolerable; ok to create and use duplicate or dangling Debugger clients")
private static Debugger getClient(final @Nullable String userEmail, final int timeout) {
    if (Strings.isNullOrEmpty(userEmail)) {
        LOG.warn("unexpected null email in controller initialize.");
        return null;
    }
    final String hashkey = userEmail + timeout;
    Debugger cloudDebuggerClient = debuggerClientsFromUserEmail.get(hashkey);
    if (cloudDebuggerClient == null) {
        try {
            final CredentialedUser user = Services.getLoginService().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) {
                        if (!login) {
                            // aggressively remove the cached item on any status change.
                            debuggerClientsFromUserEmail.remove(hashkey);
                        } else { // NOPMD
                            // user logged in, should we do something?
                        }
                    }
                });
                HttpRequestInitializer initializer = new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest httpRequest) throws IOException {
                        HttpHeaders headers = new HttpHeaders();
                        httpRequest.setConnectTimeout(timeout);
                        httpRequest.setReadTimeout(timeout);
                        httpRequest.setHeaders(headers);
                        credential.initialize(httpRequest);
                    }
                };

                HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
                String userAgent = ServiceManager.getService(CloudToolsPluginInfoService.class).getUserAgent();
                cloudDebuggerClient = new Builder(httpTransport, JSON_FACTORY, initializer).setRootUrl(ROOT_URL)
                        // this ends up prefixed to user agent
                        .setApplicationName(userAgent).build().debugger();
            }
        } 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) {
            debuggerClientsFromUserEmail.put(hashkey, cloudDebuggerClient);
        }
    }

    return cloudDebuggerClient;
}

From source file:com.google.cloud.tools.intellij.vcs.CloudRepositoryService.java

License:Open Source License

@NotNull
public ListReposResponse list(CredentialedUser user, String cloudProject)
        throws CloudRepositoryServiceException {
    try {//from   w  ww. ja  va  2  s .c o  m
        Credential credential = user.getCredential();
        HttpRequestInitializer initializer = httpRequest -> {
            HttpHeaders headers = new HttpHeaders();
            httpRequest.setConnectTimeout(LIST_TIMEOUT_MS);
            httpRequest.setReadTimeout(LIST_TIMEOUT_MS);
            httpRequest.setHeaders(headers);
            credential.initialize(httpRequest);
        };

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        String userAgent = ServiceManager.getService(CloudToolsPluginInfoService.class).getUserAgent();

        Source source = new Source.Builder(httpTransport, JacksonFactory.getDefaultInstance(), initializer)
                .setRootUrl(CLOUD_SOURCE_API_ROOT_URL).setServicePath("")
                // this ends up prefixed to user agent
                .setApplicationName(userAgent).build();

        return new CustomUrlSourceRequest(source, cloudProject).execute();
    } catch (IOException | GeneralSecurityException ex) {
        throw new CloudRepositoryServiceException();
    }
}

From source file:com.google.cloud.trace.sdk.examples.GetTrace.java

License:Open Source License

public static void main(String[] args) throws Exception {
    InstalledAppCredentialProvider credentialProvider = new InstalledAppCredentialProvider();
    credentialProvider.setClientSecretsFile(new File(args[0]));

    CloudTraceReader reader = new CloudTraceReader();
    // NetHttpTransport doesn't support HTTP PATCH, but for a GET it's good enough.
    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    HttpRequestFactory requestFactory = httpTransport
            .createRequestFactory(credentialProvider.getCredential(CloudTraceReader.SCOPES));
    reader.setRequestFactory(new HttpTransportCloudTraceRequestFactory(httpTransport, requestFactory));
    reader.setApiEndpoint(args[1]);/*from  ww  w  .j  ava2  s  .  c  om*/
    reader.setProjectId(args[2]);
    Trace result = reader.readTraceById(args[3]);
    System.out.println(result);
}

From source file:com.google.cloud.trace.sdk.examples.GetTraceWithServiceAccount.java

License:Open Source License

public static void main(String[] args) throws Exception {
    ServiceAccountCredentialProvider credentialProvider = new ServiceAccountCredentialProvider();
    credentialProvider.setEmailAddress(args[0]);
    credentialProvider.setP12File(new File(args[1]));

    CloudTraceReader reader = new CloudTraceReader();
    // NetHttpTransport doesn't support HTTP PATCH, but for a GET it's good enough.
    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    HttpRequestFactory requestFactory = httpTransport
            .createRequestFactory(credentialProvider.getCredential(CloudTraceReader.SCOPES));
    reader.setRequestFactory(new HttpTransportCloudTraceRequestFactory(httpTransport, requestFactory));
    reader.setApiEndpoint(args[2]);/* w w  w . jav  a  2s.  c  o  m*/
    reader.setProjectId(args[3]);
    Trace result = reader.readTraceById(args[4]);
    System.out.println(result);
}