Java Code Examples for com.google.api.client.googleapis.auth.oauth2.GoogleCredential#fromStream()

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleCredential#fromStream() . 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: ClientAuthenticationFactory.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
private GoogleCredential getGoogleCredential(GcpIamProperties gcp)
		throws IOException {

	GcpCredentials credentialProperties = gcp.getCredentials();
	if (credentialProperties.getLocation() != null) {
		return GoogleCredential
				.fromStream(credentialProperties.getLocation().getInputStream());
	}

	if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
		return GoogleCredential.fromStream(new ByteArrayInputStream(
				Base64.getDecoder().decode(credentialProperties.getEncodedKey())));
	}

	return GoogleCredential.getApplicationDefault();
}
 
Example 2
Source File: AuthModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@CloudSqlClientCredential
public static Credential providesLocalCredentialForCloudSqlClient(
    @LocalCredentialJson String credentialJson,
    @Config("localCredentialOauthScopes") ImmutableList<String> credentialScopes) {
  try {
    GoogleCredential credential =
        GoogleCredential.fromStream(new ByteArrayInputStream(credentialJson.getBytes(UTF_8)));
    if (credential.createScopedRequired()) {
      credential = credential.createScoped(credentialScopes);
    }
    return credential;
  } catch (IOException e) {
    throw new UncheckedIOException(
        "Error occurred while creating a GoogleCredential for Cloud SQL client", e);
  }
}
 
Example 3
Source File: GcpIamClientAuthenticationProvider.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
public static GcpCredentialSupplier getGoogleCredential(
		VaultEnvironmentProperties.GcpIamProperties gcp) {
	return () -> {

		VaultEnvironmentProperties.GcpCredentials credentialProperties = gcp
				.getCredentials();
		if (credentialProperties.getLocation() != null) {
			return GoogleCredential.fromStream(
					credentialProperties.getLocation().getInputStream());
		}

		if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
			return GoogleCredential.fromStream(new ByteArrayInputStream(Base64
					.getDecoder().decode(credentialProperties.getEncodedKey())));
		}

		return GoogleCredential.getApplicationDefault();
	};
}
 
Example 4
Source File: GcpConfiguration.java    From spydra with Apache License 2.0 5 votes vote down vote up
@Override
public GoogleCredential getCredential() {
  try {
    return GoogleCredential.fromStream(
        new ByteArrayInputStream(credentialJsonFromEnv().getBytes()));
  } catch (IOException e) {
    throw new RuntimeException("Failed to load GoogleCredential from json", e);
  }
}
 
Example 5
Source File: GoogleDirectoryUserRolesProvider.java    From fiat with Apache License 2.0 5 votes vote down vote up
private GoogleCredential getGoogleCredential() {
  try {
    if (StringUtils.isNotEmpty(config.getCredentialPath())) {
      return GoogleCredential.fromStream(new FileInputStream(config.getCredentialPath()));
    } else {
      return GoogleCredential.getApplicationDefault();
    }
  } catch (IOException ioe) {
    throw new RuntimeException(ioe);
  }
}
 
Example 6
Source File: GcpCredentialProvider.java    From digdag with Apache License 2.0 5 votes vote down vote up
private GoogleCredential googleCredential(String credential)
{
    try {
        return GoogleCredential.fromStream(new ByteArrayInputStream(credential.getBytes(UTF_8)));
    }
    catch (IOException e) {
        throw new TaskExecutionException(e);
    }
}
 
