com.google.cloud.ServiceOptions Java Examples

The following examples show how to use com.google.cloud.ServiceOptions. 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: SpannerIT.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
private List<String> getSessionNames() {
  String databaseName = DatabaseName.format(ServiceOptions.getDefaultProjectId(),
      DatabaseProperties.INSTANCE, DatabaseProperties.DATABASE);

  ListSessionsRequest listSessionsRequest =
      ListSessionsRequest.newBuilder()
          .setDatabase(databaseName)
          .build();

  ListSessionsResponse listSessionsResponse =
      ObservableReactiveUtil.<ListSessionsResponse>unaryCall(
          obs -> this.spanner.listSessions(listSessionsRequest, obs))
          .block();

  return listSessionsResponse.getSessionsList()
      .stream()
      .map(Session::getName)
      .collect(Collectors.toList());
}
 
Example #2
Source File: PubSubPublish.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  Publisher publisher = this.publisher;
  try {
    String topicId = System.getenv("PUBSUB_TOPIC");
    // create a publisher on the topic
    if (publisher == null) {
      publisher = Publisher.newBuilder(
          ProjectTopicName.of(ServiceOptions.getDefaultProjectId(), topicId))
          .build();
    }
    // construct a pubsub message from the payload
    final String payload = req.getParameter("payload");
    PubsubMessage pubsubMessage =
        PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(payload)).build();

    publisher.publish(pubsubMessage);
    // redirect to home page
    resp.sendRedirect("/");
  } catch (Exception e) {
    resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
  }
}
 
Example #3
Source File: GoogleCloudStorage.java    From metastore with Apache License 2.0 6 votes vote down vote up
public void init(RegistryInfo registryInfo, Map<String, String> config, String extension) {
  this.storage = StorageOptions.getDefaultInstance().getService();
  String project = ServiceOptions.getDefaultProjectId();

  if (config.get("project") == null && project == null) {
    throw new RuntimeException("project variable not set");
  }
  if (config.get("bucket") == null) {
    throw new RuntimeException("bucket variable not set");
  }
  if (config.get("path") == null) {
    throw new RuntimeException("path variable not set");
  }

  if (config.get("project") != null) {
    this.project = config.get("project");
  }
  this.bucket = config.get("bucket");
  if (config.get("path").endsWith("/")) {
    this.fileName = config.get("path") + registryInfo.getName() + "." + extension;
  } else {
    this.fileName = config.get("path") + "/" + registryInfo.getName() + "." + extension;
  }
}
 
Example #4
Source File: ITBucketSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequesterPays() throws Exception {
  EnableRequesterPays.enableRequesterPays(PROJECT_ID, BUCKET);
  Bucket bucket = storage.get(BUCKET);
  assertTrue(bucket.requesterPays());
  String projectId = ServiceOptions.getDefaultProjectId();
  String blobName = "test-create-empty-blob-requester-pays";
  byte[] content = {0xD, 0xE, 0xA, 0xD};
  Blob remoteBlob =
      bucket.create(blobName, content, Bucket.BlobTargetOption.userProject(projectId));
  assertNotNull(remoteBlob);
  DownloadRequesterPaysObject.downloadRequesterPaysObject(
      projectId, BUCKET, blobName, Paths.get(blobName));
  byte[] readBytes = Files.readAllBytes(Paths.get(blobName));
  assertArrayEquals(content, readBytes);
  DisableRequesterPays.disableRequesterPays(PROJECT_ID, BUCKET);
  assertFalse(storage.get(BUCKET).requesterPays());
}
 
Example #5
Source File: TraceValve.java    From tomcat-runtime with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void initTraceService() throws LifecycleException {

  if (traceScheduledDelay != null && traceScheduledDelay <= 0) {
    throw new LifecycleException("The delay for trace must be greater than 0");
  }

  try {
    String projectId = ServiceOptions.getDefaultProjectId();
    TraceGrpcApiService.Builder traceServiceBuilder = getTraceService()
        .setProjectId(projectId);

    if (traceScheduledDelay != null) {
      traceServiceBuilder.setScheduledDelay(traceScheduledDelay);
    }

    traceService = traceServiceBuilder.build();
    Trace.init(traceService);
    log.info("Trace service initialized for project: " + projectId);
  } catch (IOException e) {
    throw new LifecycleException(e);
  }
}
 
Example #6
Source File: KmsDecrypter.java    From dbeam with Apache License 2.0 6 votes vote down vote up
/**
 * Decrypt a base64 encoded cipher text string.
 *
 * @return A {@link ByteBuffer} with the raw contents.
 */
