Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential getApplicationDefault

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential getApplicationDefault

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential getApplicationDefault.

Prototype

@Beta
public static GoogleCredential getApplicationDefault() throws IOException 

Source Link

Document

Beta
Returns the Application Default Credentials.

Usage

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

License:Apache License

/** Modify the latest cloud to device config for the given device, with the config data. */
public static void modifyCloudToDeviceConfig(String deviceId, String configData, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;//from  w w w. j a va2s .  c  o m
    final String devicePath = registryPath + "/devices/" + deviceId;
    ModifyCloudToDeviceConfigRequest request = new ModifyCloudToDeviceConfigRequest();
    request.setVersionToUpdate(0L); // 0L indicates update all versions
    request.setBinaryData(DatatypeConverter.printBase64Binary(configData.getBytes(Charsets.UTF_8)));
    DeviceConfig config = service.projects().locations().registries().devices()
            .modifyCloudToDeviceConfig(devicePath, request).execute();

    System.out.println("Created device config: " + config.toPrettyString());
}

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

License:Apache License

/** Patch the device to add an ES256 key for authentication. */
public static void patchEs256ForAuth(String deviceId, String publicKeyFilePath, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;/*from w w  w . j  av  a  2  s .  co  m*/

    final String devicePath = registryPath + "/devices/" + deviceId;
    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);
    publicKeyCredential.setFormat("ES256_PEM");

    DeviceCredential devCredential = new DeviceCredential();
    devCredential.setPublicKey(publicKeyCredential);

    Device device = new Device();
    device.setCredentials(Arrays.asList(devCredential));

    Device patchedDevice = service.projects().locations().registries().devices().patch(devicePath, device)
            .setUpdateMask("credentials").execute();

    System.out.println("Patched device is " + patchedDevice.toPrettyString());
}

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

License:Apache License

/** Patch the device to add an RSA256 key for authentication. */
public static void patchRsa256ForAuth(String deviceId, String publicKeyFilePath, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;/*w  w  w . ja va 2s .  c om*/

    final String devicePath = registryPath + "/devices/" + deviceId;
    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);
    publicKeyCredential.setFormat("RSA_X509_PEM");

    DeviceCredential devCredential = new DeviceCredential();
    devCredential.setPublicKey(publicKeyCredential);

    Device device = new Device();
    device.setCredentials(Arrays.asList(devCredential));

    Device patchedDevice = service.projects().locations().registries().devices().patch(devicePath, device)
            .setUpdateMask("credentials").execute();

    System.out.println("Patched device is " + patchedDevice.toPrettyString());
}

From source file:com.examples.abelanav2.storage.CloudStorage.java

License:Open Source License

/**
 * Returns a Google Cloud Storage upload url.
 *
 * @param name the filename/* w w  w .jav  a  2s.c  om*/
 * @return a URL
 */
public static String getUploadUrl(final String name) {

    try {
        GoogleCredential googleCredentials = GoogleCredential.getApplicationDefault()
                .createScoped(Collections.singleton(STORAGE_SCOPE));

        String uri = "https://www.googleapis.com/upload/storage/v1/b/"
                + URLEncoder.encode(BackendConstants.UPLOAD_BUCKET_NAME, "UTF-8")
                + "/o?uploadType=resumable&name=" + URLEncoder.encode(name, "UTF-8");

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory(googleCredentials);
        GenericUrl url = new GenericUrl(uri);
        HttpRequest request = requestFactory.buildPostRequest(url, new EmptyContent());
        try {
            HttpResponse response = request.execute();

            if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_OK) {
                return response.getHeaders().getLocation();
            } else {
                LOGGER.severe("Could not get upload URL, HTTP code = " + response.getStatusCode());
            }
        } catch (IOException e) {
            LOGGER.severe("API request to Google Cloud Storage failed: " + e.getMessage());
        }

    } catch (IOException e) {
        LOGGER.severe("Could not get credentials: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOGGER.severe("Could not start the transport layer for upload: " + e.getMessage());
    }
    return null;
}

From source file:com.examples.abelanav2.TaskQueueNotificationServlet.java

License:Open Source License

