Dialogflow authentication programmatically javaDialogflow easy way for authorizationSetting up Dialogflow authentication for Java API gives needsCredentials errorIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Creating a memory leak with JavaDialogflow: The Application Default Credentials are not available

Why is this guy handcuffed censored?

Host telling me to cancel my booking in exchange for a discount?

Inside Out and Back to Front

Can two waves interfere head on?

"move up the school" meaning

How much did all the space agencies spent on rockets launching and space exploration? What are the benefits for me and you?

Manager is asking me to eat breakfast from now on

Conditional statement in a function for PS1 are not re-evalutated

Last-minute canceled work-trip means I'll lose thousands of dollars on planned vacation

Polynomials with natural coefficients arising from exponentiation and sums

Why does a tetrahedral molecule like methane have a dipole moment of zero?

Fitting two-dimensional data

Project Euler # 25 The 1000 digit Fibonacci index

Could a US citizen born through "birth tourism" become President?

The most secure way to handle someone forgetting to verify their account?

How is it possible for the induced emf to take negative values in Faraday's Law of induction?

Time war story - soldier name lengthens as he travels further from the battle front

Three Subway Escalators

ESTA Travel not Authorized. Accepted twice before!

Longtable of size textwidth exceeds right margin

Do I have to mention my main characters age?

What is really the difference between uniform velocity and constant velocity?

Soft constraints and hard constraints

What does a Nintendo Game Boy do when turned on without a game cartridge inserted?



Dialogflow authentication programmatically java


Dialogflow easy way for authorizationSetting up Dialogflow authentication for Java API gives needsCredentials errorIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Creating a memory leak with JavaDialogflow: The Application Default Credentials are not available






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















Hi there I have an issue with the authentication of dialogflow. I know I have to set an GOOGLE_APPLICATION_CREDENTIALS or download Gcloud CLI to acces my agent. But since I am going to use multiple agents I need to login with credentials to my API. So I do not want to use these methods.



I saw in an other thread that there is a code available for node.js who does exactly this what I want.



Dialogflow easy way for authorization.



I want to be able to process my downloaded json file to get acces to the dialogflow agent.



This is what I tried:



//Load the json file 
String credential = "JSON"
//Read the json file
GoogleCredentials credentials = GoogleCredentials.fromStream(new
ByteArrayInputStream(credential.getBytes()));
//Read the project ID
String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
System.out.println("the ID"+ projectId);
//Read the token
AccessToken token = ((ServiceAccountCredentials)credentials).getAccessToken();
System.out.println("the token "+ token);


It displays the projectID but the token is null. and the error I am receiving is



"message": "The Application Default Credentials are not available. They 
are available if running in Google Compute Engine. Otherwise, the
environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
pointing to a file defining the credentials. See
https://developers.google.com/accounts/docs/application-default-
credentials for more information.",


So now I am stuck how can I programmatically connect to other agents? without using the GOOGLE_APPLICATION_CREDENTIALS in Java?



Please help me out










