com.google.api.gax.core.FixedCredentialsProvider Java Examples

The following examples show how to use com.google.api.gax.core.FixedCredentialsProvider. 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: BigQueryStorageClientFactory.java    From presto with Apache License 2.0 6 votes vote down vote up
BigQueryStorageClient createBigQueryStorageClient()
{
    try {
        BigQueryStorageSettings.Builder clientSettings = BigQueryStorageSettings.newBuilder()
                .setTransportChannelProvider(
                        BigQueryStorageSettings.defaultGrpcTransportProviderBuilder()
                                .setHeaderProvider(headerProvider)
                                .build());
        credentials.ifPresent(credentials ->
                clientSettings.setCredentialsProvider(FixedCredentialsProvider.create(credentials)));
        return BigQueryStorageClient.create(clientSettings.build());
    }
    catch (IOException e) {
        throw new UncheckedIOException("Error creating BigQueryStorageClient", e);
    }
}
 
Example #2
Source File: PubSubSink.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void open(Configuration configuration) throws Exception {
	serializationSchema.open(() -> getRuntimeContext().getMetricGroup().addGroup("user"));

	Publisher.Builder builder = Publisher
		.newBuilder(ProjectTopicName.of(projectName, topicName))
		.setCredentialsProvider(FixedCredentialsProvider.create(credentials));

	if (hostAndPortForEmulator != null) {
		managedChannel = ManagedChannelBuilder
			.forTarget(hostAndPortForEmulator)
			.usePlaintext(true) // This is 'Ok' because this is ONLY used for testing.
			.build();
		channel = GrpcTransportChannel.newBuilder().setManagedChannel(managedChannel).build();
		builder.setChannelProvider(FixedTransportChannelProvider.create(channel))
				.setCredentialsProvider(NoCredentialsProvider.create());
	}

	publisher = builder.build();
	isRunning = true;
}
 
Example #3
Source File: StackdriverV2ExporterHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
static StackdriverV2ExporterHandler createWithCredentials(
    String projectId,
    Credentials credentials,
    Map<String, io.opencensus.trace.AttributeValue> fixedAttributes,
    Duration deadline)
    throws IOException {
  TraceServiceSettings.Builder builder =
      TraceServiceSettings.newBuilder()
          .setCredentialsProvider(
              FixedCredentialsProvider.create(checkNotNull(credentials, "credentials")));
  // We only use the batchWriteSpans API in this exporter.
  builder
      .batchWriteSpansSettings()
      .setSimpleTimeoutNoRetries(org.threeten.bp.Duration.ofMillis(deadline.toMillis()));
  return new StackdriverV2ExporterHandler(
      projectId, TraceServiceClient.create(builder.build()), fixedAttributes);
}
 
Example #4
Source File: StackdriverStatsExporter.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@GuardedBy("monitor")
@VisibleForTesting
static MetricServiceClient createMetricServiceClient(
    @Nullable Credentials credentials, Duration deadline) throws IOException {
  MetricServiceSettings.Builder settingsBuilder =
      MetricServiceSettings.newBuilder()
          .setTransportChannelProvider(
              InstantiatingGrpcChannelProvider.newBuilder()
                  .setHeaderProvider(OPENCENSUS_USER_AGENT_HEADER_PROVIDER)
                  .build());
  if (credentials != null) {
    settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
  }

  org.threeten.bp.Duration stackdriverDuration =
      org.threeten.bp.Duration.ofMillis(deadline.toMillis());
  // We use createMetricDescriptor and createTimeSeries APIs in this exporter.
  settingsBuilder.createMetricDescriptorSettings().setSimpleTimeoutNoRetries(stackdriverDuration);
  settingsBuilder.createTimeSeriesSettings().setSimpleTimeoutNoRetries(stackdriverDuration);

  return MetricServiceClient.create(settingsBuilder.build());
}
 
Example #5
Source File: StackdriverConfig.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * Return {@link CredentialsProvider} to use.
 *
 * @return {@code CredentialsProvider} to use
 * @since 1.4.0
 */