@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    HttpTransport httpTransport;/*from w  w  w.  j a  v a  2s .c  o m*/
    try {
        Map<Object, Object> params = new HashMap<>();
        params.putAll(req.getParameterMap());
        params.put("task", req.getHeader("X-AppEngine-TaskName"));

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = GoogleCredential.getApplicationDefault()
                .createScoped(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"));
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
        GenericUrl url = new GenericUrl(ConfigurationConstants.IMAGE_RESIZER_URL);

        HttpRequest request = requestFactory.buildPostRequest(url, new UrlEncodedContent(params));
        credential.initialize(request);

        HttpResponse response = request.execute();
        if (!response.isSuccessStatusCode()) {
            log("Call to the imageresizer failed: " + response.getContent().toString());
            resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
        } else {
            resp.setStatus(response.getStatusCode());
        }

    } catch (GeneralSecurityException | IOException e) {
        log("Http request error: " + e.getMessage());
        resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
    }
}

From source file:com.fullgear.dataflow.Analyze.java

License:Open Source License

/**
 * Connects to the Natural Language API using Application Default Credentials.
 *///w  w w . j ava 2s.  c  o  m
public static CloudNaturalLanguageAPI getLanguageService() throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault()
            .createScoped(CloudNaturalLanguageAPIScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new CloudNaturalLanguageAPI.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {
                    credential.initialize(request);
                }
            }).setApplicationName(APPLICATION_NAME).build();
}

From source file:com.gcloud.poc.DataFlow_File2File.java

License:Apache License

private static Storage getService() throws IOException, GeneralSecurityException {
    if (null == storageService) {
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        // Depending on the environment that provides the default credentials (e.g. Compute Engine,
        // App Engine), the credentials may require us to specify the scopes we need explicitly.
        // Check for this case, and inject the Cloud Storage scope if required.
        if (credential.createScopedRequired()) {
            credential = credential.createScoped(StorageScopes.all());
        }//from ww  w  .j  a v a  2s  . c  om
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
    }
    return storageService;
}

From source file:com.google.appengine.tools.pipeline.impl.backend.CloudTaskQueue.java

License:Apache License

public CloudTaskQueue() {
    final String rootUrl = System.getProperty(CLOUDTASKS_API_ROOT_URL_PROPERTY);
    final String apiKey = System.getProperty(CLOUDTASKS_API_KEY_PROPERTY);
    this.apiKey = apiKey;
    try {/*from w  ww .  java  2  s .com*/
        HttpRequestInitializer credential;
        try {
            credential = GoogleCredential.getApplicationDefault().createScoped(CloudTasksScopes.all());
        } catch (IOException e) {
            logger.info(
                    "Fallback to HttpRequestInitializer, cause cannot create Application default credentials: "
                            + e.getMessage());
            credential = new HttpRequestInitializer() {
                @Override
                public void initialize(final HttpRequest request) throws IOException {
                }
            };
        }
        CloudTasks.Builder builder = new CloudTasks.Builder(GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(), credential).setApplicationName("appengine-pipeline");
        if (rootUrl != null) {
            builder.setRootUrl(rootUrl);
        }
        cloudTask = builder.build();
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.cloud.crypto.tink.subtle.ServiceAccountGcpCredentialFactory.java

License:Apache License

@Override
public GoogleCredential createCredential(String kmsKeyUri /* unused */) throws IOException {
    GoogleCredential cred;/*from   w w w .jav a  2 s. c  om*/
    if (serviceAccount.isPresent()) {
        cred = createServiceAccountGoogleCredential(serviceAccount.get());
    } else {
        cred = GoogleCredential.getApplicationDefault();
    }
    cred = cred.createScoped(GcpScopes.all());
    return cred;
}

From source file:com.google.cloud.crypto.tink.tinkey.TinkeyUtil.java

License:Apache License

/**
 * @return a {@code GoogleCredential}, using the service account in {@code credentialFile}.
 * If {@code credentialFile} is null, returns an
 * <a href="https://g.co/dv/identity/protocols/application-default-credentials">application
 * default credential</a>.//from  w  w  w  .  j  a  v  a2s  .c  o  m
 */
public static GoogleCredential readGoogleCredential(File credentialFile) throws IOException {
    GoogleCredential cred;
    if (credentialFile != null) {
        byte[] credBytes = Files.readAllBytes(credentialFile.toPath());
        cred = GoogleCredential.fromStream(new ByteArrayInputStream(credBytes));
    } else {
        cred = GoogleCredential.getApplicationDefault();
    }
    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the scope if required.
    if (cred.createScopedRequired()) {
        cred = cred.createScoped(CloudKMSScopes.all());
    }
    return cred;
}