I created a simple dialogflow intent.
I want to consume it from java application in local environment (Linux).
I get the error :
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.
I set environment variable like this :
export GOOGLE_APPLICATION_CREDENTIALS="/home/me/******.json"
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-dialogflow</artifactId>
<version>0.99.0-alpha</version>
</dependency>
public class App {
public static void main(String[] args) throws Exception {
String projectId = "my-project-id";
String sessionId = "fake_session_for_testing";
String languageCode = "fr-FR";
List<String> texts = Arrays.asList("hello", "Qui tu es");
Map<String, QueryResult> result = detectIntentTexts(projectId, texts, sessionId, languageCode);
result.forEach((s, q) -> System.out.println(s + " " + q));
}
public static Map<String, QueryResult> detectIntentTexts(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
Map<String, QueryResult> queryResults = new HashMap<>();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
System.out.println("Session Path: " + session.toString());
// Detect intents for each text input
for (String text : texts) {
// Set the text (hello) and language code (en-US) for the query
TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
// Build the query with the TextInput
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
// Performs the detect intent request
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
// Display the query result
QueryResult queryResult = response.getQueryResult();
System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
queryResults.put(text, queryResult);
}
}
return queryResults;
}
}
Related
I am trying create one application from where I can get the all the information related to user/Tracks/Album.
I have used below code for authentication using clientid and client secret id.
private static String clintId = "generated id";
private static String clientSecretId = "generated secret id";
private static final URI redirectUri = SpotifyHttpManager.makeUri("http://localhost:8080/api/get-user-code/");
public static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setClientId(clintId)
.setClientSecret(clientSecretId)
.setRedirectUri(redirectUri)
.build();
#GetMapping("login")
#ResponseBody
public String spotifyLogin(){
AuthorizationCodeUriRequest authorizationCodeUriRequest = spotifyApi.authorizationCodeUri()
.scope("user-read-private user-read-email user-top-read user-library-read user-library-modify")
.show_dialog(true)
.build();
final URI uri = authorizationCodeUriRequest.execute();
return uri.toString();
}
#GetMapping(value="get-user-code")
public void getSpotifyUserCode(#RequestParam("code") String userCode, HttpServletResponse response) throws IOException {
AuthorizationCodeRequest authorizationCodeRequest = spotifyApi.authorizationCode(userCode)
.build();
try {
final AuthorizationCodeCredentials authorizationCodeCredentials = authorizationCodeRequest.execute();
// Set access and refresh token for further "spotifyApi" object usage
System.out.println("Access token::"+authorizationCodeCredentials.getAccessToken());
spotifyApi.setAccessToken(authorizationCodeCredentials.getAccessToken());
spotifyApi.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
System.out.println("Expires in: " + authorizationCodeCredentials.getExpiresIn());
} catch (IOException | SpotifyWebApiException | org.apache.hc.core5.http.ParseException e){
System.out.println("Error: " + e.getMessage());
}
response.sendRedirect("http://localhost:3000/home");
}
Now take one example: Suppose I have created above client id and secret id from User A (From development dashboard) so for User A everything is working fine like I am able to get user profile, Track etc.
But suppose if I try to get same details for User B like user profile/tracks etc with User A generated client id and secret id then not able to get those information for User B its showing "forbidden".
So my question is that how to get those information for user B (with user A client id and secret details)?
I am testing android managment API using localhost as call back url. I followed each and every step following this url Android Management API Sample.
Now i m stuck on place.. according to this guide, i download the json file from service account. Now i copy that json file and save in app folder of my project.
This is my enterprise.json file
Screenshot of json file in android studio
and i just give folder location as enterprise.json in location string
This is my code
private static final String PROJECT_ID = "enterprise-271814";
private static final String SERVICE_ACCOUNT_CREDENTIAL_FILE =
"enterprise.json";
private static final String POLICY_ID = "samplePolicy";
/** The package name of the COSU app. */
private static final String COSU_APP_PACKAGE_NAME =
"com.ariaware.devicepoliceycontroller";
/** The OAuth scope for the Android Management API. */
private static final String OAUTH_SCOPE =
"https://www.googleapis.com/auth/androidmanagement";
private static final String APP_NAME = "Device Policey Controller";
private final AndroidManagement androidManagementClient;
public Sample(AndroidManagement androidManagementClient) {
this.androidManagementClient = androidManagementClient;
}
public void run() throws IOException {
// Create an enterprise. If you've already created an enterprise, the
// createEnterprise call can be commented out and replaced with your
// enterprise name.
String enterpriseName = createEnterprise();
System.out.println("Enterprise created with name: " + enterpriseName);
// Set the policy to be used by the device.
setPolicy(enterpriseName, POLICY_ID, getCosuPolicy());
// Create an enrollment token to enroll the device.
String token = createEnrollmentToken(enterpriseName, POLICY_ID);
System.out.println("Enrollment token (to be typed on device): " + token);
// List some of the devices for the enterprise. There will be no devices for
// a newly created enterprise, but you can run the app again with an
// existing enterprise after enrolling a device.
List<Device> devices = listDevices(enterpriseName);
for (Device device : devices) {
System.out.println("Found device with name: " + device.getName());
}
// If there are any devices, reboot one.
if (devices.isEmpty()) {
System.out.println("No devices found.");
} else {
rebootDevice(devices.get(0));
}
}
public static AndroidManagement getAndroidManagementClient()
throws IOException, GeneralSecurityException {
try (FileInputStream input =
new FileInputStream(SERVICE_ACCOUNT_CREDENTIAL_FILE)) {
GoogleCredential credential =
GoogleCredential.fromStream(input)
.createScoped(Collections.singleton(OAUTH_SCOPE));
return new AndroidManagement.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName(APP_NAME)
.build();
}
}
private String createEnterprise() throws IOException {
// Initiate signup process.
System.out.println("Creating signup URL...");
SignupUrl signupUrl =
androidManagementClient
.signupUrls()
.create()
.setProjectId(PROJECT_ID)
.setCallbackUrl("https://localhost:9999")
.execute();
System.out.print(
"To sign up for a new enterprise, open this URL in your browser: ");
System.out.println(signupUrl.getUrl());
System.out.println(
"After signup, you will see an error page in the browser.");
System.out.print(
"Paste the enterpriseToken value from the error page URL here: ");
String enterpriseToken =
new BufferedReader(new InputStreamReader(System.in)).readLine();
// Create the enterprise.
System.out.println("Creating enterprise...");
return androidManagementClient
.enterprises()
.create(new Enterprise())
.setProjectId(PROJECT_ID)
.setSignupUrlName(signupUrl.getName())
.setEnterpriseToken(enterpriseToken)
.execute()
.getName();
}
private Policy getCosuPolicy() {
List<String> categories = new ArrayList<>();
categories.add("android.intent.category.HOME");
categories.add("android.intent.category.DEFAULT");
return new Policy()
.setApplications(
Collections.singletonList(
new ApplicationPolicy()
.setPackageName(COSU_APP_PACKAGE_NAME)
.setInstallType("FORCE_INSTALLED")
.setDefaultPermissionPolicy("GRANT")
.setLockTaskAllowed(true)))
.setPersistentPreferredActivities(
Collections.singletonList(
new PersistentPreferredActivity()
.setReceiverActivity(COSU_APP_PACKAGE_NAME)
.setActions(
Collections.singletonList("android.intent.action.MAIN"))
.setCategories(categories)))
.setKeyguardDisabled(true)
.setStatusBarDisabled(true);
}
private void setPolicy(String enterpriseName, String policyId, Policy policy)
throws IOException {
System.out.println("Setting policy...");
String name = enterpriseName + "/policies/" + policyId;
androidManagementClient
.enterprises()
.policies()
.patch(name, policy)
.execute();
}
private String createEnrollmentToken(String enterpriseName, String policyId)
throws IOException {
System.out.println("Creating enrollment token...");
EnrollmentToken token =
new EnrollmentToken().setPolicyName(policyId).setDuration("86400s");
return androidManagementClient
.enterprises()
.enrollmentTokens()
.create(enterpriseName, token)
.execute()
.getValue();
}
private List<Device> listDevices(String enterpriseName) throws IOException {
System.out.println("Listing devices...");
ListDevicesResponse response =
androidManagementClient
.enterprises()
.devices()
.list(enterpriseName)
.execute();
return response.getDevices() ==null
? new ArrayList<Device>() : response.getDevices();
}
private void rebootDevice(Device device) throws IOException {
System.out.println(
"Sending reboot command to " + device.getName() + "...");
Command command = new Command().setType("REBOOT");
androidManagementClient
.enterprises()
.devices()
.issueCommand(device.getName(), command)
.execute();
}
Moreover i m using android management api for the first time and i dont know its proper implementation. Anyone who has experience on this kinllt guide me a little bit. I found a lot about this but i didn't found any userful tutorial
For Android, you have to store the service account file either in the assets folder or raw folder.
This thread provides code on a number of ways to load the json data into an InputStream depending on the location you selected.
I'm setting up a chat bot in JHIPSTER & Dialogflow. but I keep getting errors when I execute my code.
I have created a class called DetectIntent with the code for DetectIntent provided by DialogFlow v2, and a REST api that receives messages from users and then I call the DetectIntent class to understand what the user wants to say.
NOTE: I am behind a proxy of the company I work at.
import com.google.api.client.util.Maps;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.TextInput.Builder;
import java.util.List;
import java.util.Map;
/**
* DialogFlow API Detect Intent sample with text inputs.
*/
public class DetectIntent {
public static Map<String, QueryResult> detectIntentTexts(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
Map<String, QueryResult> queryResults = Maps.newHashMap();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
System.out.println("Session Path: " + session.toString());
// Detect intents for each text input
for (String text : texts) {
// Set the text (hello) and language code (en-US) for the query
TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
// Build the query with the TextInput
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
// Performs the detect intent request
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
// Display the query result
QueryResult queryResult = response.getQueryResult();
System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
queryResults.put(text, queryResult);
}
}
return queryResults;
}
}
#RestController
#RequestMapping("/api")
public class ConversationExchange {
public ConversationExchange()
{
}
// Receive Messages Web Hook
#PostMapping(path="/whatsapp/hook")
public void TwilioWebHook(#RequestParam Map<String, String> map) throws Exception {
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("- DATA : " + map );
System.out.println("- SMS ID : " + map.get("SmsSid").toString());
System.out.println("- SENDER : " + map.get("From").toString());
System.out.println("- RECEIVER : " + map.get("To").toString());
System.out.println("- MESSAGE : " + map.get("Body").toString());
System.out.println("- STATUS : " + map.get("SmsStatus").toString());
System.out.println("- MESSAGE SID : " + map.get("MessageSid").toString());
System.out.println("- Account SID : " + map.get("AccountSid").toString());
System.out.println("************************************************");
System.out.println("************************************************");
List<String> list = new ArrayList<String>(Arrays.asList(map.get("Body").split(" ")));
// Detect Intent From Message
String session = UUID.randomUUID().toString();
DetectIntent detectIntent = new DetectIntent();
String response = detectIntentTexts("agent...", list, session,"fr-FR").toString();
System.out.println("----> INTENT DETECTED : " + response );
// SEND RESPONSE
}
}
I excepted to get the intent detected but what I get multiple errors in the console.
i.g.n.s.io.grpc.netty.GrpcSslContexts : Conscrypt class not found. Not using Conscrypt
i.g.n.s.i.n.u.i.NativeLibraryLoader : Unable to load the library 'io_grpc_netty_shaded_netty_tcnative_windows_x86_64', trying other loading mechanism.
i.g.n.s.i.n.u.i.NativeLibraryLoader : io_grpc_netty_shaded_netty_tcnative_windows_x86_64 cannot be loaded from java.libary.path, now trying export to -Dio.netty.native.workdir:..
Couldn't load full implementation for TagsComponent, now trying to load lite implementation.
io.opencensus.tags.Tags : Couldn't load lite implementation for TagsComponent, now using default implementation for TagsComponent.
io.opencensus.stats.Stats : Couldn't load full implementation for StatsComponent, now trying to load lite implementation.
io.opencensus.stats.Stats : Couldn't load lite implementation for StatsComponent, now using default implementation for StatsComponent.
io.opencensus.trace.Tracing : Couldn't load full implementation for TraceComponent, now trying to load lite implementation.
io.opencensus.trace.Tracing : Couldn't load lite implementation for TraceComponent, now using default implementation for TraceComponent.
io.grpc.Context : Storage override doesn't exist. Using default
Fixed it, the issue was the proxy, I had to set system variables to support the proxy.
I am working on Restlet tutorial example concerning coarse-grained authorization:
public class MyApiWithRoleAuthorization extends Application {
//Define role names
public static final String ROLE_USER = "user";
public static final String ROLE_OWNER = "owner";
#Override
public Restlet createInboundRoot() {
//Create the authenticator, the authorizer and the router that will be protected
ChallengeAuthenticator authenticator = createAuthenticator();
RoleAuthorizer authorizer = createRoleAuthorizer();
Router router = createRouter();
Router baseRouter = new Router(getContext());
//Protect the resource by enforcing authentication then authorization
authorizer.setNext(Resource0.class);
authenticator.setNext(baseRouter);
//Protect only the private resources with authorizer
//You could use several different authorizers to authorize different roles
baseRouter.attach("/resourceTypePrivate", authorizer);
baseRouter.attach("/resourceTypePublic", router);
return authenticator;
}
private ChallengeAuthenticator createAuthenticator() {
ChallengeAuthenticator guard = new ChallengeAuthenticator(
getContext(), ChallengeScheme.HTTP_BASIC, "realm");
//Create in-memory users with roles
MemoryRealm realm = new MemoryRealm();
User user = new User("user", "user");
realm.getUsers().add(user);
realm.map(user, Role.get(this, ROLE_USER));
User owner = new User("owner", "owner");
realm.getUsers().add(owner);
realm.map(owner, Role.get(this, ROLE_OWNER));
//Attach verifier to check authentication and enroler to determine roles
guard.setVerifier(realm.getVerifier());
guard.setEnroler(realm.getEnroler());
return guard;
}
private RoleAuthorizer createRoleAuthorizer() {
//Authorize owners and forbid users on roleAuth's children
RoleAuthorizer roleAuth = new RoleAuthorizer();
roleAuth.getAuthorizedRoles().add(Role.get(this, ROLE_OWNER));
roleAuth.getForbiddenRoles().add(Role.get(this, ROLE_USER));
return roleAuth;
}
private Router createRouter() {
//Attach Server Resources to given URL
Router router = new Router(getContext());
router.attach("/resource1/", Resource1.class);
router.attach("/resource2/", Resource2.class);
return router;
}
public static void main(String[] args) throws Exception {
//Attach application to http://localhost:9000/v1
Component c = new Component();
c.getServers().add(Protocol.HTTP, 9000);
c.getDefaultHost().attach("/v1", new MyApiWithRoleAuthorization());
c.start();
}
}
I create a class for checking user credentials:
public class Resource1 extends ServerResource{
#Get
public String represent() throws Exception {
User user = getRequest().getClientInfo().getUser();
String identifier = user.getIdentifier();
char[] pass = user.getSecret();
return this.getClass().getSimpleName() + " found ! User: " + identifier +
"; password = " + charArrayToString(pass) ;
}
private String charArrayToString(char[] chars ) {
String result = "";
for (char c : chars){
result += c;
}
return result;
}
}
When I go to resource http://localhost:9000/v1/resourceTypePublic/resource1/ the application asks for credentials and I input "user", "user" (or "owner", "owner"). But I get internal server error. The reason is that variable pass in return statement
return this.getClass().getSimpleName() + " found ! User: " + identifier +
"; password = " + charArrayToString(pass) ;
has null value. The statement without this variable works ok:
return this.getClass().getSimpleName() + " found ! User: " + identifier;
and returns user login. But what about the secret? Why it returns null value despite the user secret had been inputted?
User object created with statement
User user = getRequest().getClientInfo().getUser();
does not contain information about password despite it has a field secret. There is another way to get user credentials:
char[] pass = getChallengeResponse().getSecret();
I have tried to write a little code using libGDX to work with network. Here's a code:
public class Test {
public static void main(String[] args) {
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
If I write this URL in browser, it works right. It means, that the problem on my side. How to fix it?
Summary of values of the object which causes NullPointerException:
You are writing this code in the static main entry point of your program. Your Gdx is not yet loaded,so Gdx is still null at this point.
Create a none static class and put your code in it's constructor and initialize that class within this static entry point.
public class WebTest()
{
public WebTest()
{
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
}
public class Test {
public static void main(String[] args) {
new WebTest();
}
}