I'm trying to send messages to single devices using their token from a Java application. I'm using the Firebase Admin SDK. Below is what I have
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream("google-services.json");
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://MYPROJECTID.firebaseio.com/")
.build();
} catch (IOException e1) {
e1.printStackTrace();
}
FirebaseApp.initializeApp(options);
String registrationToken = "MYDEVICETOKEN";
// See documentation on defining a message payload.
Message message = Message.builder().putData("time", "2:45").setToken(registrationToken)
.build();
// Send a message to the device corresponding to the provided
// registration token.
String response = null;
try {
response = FirebaseMessaging.getInstance().sendAsync(message).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
But I get the following exception
java.io.IOException: Error reading credentials from stream, 'type' field not specified.
What am I doing wrong here?
Click on Generate new private key button.
The error means that your google-services.json file contains invalid data. GoogleCredentials class expects your file to have a type property, but it's not there.
Brief googling gave me this post regarding very similar problem. It says:
From the API Manager, just create select "Create credentials" >
"Service Account key" and generate a new key for the Service
that is associated to your Google Play account.
Related
I am implementing "Login with Microsoft button" and I need to store the refresh token in my database so that I can use that to obtain new access tokens in future. I am trying to do this with Java sdk for microsoft graph.
Edit 1: I actually want to create calendar events using my web application. So, the goal is for the web app to access Graph API without having a signed in user present.
This is what the code looks like:
AuthorizationCode authorizationCode = new AuthorizationCode(httpServletRequest.getParameter("code"));
String currentUri = httpServletRequest.getRequestURL().toString();
IAuthenticationResult result;
ConfidentialClientApplication app;
try {
app = createClientApplication();
String authCode = authorizationCode.getValue();
Set<String> scopes = new HashSet<String>();
scopes.add("Calendars.ReadWrite");
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(authCode, new URI(currentUri)).scopes(scopes)
.build();
Future<IAuthenticationResult> future = app.acquireToken(parameters);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
String accessToken = result.accessToken();
/*
IAuthenticationResult does not contain any method to get the refresh token - how do I get the refresh token??
I want to do something like: result.refreshToken();
*/
IAuthenticationResult is implemented by AuthenticationResult -- but, AuthenticationResult is declared in another class and is not public. AuthenticationResult exposes a method to obtain refreshToken but, I am not able to access it.
Can someone help me access the refresh token?
Thanks!
I got the answer from this link: https://github.com/AzureAD/microsoft-authentication-library-for-java/issues/228
Short Answer: Use reflection
try {
//see com.microsoft.aad.msal4j.AuthenticationResult#refreshToken
final Field refreshTokenField = result.getClass()
.getDeclaredField("refreshToken");
refreshTokenField.setAccessible(true);
return refreshTokenField.get(result).toString();
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
Following their guide in usage here I couldn't get started.
The code:
KucoinClientBuilder builder = new KucoinClientBuilder()
.withApiKeyVersion(2)
.withBaseUrl("https://openapi-sandbox.kucoin.com")
.withApiKey("MyKey", "MySecret", "MyPass");
KucoinRestClient kucoinRestClient = builder.buildRestClient();
KucoinPrivateWSClient kucoinPrivateWSClient;
try {
kucoinPrivateWSClient = builder.buildPrivateWSClient();
KucoinPublicWSClient kucoinPublicWSClient = builder.buildPublicWSClient();
} catch (IOException e) {
e.printStackTrace();
}
builder.buildPrivateWSClient() throws an exception with this message:
KucoinApiException{code='400003', message='KC-API-KEY not exists'}
I copied the Api Key and Secret and pass from the api page
What am I missing here? Why the KC-API-KEY does not exist?
The "sandbox" account is different than the original account.
Its domain is different and you need to register in the sandbox version of the website here
I have created an agent on api.ai and it is working well. Now I want to pass text queries to the agent from a java project and get response from it. Any help?
This worked for me on my android project.
final AIConfiguration config = new
AIConfiguration("your key",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
AIRequest request = new AIRequest("your text request");
AIService aiService = AIService.getService("implement new AIService", config);
try {
aiService.textRequest(request);
} catch (AIServiceException e) {
e.printStackTrace();
}
I am using Paho java client library for my on android App. Code provided below.
MqttAndroidClient client_Panic = new MqttAndroidClient(this.getApplicationContext(), serverURL, CLIENT_ID);
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
options.setCleanSession(false);
options.setKeepAliveInterval(90);
options.setConnectionTimeout(100);
IMqttToken token = client_Panic.connect(options);
//Few callbacks
} catch (MqttException e) {
e.printStackTrace();
}
And publishing messages, when required
String msg = "messages";
MqttMessage message = new MqttMessage();
message.setPayload(msg.getBytes());
try {
client_Panic.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
It is working fine, but somehow incomplete. What I need is, whenever other client subscribed to same topic, should get the last retained message, which publisher might had published earlier.
For that I searched on their documentation, I got
protected void setWill(String topic,
MqttMessage msg,
int qos,
boolean retained)
So setWill as per documentation have the option to enable the retained option. So I tried with
options.setConnectionTimeout(100);
options.setWill(topic,null,2,true); // This place I added
IMqttToken token = client_Panic.connect(options);
But got error java.lang.IllegalArgumentException at org.eclipse.paho.client.mqttv3.MqttConnectOptions.validateWill on the line containing options.setWill.
Is setWill is the correct method for enabling retained true on android, if yes then what parameters need to be provided or else their is any other method for enabling it on android? TIA.
The Will is a very specific message that is only published if the client disconnects uncleanly from the broker (e.g. network drops).
You can not set a null message as the Will message which is what the error is about.
The retained state is specific to a given message so you do not set it globally, it is set on each message. To mark a message as retained when you just call the setRetained(boolean) e.g.
String msg = "messages";
MqttMessage message = new MqttMessage();
message.setRetained(true);
message.setPayload(msg.getBytes());
try {
client_Panic.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
Can someone please explain me how to access the protected web api using a web app client?
I am trying something mentioned here in the following link. But I am always getting
The provided access grant is invalid or malformed.
https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
Here is the code i am using for java
AuthenticationResult result = null;
try {
final Future<AuthenticationResult> resultFuture = context.acquireTokenByAuthorizationCode(
code, new URI(redirectUri), new ClientCredential(clientId, clientSecret), RESOURCE_GRAPH_API, null);
result = resultFuture.get();
} catch (InterruptedException | ExecutionException e) {
LOG.info("Failed to obtain access token: " + e.getMessage());
} catch (URISyntaxException e) {
}