Java Code Examples for com.google.cloud.ServiceOptions#getDefaultProjectId()

The following examples show how to use com.google.cloud.ServiceOptions#getDefaultProjectId() . 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: 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 2
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 3
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 4
Source File: GoogleCloudConfiguration.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Google project ID for the project.
 *
 * @return The project id
 * @throws ConfigurationException if no project ID is found
 */
public @Nonnull String getProjectId() {
    if (projectId == null) {
        projectId = ServiceOptions.getDefaultProjectId();
        if (projectId == null) {
            throw new ConfigurationException(NO_PROJECT_ID_MESSAGE);
        }
    }
    return projectId;
}
 
Example 5
Source File: BookExampleAppIT.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutput() {
  BookExampleApp bookExampleApp = new BookExampleApp(TEST_INSTANCE, TEST_DATABASE, ServiceOptions
      .getDefaultProjectId());

  bookExampleApp.dropTableIfPresent();
  bookExampleApp.createTable();
  bookExampleApp.saveBooks();
  bookExampleApp.retrieveBooks();

  assertThat(baos.toString()).contains("Table creation completed.");
  assertThat(baos.toString()).contains("Insert books transaction committed.");
  assertThat(baos.toString()).contains("Retrieved book: book1 Book One");
  assertThat(baos.toString()).contains("Retrieved book: book2 Book Two");
}
 
Example 6
Source File: PubsubIntegrationTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Create a Pub/Sub topic and subscription.
 *
 * @throws IOException if Pub/Sub is unavailable
 */
@Before
public void initializePubsubResources() throws IOException {
  projectId = ServiceOptions.getDefaultProjectId();
  topicId = "test-topic-" + UUID.randomUUID().toString();
  subscriptionId = "test-subscription-" + UUID.randomUUID().toString();
  topicName = ProjectTopicName.of(projectId, topicId);
  subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId);

  TopicAdminClient.create().createTopic(topicName);
  SubscriptionAdminClient.create().createSubscription(subscriptionName, topicName,
      PushConfig.getDefaultInstance(), 0);
}
 
Example 7
Source File: OpenCensusTraceLoggingEnhancer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String lookUpProjectId() {
  String projectIdProperty = lookUpProperty(PROJECT_ID_PROPERTY_NAME);
  return projectIdProperty == null || projectIdProperty.isEmpty()
      ? ServiceOptions.getDefaultProjectId()
      : projectIdProperty;
}
 
Example 8
Source File: StackdriverStatsConfigurationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void allowToUseDefaultProjectId() {
  String defaultProjectId = ServiceOptions.getDefaultProjectId();
  if (defaultProjectId != null) {
    StackdriverStatsConfiguration configuration = StackdriverStatsConfiguration.builder().build();
    assertThat(configuration.getProjectId()).isEqualTo(defaultProjectId);
  }
}
 
Example 9
Source File: StackdriverTraceConfigurationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void allowToUseDefaultProjectId() {
  String defaultProjectId = ServiceOptions.getDefaultProjectId();
  if (defaultProjectId != null) {
    StackdriverTraceConfiguration configuration = StackdriverTraceConfiguration.builder().build();
    assertThat(configuration.getProjectId()).isEqualTo(defaultProjectId);
  }
}
 
Example 10
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 11
Source File: GcpConfiguration.java    From spydra with Apache License 2.0 4 votes vote down vote up
@Override
public String getProjectId() {
  return ServiceOptions.getDefaultProjectId();
}
 
Example 12
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp()  {

    String projectId = ServiceOptions.getDefaultProjectId();
	try {

		//export GRPC_PROXY_EXP=localhost:3128
		HttpHost proxy = new HttpHost("127.0.0.1",3128);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
					
		httpClient.addRequestInterceptor(new HttpRequestInterceptor(){            
			@Override
			public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
					//if (request.getRequestLine().getMethod().equals("CONNECT"))                 
					//   request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
				}
			});
		
		mHttpTransport =  new ApacheHttpTransport(httpClient);		

		HttpTransportFactory hf = new HttpTransportFactory(){
			@Override
			public HttpTransport create() {
				return mHttpTransport;
			}
		};            
		
		credential = GoogleCredentials.getApplicationDefault(hf);

		CredentialsProvider credentialsProvider =  new GoogleCredentialsProvider(){
			public List<String> getScopesToApply(){
				return Arrays.asList("https://www.googleapis.com/auth/pubsub");
			   }

			public Credentials getCredentials()  {
				return credential;
			}
		};

		TopicAdminSettings topicAdminSettings =
		     TopicAdminSettings.newBuilder().setCredentialsProvider(credentialsProvider)
				 .build();
				 
		 TopicAdminClient topicAdminClient =
		     TopicAdminClient.create(topicAdminSettings);
		
		//TopicAdminClient topicAdminClient = TopicAdminClient.create();
		ProjectName project = ProjectName.create(projectId);
		for (Topic element : topicAdminClient.listTopics(project).iterateAll()) 
	  		System.out.println(element.getName());
	
	} catch (Exception ex) 
	{
		System.out.println("ERROR " + ex);
	}
  }
 
Example 13
Source File: DefaultGcpProjectIdProvider.java    From spring-cloud-gcp with Apache License 2.0 2 votes vote down vote up
/**
 * {@link ServiceOptions#getDefaultProjectId()} checks for the project ID in the
 * {@code GOOGLE_CLOUD_PROJECT} environment variable and the Metadata Server, among others.
 *
 * @return the project ID in the context
 */
@Override
public String getProjectId() {
	return ServiceOptions.getDefaultProjectId();
}