ByteBuffer decryptBinary(final String base64Ciphertext) throws IOException {
  final String project = project().orElseGet(ServiceOptions::getDefaultProjectId);
  final String keyName =
      String.format(
          "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
          project, location(), keyring(), key());

  final DecryptResponse response =
      kms()
          .projects()
          .locations()
          .keyRings()
          .cryptoKeys()
          .decrypt(
              keyName,
              new DecryptRequest()
                  .setCiphertext(CharMatcher.whitespace().removeFrom(base64Ciphertext)))
          .execute();
  return ByteBuffer.wrap(Base64.getDecoder().decode(response.getPlaintext()));
}
 
Example #7
Source File: DefaultGcpEnvironmentProvider.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Override
public GcpEnvironment getCurrentEnvironment() {

	if (System.getenv("GAE_INSTANCE") != null) {
		return GcpEnvironment.APP_ENGINE_FLEXIBLE;
	}

	if (System.getenv("KUBERNETES_SERVICE_HOST") != null) {
		return GcpEnvironment.KUBERNETES_ENGINE;
	}

	if (ServiceOptions.getAppEngineAppId() != null) {
		return GcpEnvironment.APP_ENGINE_STANDARD;
	}

	if (MetadataConfig.getInstanceId() != null) {
		return GcpEnvironment.COMPUTE_ENGINE;
	}

	return GcpEnvironment.UNKNOWN;
}
 
Example #8
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void insertTestData() throws SQLException {
  String connectionUrl =
      String.format(
          "jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
          ServiceOptions.getDefaultProjectId(), instanceId, databaseId);
  try (Connection connection = DriverManager.getConnection(connectionUrl)) {
    CloudSpannerJdbcConnection spannerConnection =
        connection.unwrap(CloudSpannerJdbcConnection.class);
    spannerConnection.setAutoCommit(false);
    for (Singer singer : TEST_SINGERS) {
      spannerConnection.bufferedWrite(
          Mutation.newInsertBuilder("Singers")
              .set("SingerId")
              .to(singer.singerId)
              .set("FirstName")
              .to(singer.firstName)
              .set("LastName")
              .to(singer.lastName)
              .build());
    }
    connection.commit();
  }
}
 