default CredentialsProvider credentials() {
    return getString(this, "credentials")
            .flatMap((credentials, valid) -> {
                if (StringUtils.isBlank(credentials)) {
                    return Validated.valid(valid.getProperty(), MetricServiceSettings.defaultCredentialsProviderBuilder().build());
                }

                try {
                    FixedCredentialsProvider provider = FixedCredentialsProvider.create(
                            GoogleCredentials.fromStream(new FileInputStream(credentials))
                                    .createScoped(MetricServiceSettings.getDefaultServiceScopes())
                    );
                    return Validated.valid(valid.getProperty(), provider);
                } catch (IOException t) {
                    return Validated.invalid(valid.getProperty(), credentials, "cannot read credentials file", InvalidReason.MALFORMED, t);
                }
            })
            .get();
}
 
Example #6
Source File: FirestoreClient.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private FirestoreClient(FirebaseApp app) {
  checkNotNull(app, "FirebaseApp must not be null");
  String projectId = ImplFirebaseTrampolines.getProjectId(app);
  checkArgument(!Strings.isNullOrEmpty(projectId),
      "Project ID is required for accessing Firestore. Use a service account credential or "
          + "set the project ID explicitly via FirebaseOptions. Alternatively you can also "
          + "set the project ID via the GOOGLE_CLOUD_PROJECT environment variable.");
  FirestoreOptions userOptions = ImplFirebaseTrampolines.getFirestoreOptions(app);
  FirestoreOptions.Builder builder = userOptions != null
      ? userOptions.toBuilder() : FirestoreOptions.newBuilder();
  this.firestore = builder
      // CredentialsProvider has highest priority in FirestoreOptions, so we set that.
      .setCredentialsProvider(
          FixedCredentialsProvider.create(ImplFirebaseTrampolines.getCredentials(app)))
      .setProjectId(projectId)
      .build()
      .getService();
}
 
Example #7
Source File: PubSubManager.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private static Optional<CredentialsProvider> buildCredentialsProvider(final PubSubConfig config) {
    if (config.isMockPubSubTopics()) {
        return Optional.of(NoCredentialsProvider.create());
    }

    if (config.getCredentialPath() != null) {
        try {
            return Optional.of(FixedCredentialsProvider
                    .create(ServiceAccountCredentials.fromStream(Files.newInputStream(config.getCredentialPath()))));
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        }
    }

    return Optional.empty();
}
 
Example #8
Source File: BigQueryServicesImpl.java    From beam with Apache License 2.0 5 votes vote down vote up
private StorageClientImpl(BigQueryOptions options) throws IOException {
  BigQueryStorageSettings settings =
      BigQueryStorageSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(options.getGcpCredential()))
          .setTransportChannelProvider(
              BigQueryStorageSettings.defaultGrpcTransportProviderBuilder()
                  .setHeaderProvider(USER_AGENT_HEADER_PROVIDER)
                  .build())
          .build();
  this.client = BigQueryStorageClient.create(settings);
}
 
Example #9
Source File: PublishGCPubSub.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Publisher.Builder getPublisherBuilder(ProcessContext context) {
    final Long batchSize = context.getProperty(BATCH_SIZE).asLong();

    return Publisher.newBuilder(getTopicName(context))
            .setCredentialsProvider(FixedCredentialsProvider.create(getGoogleCredentials(context)))
            .setBatchingSettings(BatchingSettings.newBuilder()
            .setElementCountThreshold(batchSize)
            .setIsEnabled(true)
            .build());
}
 
Example #10
Source File: ConsumeGCPubSub.java    From nifi with Apache License 2.0 5 votes vote down vote up
private SubscriberStub getSubscriber(ProcessContext context) throws IOException {

        final SubscriberStubSettings subscriberStubSettings = SubscriberStubSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(getGoogleCredentials(context)))
                .build();

        return GrpcSubscriberStub.create(subscriberStubSettings);
    }
 
