Java Code Examples for com.google.api.gax.core.FixedCredentialsProvider#create()

The following examples show how to use com.google.api.gax.core.FixedCredentialsProvider#create() . 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: 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);
	}
}
 
Example 2
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 3
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 4
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);
		}
	}