Example #9
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void bufferedWrite_shouldInsertData() throws SQLException {
  String out =
      runExample(
          () ->
              BufferedWriteExample.bufferedWrite(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Transaction committed at [");
}
 
Example #10
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void readOnlyTransaction_shouldReadData() throws SQLException {
  String out =
      runExample(
          () ->
              ReadOnlyTransactionExample.readOnlyTransaction(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("1 Marc Richards");
  assertThat(out).contains("2 Catalina Smith");
  assertThat(out).contains("Read-only transaction used read timestamp [");
}
 
Example #11
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void partitionedDml_shouldUpdateData() throws SQLException {
  String out =
      runExample(
          () ->
              PartitionedDmlExample.partitionedDml(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Updated 5 row(s)");
}
 
Example #12
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void insertData_shouldInsertData() throws SQLException {
  String out =
      runExample(
          () ->
              InsertDataExample.insertData(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Insert counts: [1, 1, 1, 1, 1]");
}
 
Example #13
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void getReadTimestampExample_shouldGetReadTimestamp() throws SQLException {
  String out =
      runExample(
          () ->
              GetReadTimestampExample.getReadTimestamp(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Read timestamp: [");
}
 
Example #14
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void getCommitTimestampExample_shouldGetCommitTimestamp() throws SQLException {
  String out =
      runExample(
          () ->
              GetCommitTimestampExample.getCommitTimestamp(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Commit timestamp: [");
}
 
Example #15
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void spannerJdbcConnectionWithQueryOtions_shouldUseOptimizerVersion() throws SQLException {
  String out =
      runExample(
          () ->
              ConnectionWithQueryOptionsExample.connectionWithQueryOptions(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("1 Marc Richards");
  assertThat(out).contains("Optimizer version: 1");
}
 
Example #16
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void singleUseReadOnly_shouldReturnData() throws SQLException {
  String out =
      runExample(
          () ->
              SingleUseReadOnlyExample.singleUseReadOnly(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("1 Marc Richards");
  assertThat(out).contains("2 Catalina Smith");
}
 
Example #17
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void batchDmlUsingSqlStatements_shouldInsertData() throws SQLException {
  String out =
      runExample(
          () ->
              BatchDmlUsingSqlStatementsExample.batchDmlUsingSqlStatements(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Batch insert counts: [1, 1, 1]");
}
 
Example #18
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void batchDml_shouldInsertData() throws SQLException {
  String out =
      runExample(
          () ->
              BatchDmlExample.batchDml(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Batch insert counts: [1, 1, 1]");
}
 
Example #19
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void batchDdlUsingSqlStatements_shouldCreateTables() throws SQLException {
  String out =
      runExample(
          () ->
              BatchDdlUsingSqlStatementsExample.batchDdlUsingSqlStatements(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Update count for CREATE TABLE Concerts: -2");
  assertThat(out).contains("Update count for CREATE INDEX SingersByFirstLastName: -2");
  assertThat(out).contains("Executed DDL batch");
}
 
Example #20
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void readWriteTransaction_shouldWriteData() throws SQLException {
  String out =
      runExample(
          () ->
              ReadWriteTransactionExample.readWriteTransaction(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Transaction committed with commit timestamp [");
}
 
Example #21
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void spannerJdbcSetStatementForQueryOptions_shouldUseOptimizerVersion()
    throws SQLException {
  String out =
      runExample(
          () ->
              SetQueryOptionsExample.setQueryOptions(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("1 Marc Richards");
  assertThat(out).contains("Optimizer version: 1");
}
 
Example #22
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void createConnectionWithDataSource_shouldConnectToSpanner() throws SQLException {
  String out =
      runExample(
          () ->
              CreateConnectionWithDataSourceExample.createConnectionWithDataSource(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Readonly: true");
  assertThat(out).contains("Autocommit: false");
}
 
Example #23
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void singleUseReadOnlyTimestampBound_shouldNotReturnData() throws SQLException {
  String out =
      runExample(
          () ->
              SingleUseReadOnlyTimestampBoundExample.singleUseReadOnlyTimestampBound(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).doesNotContain("10 Marc Richards");
  assertThat(out).doesNotContain("20 Catalina Smith");
}
 
Example #24
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionWithRetryLoop_shouldCommit() throws SQLException {
  String out =
      runExample(
          () ->
              TransactionWithRetryLoopExample.transactionWithRetryLoop(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Transaction committed at [");
}
 
Example #25
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionWithRetryLoopUsingOnlyJdbc_shouldCommit() throws SQLException {
  String out =
      runExample(
          () ->
              TransactionWithRetryLoopUsingOnlyJdbcExample.genericJdbcTransactionWithRetryLoop(
                  ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
  assertThat(out).contains("Transaction committed at [");
}
 
Example #26
Source File: QuickStartIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testExportAssetBigqueryExample() throws Exception {
  String dataset =
      String.format("projects/%s/datasets/%s", ServiceOptions.getDefaultProjectId(), datasetName);
  String table = "java_test";
  ExportAssetsBigqueryExample.exportBigQuery(dataset, table);
  String got = bout.toString();
  assertThat(got).contains(String.format("dataset: \"%s\"", dataset));
}
 
Example #27
Source File: GcpOptions.java    From flo with Apache License 2.0 5 votes vote down vote up
/**
 * A version of {@link ServiceOptions#getDefaultProject()} that defaults to the service account
 * project instead of the GCE (metadata server) project id.
 */
static String getDefaultProjectId() {
  String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME));
  if (projectId == null) {
    projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME));
  }
  if (projectId == null) {
    projectId = getServiceAccountProjectId();
  }
  return (projectId != null) ? projectId : ServiceOptions.getDefaultProjectId();
}
 
Example #28
Source File: MonitoringServlet.java    From tomcat-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  JsonNode body = objectMapper.readTree(req.getReader());
  String name = body.path("name").asText();
  long token = body.path("token").asLong();

  logger.info("Creating Time series with name " + name + " and token " + token);

  MetricServiceClient serviceClient = MetricServiceClient.create();

  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .addPoints(Point.newBuilder()
              .setValue(TypedValue.newBuilder().setInt64Value(token))
              .setInterval(TimeInterval.newBuilder()
                .setEndTime(Timestamp.now().toProto())))
          .setMetric(Metric.newBuilder().setType(name))
          .build();

  serviceClient.createTimeSeries(
      ProjectName.create(ServiceOptions.getDefaultProjectId()),
      Collections.singletonList(timeSeries));

  resp.setContentType("text/plain");
  resp.getWriter().println("OK");
}
 
Example #29
Source File: GoogleCloudPubSubConfiguration.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private static Optional<String> getDefaultProjectId() {
    final Optional<String> projectId = Optional.ofNullable(ServiceOptions.getDefaultProjectId());
    if (projectId.isPresent()) {
        logger.info("Discovered default Google Cloud project: {}", projectId.get());
    } else {
        logger.debug("No default Google Cloud project available.");
    }
    return projectId;
}
 
Example #30
Source File: MockCredentialsFactoryProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected ServiceOptions getServiceOptions(ProcessContext context, GoogleCredentials credentials) {
    ServiceOptions mockOptions = mock(ServiceOptions.class);
    Service mockService = mock(Service.class);
    when(mockOptions.getService()).thenReturn(mockService);

    return mockOptions;
}