Example #11
Source File: ComputeExample.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
private static AddressClient createCredentialedClient() throws IOException {
  Credentials myCredentials = GoogleCredentials.getApplicationDefault();
  String myEndpoint = AddressSettings.getDefaultEndpoint();

  AddressSettings addressSettings =
      AddressSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
          .setTransportChannelProvider(
              AddressSettings.defaultHttpJsonTransportProviderBuilder()
                  .setEndpoint(myEndpoint)
                  .build())
          .build();
  return AddressClient.create(addressSettings);
}
 
Example #12
Source File: BigQueryReadClientFactory.java    From spark-bigquery-connector with Apache License 2.0 5 votes vote down vote up
BigQueryReadClient createBigQueryReadClient() {
    try {
        BigQueryReadSettings.Builder clientSettings = BigQueryReadSettings.newBuilder()
                .setTransportChannelProvider(
                        BigQueryReadSettings.defaultGrpcTransportProviderBuilder()
                                .setHeaderProvider(userAgentHeaderProvider)
                                .build())
                .setCredentialsProvider(FixedCredentialsProvider.create(credentials));
        return BigQueryReadClient.create(clientSettings.build());
    } catch (IOException e) {
        throw new UncheckedIOException("Error creating BigQueryStorageClient", e);
    }
}
 
Example #13
Source File: GooglePubsubSubscriber.java    From echo with Apache License 2.0 5 votes vote down vote up
public synchronized void start() {
  this.subscriber =
      Subscriber.newBuilder(
              ProjectSubscriptionName.of(project, subscriptionName), messageReceiver)
          .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
          .build();

  subscriber.addListener(
      new GooglePubsubFailureHandler(this, formatSubscriptionName(project, subscriptionName)),
      MoreExecutors.directExecutor());
  subscriber.startAsync().awaitRunning();
  log.info(
      "Google Pubsub subscriber started for {}",
      formatSubscriptionName(project, subscriptionName));
}
 
Example #14
Source File: GrpcTraceConsumer.java    From cloud-trace-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a trace consumer that sends trace messages to the Stackdriver Trace API via gRPC.
 *
 * @param credentials a credentials used to authenticate API calls.
 */
public static GrpcTraceConsumer createWithCredentials(Credentials credentials)
    throws IOException {
  TraceServiceSettings traceServiceSettings =
      TraceServiceSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
          .build();

  return new GrpcTraceConsumer(TraceServiceClient.create(traceServiceSettings));
}
 