Example 7
Source File: BaragonServiceModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named(GOOGLE_CLOUD_COMPUTE_SERVICE)
public Optional<Compute> provideComputeService(BaragonConfiguration config) throws Exception {
  if (!config.getGoogleCloudConfiguration().isEnabled()) {
    return Optional.absent();
  }
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  GoogleCredential credential = null;

  if (config.getGoogleCloudConfiguration().getGoogleCredentialsFile() != null) {
    File credentialsFile = new File(config.getGoogleCloudConfiguration().getGoogleCredentialsFile());
    credential = GoogleCredential.fromStream(
        new FileInputStream(credentialsFile)
    );
  } else if (config.getGoogleCloudConfiguration().getGoogleCredentials() != null) {
    credential = GoogleCredential.fromStream(
        new ByteArrayInputStream(config.getGoogleCloudConfiguration().getGoogleCredentials().getBytes("UTF-8"))
    );
  } else {
    throw new RuntimeException("Must specify googleCloudCredentials or googleCloudCredentialsFile when using google cloud api");
  }

  if (credential.createScopedRequired()) {
    credential =
        credential.createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
  }

  return Optional.of(new Compute.Builder(httpTransport, jsonFactory, credential)
      .setApplicationName("BaragonService")
      .build());
}
 
Example 8
Source File: App.java    From java-play-store-uploader with MIT License 4 votes vote down vote up
/**
 * Perform apk upload an release on given track
 *
 * @throws Exception Upload error
 */
private void upload() throws Exception {
    // configure proxy
    if (this.proxyHost != null && !this.proxyHost.isEmpty()) {
        System.setProperty("https.proxyHost", this.proxyHost);
    }

    if (this.proxyPort != null && !this.proxyPort.isEmpty()) {
        System.setProperty("https.proxyPort", this.proxyPort);
    }

    // load key file credentials
    System.out.println("Loading account credentials...");
    Path jsonKey = FileSystems.getDefault().getPath(this.jsonKeyPath).normalize();
    GoogleCredential cred = GoogleCredential.fromStream(new FileInputStream(jsonKey.toFile()));
    cred = cred.createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER));

    // load apk file info
    System.out.println("Loading apk file information...");
    Path apkFile = FileSystems.getDefault().getPath(this.apkPath).normalize();
    ApkFile apkInfo = new ApkFile(apkFile.toFile());
    ApkMeta apkMeta = apkInfo.getApkMeta();
    final String applicationName = this.appName == null ? apkMeta.getName() : this.appName;
    final String packageName = apkMeta.getPackageName();
    System.out.println(String.format("App Name: %s", apkMeta.getName()));
    System.out.println(String.format("App Id: %s", apkMeta.getPackageName()));
    System.out.println(String.format("App Version Code: %d", apkMeta.getVersionCode()));
    System.out.println(String.format("App Version Name: %s", apkMeta.getVersionName()));
    apkInfo.close();

    // load release notes
    System.out.println("Loading release notes...");
    List<LocalizedText> releaseNotes = new ArrayList<LocalizedText>();
    if (this.notesPath != null) {
        Path notesFile = FileSystems.getDefault().getPath(this.notesPath).normalize();
        String notesContent = new String(Files.readAllBytes(notesFile));
        releaseNotes.add(new LocalizedText().setLanguage(Locale.US.toString()).setText(notesContent));
    } else if (this.notes != null) {
        releaseNotes.add(new LocalizedText().setLanguage(Locale.US.toString()).setText(this.notes));
    }

    // init publisher
    System.out.println("Initialising publisher service...");
    AndroidPublisher.Builder ab = new AndroidPublisher.Builder(cred.getTransport(), cred.getJsonFactory(), cred);
    AndroidPublisher publisher = ab.setApplicationName(applicationName).build();

    // create an edit
    System.out.println("Initialising new edit...");
    AppEdit edit = publisher.edits().insert(packageName, null).execute();
    final String editId = edit.getId();
    System.out.println(String.format("Edit created. Id: %s", editId));

    try {
        // upload the apk
        System.out.println("Uploading apk file...");
        AbstractInputStreamContent apkContent = new FileContent(MIME_TYPE_APK, apkFile.toFile());
        Apk apk = publisher.edits().apks().upload(packageName, editId, apkContent).execute();
        System.out.println(String.format("Apk uploaded. Version Code: %s", apk.getVersionCode()));

        // create a release on track
        System.out.println(String.format("On track:%s. Creating a release...", this.trackName));
        TrackRelease release = new TrackRelease().setName("Automated upload").setStatus("completed")
                .setVersionCodes(Collections.singletonList((long) apk.getVersionCode()))
                .setReleaseNotes(releaseNotes);
        Track track = new Track().setReleases(Collections.singletonList(release));
        track = publisher.edits().tracks().update(packageName, editId, this.trackName, track).execute();
        System.out.println(String.format("Release created on track: %s", this.trackName));

        // commit edit
        System.out.println("Commiting edit...");
        edit = publisher.edits().commit(packageName, editId).execute();
        System.out.println(String.format("Success. Commited Edit id: %s", editId));

        // Success
    } catch (Exception e) {
        // error message
        String msg = "Operation Failed: " + e.getMessage();

        // abort
        System.err.println("Opertaion failed due to an error!, Deleting edit...");
        try {
            publisher.edits().delete(packageName, editId).execute();
        } catch (Exception e2) {
            // log abort error as well
            msg += "\nFailed to delete edit: " + e2.getMessage();
        }

        // forward error with message
        throw new IOException(msg, e);
    }
}
 