share|improve this question




























    2















    Hi there I have an issue with the authentication of dialogflow. I know I have to set an GOOGLE_APPLICATION_CREDENTIALS or download Gcloud CLI to acces my agent. But since I am going to use multiple agents I need to login with credentials to my API. So I do not want to use these methods.



    I saw in an other thread that there is a code available for node.js who does exactly this what I want.



    Dialogflow easy way for authorization.



    I want to be able to process my downloaded json file to get acces to the dialogflow agent.



    This is what I tried:



    //Load the json file 
    String credential = "JSON"
    //Read the json file
    GoogleCredentials credentials = GoogleCredentials.fromStream(new
    ByteArrayInputStream(credential.getBytes()));
    //Read the project ID
    String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
    System.out.println("the ID"+ projectId);
    //Read the token
    AccessToken token = ((ServiceAccountCredentials)credentials).getAccessToken();
    System.out.println("the token "+ token);


    It displays the projectID but the token is null. and the error I am receiving is



    "message": "The Application Default Credentials are not available. They 
    are available if running in Google Compute Engine. Otherwise, the
    environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
    pointing to a file defining the credentials. See
    https://developers.google.com/accounts/docs/application-default-
    credentials for more information.",


    So now I am stuck how can I programmatically connect to other agents? without using the GOOGLE_APPLICATION_CREDENTIALS in Java?



    Please help me out










    share|improve this question
























      2












      2








      2








      Hi there I have an issue with the authentication of dialogflow. I know I have to set an GOOGLE_APPLICATION_CREDENTIALS or download Gcloud CLI to acces my agent. But since I am going to use multiple agents I need to login with credentials to my API. So I do not want to use these methods.



      I saw in an other thread that there is a code available for node.js who does exactly this what I want.



      Dialogflow easy way for authorization.



      I want to be able to process my downloaded json file to get acces to the dialogflow agent.



      This is what I tried:



      //Load the json file 
      String credential = "JSON"
      //Read the json file
      GoogleCredentials credentials = GoogleCredentials.fromStream(new
      ByteArrayInputStream(credential.getBytes()));
      //Read the project ID
      String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
      System.out.println("the ID"+ projectId);
      //Read the token
      AccessToken token = ((ServiceAccountCredentials)credentials).getAccessToken();
      System.out.println("the token "+ token);


      It displays the projectID but the token is null. and the error I am receiving is



      "message": "The Application Default Credentials are not available. They 
      are available if running in Google Compute Engine. Otherwise, the
      environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
      pointing to a file defining the credentials. See
      https://developers.google.com/accounts/docs/application-default-
      credentials for more information.",


      So now I am stuck how can I programmatically connect to other agents? without using the GOOGLE_APPLICATION_CREDENTIALS in Java?



      Please help me out










      share|improve this question














      Hi there I have an issue with the authentication of dialogflow. I know I have to set an GOOGLE_APPLICATION_CREDENTIALS or download Gcloud CLI to acces my agent. But since I am going to use multiple agents I need to login with credentials to my API. So I do not want to use these methods.



      I saw in an other thread that there is a code available for node.js who does exactly this what I want.



      Dialogflow easy way for authorization.



      I want to be able to process my downloaded json file to get acces to the dialogflow agent.



      This is what I tried:



      //Load the json file 
      String credential = "JSON"
      //Read the json file
      GoogleCredentials credentials = GoogleCredentials.fromStream(new
      ByteArrayInputStream(credential.getBytes()));
      //Read the project ID
      String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
      System.out.println("the ID"+ projectId);
      //Read the token
      AccessToken token = ((ServiceAccountCredentials)credentials).getAccessToken();
      System.out.println("the token "+ token);


      It displays the projectID but the token is null. and the error I am receiving is



      "message": "The Application Default Credentials are not available. They 
      are available if running in Google Compute Engine. Otherwise, the
      environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
      pointing to a file defining the credentials. See
      https://developers.google.com/accounts/docs/application-default-
      credentials for more information.",


      So now I am stuck how can I programmatically connect to other agents? without using the GOOGLE_APPLICATION_CREDENTIALS in Java?



      Please help me out







      java sdk dialogflow






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 11:54









      BcodedBcoded

      437 bronze badges




      437 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.



          Then I build a Credentials object with those values, and then a SessionSettings object with the credentials



          This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable



           PrivateKey privKey = null;

          StringBuilder pkcs8Lines = new StringBuilder();
          BufferedReader rdr = new BufferedReader(new StringReader(privatekey);


          String line;
          while ((line = rdr.readLine()) != null)
          pkcs8Lines.append(line);


          // Remove the "BEGIN" and "END" lines, as well as any whitespace

          String pkcs8Pem = pkcs8Lines.toString();
          pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replaceAll("\s+", "");

          // Base64 decode the result

          byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

          // extract the private key

          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
          KeyFactory kf;
          try
          kf = KeyFactory.getInstance("RSA");
          try
          privKey = kf.generatePrivate(keySpec);
          catch (InvalidKeySpecException e)
          throw new GenericException(e);

          catch (NoSuchAlgorithmException e)
          throw new GenericException(e);


          Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
          .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
          .setClientEmail(clientEmail).setClientId(clientId)
          .setTokenServerUri(URI.create(tokenServerUri)).build();

          SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

          try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {





          share|improve this answer























          • This is exactly what I was looking for!

            – Bcoded
            Jun 6 at 7:49










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55356542%2fdialogflow-authentication-programmatically-java%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.



          Then I build a Credentials object with those values, and then a SessionSettings object with the credentials



          This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable



           PrivateKey privKey = null;

          StringBuilder pkcs8Lines = new StringBuilder();
          BufferedReader rdr = new BufferedReader(new StringReader(privatekey);


          String line;
          while ((line = rdr.readLine()) != null)
          pkcs8Lines.append(line);


          // Remove the "BEGIN" and "END" lines, as well as any whitespace

          String pkcs8Pem = pkcs8Lines.toString();
          pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replaceAll("\s+", "");

          // Base64 decode the result

          byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

          // extract the private key

          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
          KeyFactory kf;
          try
          kf = KeyFactory.getInstance("RSA");
          try
          privKey = kf.generatePrivate(keySpec);
          catch (InvalidKeySpecException e)
          throw new GenericException(e);

          catch (NoSuchAlgorithmException e)
          throw new GenericException(e);


          Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
          .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
          .setClientEmail(clientEmail).setClientId(clientId)
          .setTokenServerUri(URI.create(tokenServerUri)).build();

          SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

          try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {





          share|improve this answer























          • This is exactly what I was looking for!

            – Bcoded
            Jun 6 at 7:49















          1














          I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.



          Then I build a Credentials object with those values, and then a SessionSettings object with the credentials



          This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable



           PrivateKey privKey = null;

          StringBuilder pkcs8Lines = new StringBuilder();
          BufferedReader rdr = new BufferedReader(new StringReader(privatekey);


          String line;
          while ((line = rdr.readLine()) != null)
          pkcs8Lines.append(line);


          // Remove the "BEGIN" and "END" lines, as well as any whitespace

          String pkcs8Pem = pkcs8Lines.toString();
          pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replaceAll("\s+", "");

          // Base64 decode the result

          byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

          // extract the private key

          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
          KeyFactory kf;
          try
          kf = KeyFactory.getInstance("RSA");
          try
          privKey = kf.generatePrivate(keySpec);
          catch (InvalidKeySpecException e)
          throw new GenericException(e);

          catch (NoSuchAlgorithmException e)
          throw new GenericException(e);


          Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
          .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
          .setClientEmail(clientEmail).setClientId(clientId)
          .setTokenServerUri(URI.create(tokenServerUri)).build();

          SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

          try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {





          share|improve this answer























          • This is exactly what I was looking for!

            – Bcoded
            Jun 6 at 7:49













          1












          1








          1







          I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.



          Then I build a Credentials object with those values, and then a SessionSettings object with the credentials



          This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable



           PrivateKey privKey = null;

          StringBuilder pkcs8Lines = new StringBuilder();
          BufferedReader rdr = new BufferedReader(new StringReader(privatekey);


          String line;
          while ((line = rdr.readLine()) != null)
          pkcs8Lines.append(line);


          // Remove the "BEGIN" and "END" lines, as well as any whitespace

          String pkcs8Pem = pkcs8Lines.toString();
          pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replaceAll("\s+", "");

          // Base64 decode the result

          byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

          // extract the private key

          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
          KeyFactory kf;
          try
          kf = KeyFactory.getInstance("RSA");
          try
          privKey = kf.generatePrivate(keySpec);
          catch (InvalidKeySpecException e)
          throw new GenericException(e);

          catch (NoSuchAlgorithmException e)
          throw new GenericException(e);


          Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
          .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
          .setClientEmail(clientEmail).setClientId(clientId)
          .setTokenServerUri(URI.create(tokenServerUri)).build();

          SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

          try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {





          share|improve this answer













          I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.



          Then I build a Credentials object with those values, and then a SessionSettings object with the credentials



          This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable



           PrivateKey privKey = null;

          StringBuilder pkcs8Lines = new StringBuilder();
          BufferedReader rdr = new BufferedReader(new StringReader(privatekey);


          String line;
          while ((line = rdr.readLine()) != null)
          pkcs8Lines.append(line);


          // Remove the "BEGIN" and "END" lines, as well as any whitespace

          String pkcs8Pem = pkcs8Lines.toString();
          pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
          pkcs8Pem = pkcs8Pem.replaceAll("\s+", "");

          // Base64 decode the result

          byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

          // extract the private key

          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
          KeyFactory kf;
          try
          kf = KeyFactory.getInstance("RSA");
          try
          privKey = kf.generatePrivate(keySpec);
          catch (InvalidKeySpecException e)
          throw new GenericException(e);

          catch (NoSuchAlgorithmException e)
          throw new GenericException(e);


          Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
          .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
          .setClientEmail(clientEmail).setClientId(clientId)
          .setTokenServerUri(URI.create(tokenServerUri)).build();

          SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

          try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 31 at 11:19









          Eduardo HermidaEduardo Hermida

          563 bronze badges




          563 bronze badges












          • This is exactly what I was looking for!

            – Bcoded
            Jun 6 at 7:49

















          • This is exactly what I was looking for!

            – Bcoded
            Jun 6 at 7:49
















          This is exactly what I was looking for!

          – Bcoded
          Jun 6 at 7:49





          This is exactly what I was looking for!

          – Bcoded
          Jun 6 at 7:49








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55356542%2fdialogflow-authentication-programmatically-java%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해