Example #15
Source File: GrpcTraceConsumer.java    From cloud-trace-java with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated Use {@link #createWithCredentials(Credentials)}.
 * @param apiHost a string containing the API host name.
 * @param credentials a credentials used to authenticate API calls.
 */
@Deprecated
public static GrpcTraceConsumer create(String apiHost, Credentials credentials)
    throws IOException {
  TraceServiceSettings traceServiceSettings =
      TraceServiceSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
          .setTransportChannelProvider(TraceServiceSettings.defaultGrpcTransportProviderBuilder()
              .setEndpoint(apiHost)
              .build())
          .build();

  return new GrpcTraceConsumer(TraceServiceClient.create(traceServiceSettings));
}
 
Example #16
Source File: PhotosLibraryClientFactory.java    From java-photoslibrary with Apache License 2.0 5 votes vote down vote up
/** Creates a new {@link PhotosLibraryClient} instance with credentials and scopes. */
public static PhotosLibraryClient createClient(
    String credentialsPath, List<String> selectedScopes)
    throws IOException, GeneralSecurityException {
  PhotosLibrarySettings settings =
      PhotosLibrarySettings.newBuilder()
          .setCredentialsProvider(
              FixedCredentialsProvider.create(
                  getUserCredentials(credentialsPath, selectedScopes)))
          .build();
  return PhotosLibraryClient.initialize(settings);
}
 
Example #17
Source File: PubSubSink.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void open(Configuration configuration) throws Exception {
	Publisher.Builder builder = Publisher
		.newBuilder(ProjectTopicName.of(projectName, topicName))
		.setCredentialsProvider(FixedCredentialsProvider.create(credentials));

	if (hostAndPortForEmulator != null) {
		managedChannel = ManagedChannelBuilder
			.forTarget(hostAndPortForEmulator)
			.usePlaintext(true) // This is 'Ok' because this is ONLY used for testing.
			.build();
		channel = GrpcTransportChannel.newBuilder().setManagedChannel(managedChannel).build();
		builder.setChannelProvider(FixedTransportChannelProvider.create(channel))
				.setCredentialsProvider(NoCredentialsProvider.create());
	}

	publisher = builder.build();
	isRunning = true;
}
 
Example #18
Source File: MainActivity.java    From DialogflowChat with Apache License 2.0 5 votes vote down vote up
private void initV2Chatbot() {
    try {
        InputStream stream = getResources().openRawResource(R.raw.test_agent_credentials);
        GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
        String projectId = ((ServiceAccountCredentials)credentials).getProjectId();

        SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
        SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
        sessionsClient = SessionsClient.create(sessionsSettings);
        session = SessionName.of(projectId, uuid);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: SampleRegistries.java    From micrometer with Apache License 2.0 5 votes vote down vote up
/**
 * @param serviceAccountJson The fully qualified path on the local file system to a service account's JSON.
 * @param projectId          The Google Cloud project id found on the dropdown at the top of the Google Cloud console.
 * @see <a href="https://cloud.google.com/monitoring/docs/reference/libraries#setting_up_authentication">Google Cloud authentication</a>
 * @return A Stackdriver registry.
 */
public static StackdriverMeterRegistry stackdriver(String serviceAccountJson, String projectId) {
    try (InputStream credentials = new FileInputStream(new File(serviceAccountJson))) {
        return StackdriverMeterRegistry
                .builder(new StackdriverConfig() {
                    @Override
                    public String projectId() {
                        return projectId;
                    }

                    @Override
                    public String get(String key) {
                        return null;
                    }

                    @Override
                    public Duration step() {
                        return Duration.ofSeconds(10);
                    }
                })
                .metricServiceSettings(() -> MetricServiceSettings.newBuilder()
                        .setCredentialsProvider(FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(credentials)))
                        .build()
                )
                .build();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #20
Source File: GoogleAdsVersionFactory.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/** Creates a new settings object for a @ServiceClientDescriptor method. */
private ClientSettings createClientSettings(Method method)
    throws IllegalAccessException, InvocationTargetException, IOException {
  Method settingsBuilderFactory = settingsBuilders.get(method);
  Builder settingsBuilder = (Builder) settingsBuilderFactory.invoke(null);
  settingsBuilder.setTransportChannelProvider(transportChannelProvider);
  settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
  return settingsBuilder.build();
}
 
Example #21
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp() {
	try
	{
		/*
		// For GoogleAPIs
		HttpTransport httpTransport = new NetHttpTransport();             
		JacksonFactory jsonFactory = new JacksonFactory();
		//ComputeCredential credential = new ComputeCredential.Builder(httpTransport, jsonFactory).build();	
		GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory);				            
		if (credential.createScopedRequired())
		    credential = credential.createScoped(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));           				            
		Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
		            .setApplicationName("oauth client")   
		            .build();				            
		Userinfoplus ui = service.userinfo().get().execute();
		System.out.println(ui.getEmail());
		*/

         // Using Google Cloud APIs
	  Storage storage_service = StorageOptions.newBuilder()
		.build()
		.getService();	
	  for (Bucket b : storage_service.list().iterateAll()){
		  System.out.println(b);
	  }

         // String cred_file = "/path/to/cred.json";
	  //GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(cred_file));	
	  GoogleCredentials creds = GoogleCredentials.getApplicationDefault();	  	  
	  FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(creds);
	  
	  ///ManagedChannel channel = ManagedChannelBuilder.forTarget("pubsub.googleapis.com:443").build();
         //TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));	
	  
	  TransportChannelProvider channelProvider = TopicAdminSettings.defaultTransportChannelProvider();

	  TopicAdminClient topicClient =
		  TopicAdminClient.create(
			  TopicAdminSettings.newBuilder()
				  .setTransportChannelProvider(channelProvider)
				  .setCredentialsProvider(credentialsProvider)
				  .build());

	  ListTopicsRequest listTopicsRequest =
						ListTopicsRequest.newBuilder()
							.setProject(ProjectName.format("your_project"))
							.build();
	  ListTopicsPagedResponse response = topicClient.listTopics(listTopicsRequest);
	  Iterable<Topic> topics = response.iterateAll();
	  for (Topic topic : topics) 
		 System.out.println(topic);
	 		  

	} 
	catch (Exception ex) {
		System.out.println("Error:  " + ex);
	}
}
 
Example #22
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp() {
		try
		{

			// use env or set the path directly
			String cred_env = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
			cred_env = "/path/to/your/cert.json";
			
/*
			<!--use:
				<dependency>
				<groupId>com.google.api-client</groupId>
				<artifactId>google-api-client</artifactId>
				<version>1.23.0</version>
				</dependency>
				<dependency>
				<groupId>com.google.apis</groupId>
				<artifactId>google-api-services-oauth2</artifactId>
				<version>v2-rev114-1.22.0</version>
				</dependency>
			--> 
			HttpTransport httpTransport = new NetHttpTransport();             
			JacksonFactory jsonFactory = new JacksonFactory();

            // unset GOOGLE_APPLICATION_CREDENTIALS
            //String SERVICE_ACCOUNT_JSON_FILE = "YOUR_SERVICE_ACCOUNT_JSON_FILE.json";
            //FileInputStream inputStream = new FileInputStream(new File(SERVICE_ACCOUNT_JSON_FILE));
            //GoogleCredential credential = GoogleCredential.fromStream(inputStream, httpTransport, jsonFactory);

			// to use application default credentials and a JSON file, set the environment variable first:
            // export GOOGLE_APPLICATION_CREDENTIALS=YOUR_SERVICE_ACCOUNT_JSON_FILE.json        
            GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory);

            if (credential.createScopedRequired())
                credential = credential.createScoped(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));

			Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
			            .setApplicationName("oauth client")   
			            .build();				            
			Userinfoplus ui = service.userinfo().get().execute();
			System.out.println(ui.getEmail());
*/
/* 
          Using Google Cloud APIs with service account file
		  // You can also just export an export GOOGLE_APPLICATION_CREDENTIALS and use StorageOptions.defaultInstance().service()
		  // see: https://github.com/google/google-auth-library-java#google-auth-library-oauth2-http
		  uncomment the dependencies for google-api-client
		  
			<dependency>
				<groupId>com.google.cloud</groupId>
				<artifactId>google-cloud-storage</artifactId>
				<version>1.35.0</version>
			</dependency>

			<dependency>
				<groupId>com.google.cloud</groupId>
				<artifactId>google-cloud-pubsub</artifactId>
				<version>1.35.0</version>
			</dependency>
*/
		  
		  
		  Storage storage_service = StorageOptions.newBuilder()
			.build()
			.getService();	
		  for (Bucket b : storage_service.list().iterateAll()){
			  System.out.println(b);
		  }

		  //GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(cred_env));	
		  GoogleCredentials creds = GoogleCredentials.getApplicationDefault();	  	  
		  FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(creds);
		  
		  ///ManagedChannel channel = ManagedChannelBuilder.forTarget("pubsub.googleapis.com:443").build();
          //TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));	
		  
		  TransportChannelProvider channelProvider = TopicAdminSettings.defaultTransportChannelProvider();

		  TopicAdminClient topicClient =
			  TopicAdminClient.create(
				  TopicAdminSettings.newBuilder()
					  .setTransportChannelProvider(channelProvider)
					  .setCredentialsProvider(credentialsProvider)
					  .build());

		  ListTopicsRequest listTopicsRequest =
							ListTopicsRequest.newBuilder()
								.setProject(ProjectName.format("your_project"))
								.build();
		  ListTopicsPagedResponse response = topicClient.listTopics(listTopicsRequest);
		  Iterable<Topic> topics = response.iterateAll();
		  for (Topic topic : topics) 
			 System.out.println(topic);
		 

		} 
		catch (Exception ex) {
			System.out.println("Error:  " + ex);
		}
	}
 
Example #23
Source File: ApiRequest.java    From android-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * function to get the DetectIntentRequest object
 *
 * @param sessionName              : sessionName object
 * @param queryInput               : queryInput object
 * @param tts                      : if text to speech is true
 * @param sentiment                : if sentiment analysis is true
 * @param knowledge                : if knowledge base is true
 * @param fixedCredentialsProvider : fixedCredentialsProvider for knowledgebase
 * @return : DetectIntentRequest object
 */
private DetectIntentRequest getDetectIntentRequest(SessionName sessionName,
        QueryInput queryInput, boolean tts, boolean sentiment, boolean knowledge,
        FixedCredentialsProvider fixedCredentialsProvider, byte[] audioBytes) throws Exception {

    DetectIntentRequest.Builder detectIntentRequestBuilder = DetectIntentRequest.newBuilder()
            .setSession(sessionName.toString())
            .setQueryInput(queryInput);

    if (audioBytes != null) {
        detectIntentRequestBuilder.setInputAudio(ByteString.copyFrom(audioBytes));
    }

    QueryParameters.Builder queryParametersBuilder = QueryParameters.newBuilder();

    if (tts) {
        OutputAudioEncoding audioEncoding = OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_MP3;
        int sampleRateHertz = 16000;
        OutputAudioConfig outputAudioConfig = OutputAudioConfig.newBuilder()
                .setAudioEncoding(audioEncoding)
                .setSampleRateHertz(sampleRateHertz)
                .build();

        detectIntentRequestBuilder.setOutputAudioConfig(outputAudioConfig);
    }

    if (sentiment) {
        SentimentAnalysisRequestConfig sentimentAnalysisRequestConfig =
                SentimentAnalysisRequestConfig.newBuilder()
                        .setAnalyzeQueryTextSentiment(true).build();

        queryParametersBuilder
                .setSentimentAnalysisRequestConfig(sentimentAnalysisRequestConfig);
    }


    if (knowledge) {
        KnowledgeBasesSettings knowledgeSessionsSettings = KnowledgeBasesSettings.newBuilder()
                .setCredentialsProvider(fixedCredentialsProvider).build();
        ArrayList<String> knowledgeBaseNames =
                KnowledgeBaseUtils.listKnowledgeBases(
                        AppController.PROJECT_ID, knowledgeSessionsSettings);

        if (knowledgeBaseNames.size() > 0) {
            // As an example, we'll only grab the first Knowledge Base
            queryParametersBuilder.addKnowledgeBaseNames(knowledgeBaseNames.get(0));
        }
    }

    QueryParameters queryParameters = queryParametersBuilder.build();
    detectIntentRequestBuilder.setQueryParams(queryParameters);

    return detectIntentRequestBuilder.build();
}
 
Example #24
Source File: ApiRequest.java    From android-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * function to getting the results from the dialogflow
 *
 * @param msg        :   message sent by the user
 * @param audioBytes :   audio sent by the user
 * @param tts        :   send message to text to speech if true
 * @param sentiment  :   send message to sentiment analysis if true
 * @param knowledge  :   send message to knowledge base if true
 * @return :   response from the server
 */
private String detectIntent(String msg, byte[] audioBytes, boolean tts, boolean sentiment,
                            boolean knowledge) {
    try {
        AccessToken accessToken = new AccessToken(token, tokenExpiration);
        Credentials credentials = GoogleCredentials.create(accessToken);
        FixedCredentialsProvider fixedCredentialsProvider =
                FixedCredentialsProvider.create(credentials);
        SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
                .setCredentialsProvider(fixedCredentialsProvider).build();
        SessionsClient sessionsClient = SessionsClient.create(sessionsSettings);
        SessionName sessionName = SessionName.of(AppController.PROJECT_ID,
                AppController.SESSION_ID);

        QueryInput queryInput;
        if (msg != null) {
            // Set the text (hello) and language code (en-US) for the query
            TextInput textInput = TextInput.newBuilder()
                    .setText(msg)
                    .setLanguageCode("en-US")
                    .build();

            // Build the query with the TextInput
            queryInput = QueryInput.newBuilder().setText(textInput).build();
        } else {
            // Instructs the speech recognizer how to process the audio content.
            InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder()
                    .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_AMR)
                    .setLanguageCode("en-US")
                    .setSampleRateHertz(8000)
                    .build();

            // Build the query with the TextInput
            queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
        }

        DetectIntentRequest detectIntentRequest = getDetectIntentRequest(sessionName,
                queryInput, tts, sentiment, knowledge, fixedCredentialsProvider, audioBytes);

        DetectIntentResponse detectIntentResponse =
                sessionsClient.detectIntent(detectIntentRequest);

        sessionsClient.close();

        if (tts) {
            AppController.playAudio(detectIntentResponse.getOutputAudio().toByteArray());
        }

        if (msg != null) {
            return handleResults(detectIntentResponse);
        } else {
            return String.format(
                    "%s|%s",
                    handleResults(detectIntentResponse),
                    detectIntentResponse.getQueryResult().getQueryText());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return ex.getMessage();
    }
}
 
Example #25
Source File: DefaultCredentialsProvider.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
/**
 * The credentials provided by this object originate from the following sources:
 * <ul>
 *     <li>*.credentials.location: Credentials built from JSON content inside the file pointed
 *     to by this property,</li>
 *     <li>*.credentials.encoded-key: Credentials built from JSON String, encoded on
 *     base64,</li>
 *     <li>Google Cloud Client Libraries default credentials provider.</li>
 * </ul>
 *
 * <p>If credentials are provided by one source, the next sources are discarded.
 * @param credentialsSupplier provides properties that can override OAuth2
 * scopes list used by the credentials, and the location of the OAuth2 credentials private
 * key.
 * @throws IOException if an issue occurs creating the DefaultCredentialsProvider
 */
public DefaultCredentialsProvider(CredentialsSupplier credentialsSupplier) throws IOException {
	List<String> scopes = resolveScopes(credentialsSupplier.getCredentials().getScopes());
	Resource providedLocation = credentialsSupplier.getCredentials().getLocation();
	String encodedKey = credentialsSupplier.getCredentials().getEncodedKey();

	if (!StringUtils.isEmpty(providedLocation)) {
		this.wrappedCredentialsProvider = FixedCredentialsProvider
				.create(GoogleCredentials.fromStream(
						providedLocation.getInputStream())
						.createScoped(scopes));
	}
	else if (!StringUtils.isEmpty(encodedKey)) {
		this.wrappedCredentialsProvider = FixedCredentialsProvider.create(
				GoogleCredentials.fromStream(
						new ByteArrayInputStream(Base64.getDecoder().decode(encodedKey)))
						.createScoped(scopes));
	}
	else {
		this.wrappedCredentialsProvider = GoogleCredentialsProvider.newBuilder()
				.setScopesToApply(scopes)
				.build();
	}

	try {
		Credentials credentials = this.wrappedCredentialsProvider.getCredentials();

		if (LOGGER.isInfoEnabled()) {
			if (credentials instanceof UserCredentials) {
				LOGGER.info("Default credentials provider for user "
						+ ((UserCredentials) credentials).getClientId());
			}
			else if (credentials instanceof ServiceAccountCredentials) {
				LOGGER.info("Default credentials provider for service account "
						+ ((ServiceAccountCredentials) credentials).getClientEmail());
			}
			else if (credentials instanceof ComputeEngineCredentials) {
				LOGGER.info("Default credentials provider for Google Compute Engine.");
			}
			LOGGER.info("Scopes in use by default credentials: " + scopes.toString());
		}
	}
	catch (IOException ioe) {
		LOGGER.warn("No core credentials are set. Service-specific credentials " +
				"(e.g., spring.cloud.gcp.pubsub.credentials.*) should be used if your app uses "
				+ "services that require credentials.", ioe);
	}
}