Example 9
Source File: BigQueryIT.java    From digdag with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    assumeThat(GCP_CREDENTIAL, not(isEmptyOrNullString()));

    proxyServer = TestUtils.startRequestFailingProxy(2, new ConcurrentHashMap<>(), HttpResponseStatus.INTERNAL_SERVER_ERROR,
            (req, reqCount) -> {
                // io.digdag.standards.operator.gcp.BqJobRunner sends "CONNECT www.googleapis.com" frequently. It can easily cause infinite retry.
                // So the following custom logic should be used for that kind of requests.
                if (req.getMethod().equals(HttpMethod.CONNECT)) {
                    return Optional.of(reqCount % 5 == 0);
                }
                return Optional.absent();
            });

    server = TemporaryDigdagServer.builder()
            .environment(ImmutableMap.of(
                    "https_proxy", "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort())
            )
            .withRandomSecretEncryptionKey()
            .build();
    server.start();

    projectDir = folder.getRoot().toPath();
    createProject(projectDir);
    projectName = projectDir.getFileName().toString();
    projectId = pushProject(server.endpoint(), projectDir, projectName);

    outfile = folder.newFolder().toPath().resolve("outfile");

    digdagClient = DigdagClient.builder()
            .host(server.host())
            .port(server.port())
            .build();

    digdagClient.setProjectSecret(projectId, "gcp.credential", GCP_CREDENTIAL);

    gcpCredential = GoogleCredential.fromStream(new StringInputStream(GCP_CREDENTIAL));

    assertThat(gcpProjectId, not(isEmptyOrNullString()));

    jsonFactory = new JacksonFactory();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    gcs = gcsClient(gcpCredential);
    bq = bqClient(gcpCredential);
}
 
Example 10
Source File: GcsWaitIT.java    From digdag with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    assumeThat(GCP_CREDENTIAL, not(isEmptyOrNullString()));
    assumeThat(GCS_TEST_BUCKET, not(isEmptyOrNullString()));

    proxyServer = TestUtils.startRequestFailingProxy(1);

    server = TemporaryDigdagServer.builder()
            .environment(ImmutableMap.of(
                    "https_proxy", "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort())
            )
            .withRandomSecretEncryptionKey()
            .build();
    server.start();

    projectDir = folder.getRoot().toPath();
    createProject(projectDir);
    projectName = projectDir.getFileName().toString();
    projectId = pushProject(server.endpoint(), projectDir, projectName);

    outfile = folder.newFolder().toPath().resolve("outfile");

    digdagClient = DigdagClient.builder()
            .host(server.host())
            .port(server.port())
            .build();

    digdagClient.setProjectSecret(projectId, "gcp.credential", GCP_CREDENTIAL);

    gcpCredential = GoogleCredential.fromStream(new StringInputStream(GCP_CREDENTIAL));

    gcpProjectId = DigdagClient.objectMapper().readTree(GCP_CREDENTIAL).get("project_id").asText();
    assertThat(gcpProjectId, not(isEmptyOrNullString()));

    jsonFactory = new JacksonFactory();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    gcs = gcsClient(gcpCredential);

    client = DigdagClient.builder()
            .host(server.host())
            .port(server.port())
            .build();
}