Android notification push empty using GCM and java with json message - java

I'm struggling to push notifications to Android devices.
Here is a small piece of code I wrote:
String API_KEY = "AIzaSy....";
String url = "https://android.googleapis.com/gcm/send";
String to = "ce0kUrW...";
String data = "{\"to\": \"" + to + "\"}";
RequestBody body = RequestBody.create(MediaType.parse("application/json"), data);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).post(body).addHeader("Authorization", "key=" + API_KEY).build();
Response response = client.newCall(request).execute();
System.out.println(response.headers());
System.out.println(response.body().string());
Looking at https://developers.google.com/cloud-messaging/http#send-to-sync, it works fine when I try the send-to-sync option. I get a notification sound on my phone, but there is no actual notification, since there is no message or data linked to the push.
Now when I replace my data String with the following line, I still get the same result:
String data = "{ \"notification\": {\"title\": \"Test title\", \"text\": \"Hi, this is a test\"},\"to\" : \""
+ to + "\"}";
I'm not sure what I'm missing. My guess is that my format of the notification is wrong, but I've tried every combination that I've found so far during my research.
They writes to the log looks like this:
Content-Type: application/json; charset=UTF-8
Date: Thu, 21 Apr 2016 10:51:23 GMT
Expires: Thu, 21 Apr 2016 10:51:23 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alternate-Protocol: 443:quic
Alt-Svc: quic=":443"; ma=2592000; v="32,31,30,29,28,27,26,25"
Transfer-Encoding: chunked
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1461235877551
OkHttp-Received-Millis: 1461235877855
{"multicast_id":6596853786874127657,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1461235883968556%6ff215a7f9fd7ecd"}]}

The log entry indicates that your message was processed successfully. However for the notification with payload option you should send a JSON message like this:
{
"to" : "<your-recipient-id>",
"notification" : {
"body" : "Hi, this is a test",
"title" : "My test"
}
}
Please change as suggested and let us know if this helps.
You can check the Messaging Concepts and Options on Developer Guides - the guide provides some useful examples.
Maybe as an example - this is how you can handle the notifications.
In your app's onMessageReceived() you process it by retrieving the notification payload using notification as a key. For example:
public void onMessageReceived(String from, Bundle data) {
String notificationJSONString = data.getString("notification");
//then you can parse the notificationJSONString into a JSON object
JSONObject notificationJSON = new JSONObject(notificationJSONString );
String body = notificationJSON.getString("body");
Log.d(TAG, "Notification Message is : " + body);
}

Related

send an email using hotmail access token in java

I am trying to send an email using hotmail authorization access token on java env. , I have seen the documentation, but still unable to send an email successfully , here is my code :
private String doPostRequest(String accessToken) throws IOException {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String url = "https://outlook.office.com/api/v2.0/me/sendmail";
String json = "{"+
"'Message': {"+
"'Subject': 'Meet for lunch?',"+
"'Body': {"+
"'ContentType': 'Text',"+
"'Content': 'The new cafeteria is open.'"+
"},"+
"'ToRecipients': [{"+
"'EmailAddress': {"+
"'Address': 'mymail#gmail.com'"+
"}"+
"}"+
"],"+
"'Attachments': [{"+
"'#odata.type': '#Microsoft.OutlookServices.FileAttachment',"+
"'Name': 'menu.txt',"+
"'ContentBytes': 'bWFjIGFuZCBjaGVlc2UgdG9kYXk='"+
"}"+
"]"+
"},"+
"'SaveToSentItems': 'false'"+
"}";
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().header("User-Agent", "java-tutorial").header("client-request-id", UUID.randomUUID().toString())
.header("return-client-request-id", "true").header("Authorization", String.format("Bearer %s", accessToken)).url(url).post(body).build();
Response response = client.newCall(request).execute();
System.out.println("response :"+response);
System.out.println("responseHeader :"+response.headers());
System.out.println("responseMessage :"+response.message());
return response.body().string();
}
and here is what I get on the console :
response :Response{protocol=http/1.1, code=401, message=Unauthorized, url=https://outlook.office.com/api/v2.0/me/sendmail}
responseHeader :Set-Cookie: exchangecookie=520b1dfb18d54248ba3bca9becf3a40d; expires=Mon, 29-Oct-2018 08:51:24 GMT; path=/; HttpOnly
WWW-Authenticate: Bearer client_id="00000002-0000-0ff1-ce00-000000000000", trusted_issuers="00000001-0000-0000-c000-000000000000#*", token_types="app_asserted_user_v1 service_asserted_app_v1", authorization_uri="https://login.windows.net/common/oauth2/authorize", error="invalid_token",Basic Realm="",Basic Realm="",Basic Realm=""
request-id: 7d7030b8-c31f-4572-9c18-6a2fce3609a0
client-request-id: 66b1e177-5030-4c0e-892a-7ad276351daf
X-CalculatedFETarget: AM5P190CU001.internal.outlook.com
X-BackEndHttpStatus: 401
X-FEProxyInfo: AM5P190CA0028.EURP190.PROD.OUTLOOK.COM
X-CalculatedBETarget: AM4PR05MB1906.eurprd05.prod.outlook.com
X-BackEndHttpStatus: 401
x-ms-diagnostics: 2000010;reason="ErrorCode: 'PP_E_RPS_CERT_NOT_FOUND'. Message: 'Certificate cannot be found. Certificate required for the operation cannot be found.%0d%0a Internal error: spRPSTicket->ProcessToken failed. Failed to call CRPSDataCryptImpl::UnpackData:Certificate cannot be found. Certificate required for the operation cannot be found.%0d%0a Internal error: Failed to decrypt data. :Failed to get session key. RecipientId=293577. spCache->GetCacheItem returns error.:Cert Name: (null). SKI: ee9f500e98bf0fbc492f0b138028374ec9324da4...'";error_category="invalid_msa_ticket"
X-DiagInfo: AM4PR05MB1906
X-BEServer: AM4PR05MB1906
X-FEServer: AM5P190CA0028
X-Powered-By: ASP.NET
X-FEServer: AM4PR05CA0019
X-MSEdge-Ref: Ref A: 9F523827F0CE47DEB84ECF96913B53AE Ref B: AMS04EDGE0320 Ref C: 2017-10-29T08:51:25Z
Date: Sun, 29 Oct 2017 08:51:24 GMT
Content-Length: 0
OkHttp-Sent-Millis: 1509267094755
OkHttp-Received-Millis: 1509267094903
responseMessage :Unauthorized
Note that the authorization token is correct and looks something similar to :
EwAwA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAYDt8KR/8o7V7P+9ynPu97AHv8CIiJA/Zn+...
And it is the same one used to get the emails on inbox folder and show them to the user as what this tutorial describes .
Also I didn't forget to add the correct scopes for the api to be able to send mail "Mail.Send" .
I need to find a way to send the email successfully using authentication token , please help .
I have found a solution , looks like I need to change the url since I was calling the wrong one according to this documentation , my code now looks
public void tryingOkHttpClientPostt(String accessToken) {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://graph.microsoft.com/v1.0/me/sendMail").newBuilder();
String json = "{" + "'Message': {" + "'Subject': 'Meet for lunch?'," + "'Body': {" + "'ContentType': 'Text',"
+ "'Content': 'The new cafeteria is open.'" + "}," + "'ToRecipients': [{" + "'EmailAddress': {" + "'Address': 'myMail#gmail.com'" + "}" + "}"
+ "]," + "'Attachments': [{" + "'#odata.type': '#Microsoft.OutlookServices.FileAttachment'," + "'Name': 'menu.txt',"
+ "'ContentBytes': 'bWFjIGFuZCBjaGVlc2UgdG9kYXk='" + "}" + "]" + "}," + "'SaveToSentItems': 'false'" + "}";
RequestBody body = RequestBody.create(JSON, json);
String url = urlBuilder.build().toString();
Request request = new Request.Builder().header("Content-Type", "application/json")
.header("Authorization", String.format("Bearer %s", accessToken)).method("POST", body).url(url).build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}

Why is Jersey Client response giving garbage data?

I cannot figure out why my code is giving me garbage data when I read the Http Response entity. This is only happening when I issue a request to one specific URL with data that causes a 400 response. My code attempts to read the response entity, but as you can see below it is garbage.
Here is a simplified test case:
import org.junit.Test;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
public class Sandbox {
#Test
public void jaguarTestCase() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://www.jaguarusa.com/owners/vin-recall.html?view=vinRecallQuery&vin=xxxxxxxxxxxxxxxxx");
Invocation.Builder builder = target.request();
Response response = builder.get(Response.class);
System.out.println("Response Code:");
System.out.println("\t" + response.getStatus() + " - " + response.getStatusInfo().getReasonPhrase());
System.out.println("\nResponse Headers:");
for (Map.Entry<String, List<String>> entry : response.getStringHeaders().entrySet()) {
System.out.print("\t" + entry.getKey() + ": ");
for (String value : entry.getValue()) {
System.out.println(value);
}
}
String responseEntity = response.readEntity(String.class);
System.out.println("\nResponse Entity: ");
System.out.println(responseEntity);
}
}
And the output from that testcase:
Response Code:
400 - Bad Request
Response Headers:
X-Frame-Options: SAMEORIGIN
Cache-Control: no-cache, no-store, must-revalidate
Server: Apache-Coyote/1.1
Connection: keep-alive
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Length: 135
Date: Tue, 08 Nov 2016 00:03:23 GMT
Content-Language: en-US
Content-Type: application/json;charset=UTF-8
Response Entity:
� \�1
�#E��:H
���B��C2����X�wנ��z�{%1�vw��:ga�����4$ ������k�Q�-i�����y��T��!f��� c� ��iK-��?z� ���dW��
This is what the entity body is supposed to be (paste the URL in any browser and see for yourself):
{
"errorMessage" : "Please check your details and try again.",
"error" : 400,
"errorTitle" : "Sorry, that is not a valid VIN.",
"vin" : "XXXXXXXXXXXXXXXXX"
}
I am using the JDK version 1.8.0_102. I think the problem is happening when the response entity is parsed because the reported content-length of 135 is the correct value, confirmed by running this request in a Chrome browser debug window.
The Content-Type response header shows charset=UTF-8, which is what my JVM is running as. What gives? I'm completely stumped after working on this all afternoon.
If you inspect your response headers, you will notice
Content-Encoding: gzip
The garbled text is actually zipped.
You can uncompress that response.
WebTarget target = ...
target.register(GZipEncoder.class);
After this change, the readEntity thing you are doing should work fine.
This works in Jersey 2.26.
For earlier versions, the solutions are slightly different. Refer to https://stackoverflow.com/a/7574663/2695332

How to add headers of HTTP request to response

Sorry if the question is possibly repeated. I'm not familiar with Java and I'm stuck with a Cordova plugin which returns headers in a non-JSON structure which I think is Map.soString() presentation of request.headers()
//These parts works fine returning response body
HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupSecurity(request);
request.headers(this.getHeaders());
request.acceptJson();
request.contentType(HttpRequest.CONTENT_TYPE_JSON);
request.send(getJsonObject().toString());
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
response.put("status", code);
// in this line I must put JSON converted headers instead of request.headers()
response.put("headers", request.headers());
I've tried
String headers = request.headers().toString();
and
JSONObject headers = new JSONObject(request.headers());
to change the aforementioned line to
response.put("headers", headers);
but none of them worked.
How should I send headers as JSON in response?
More context:
Currently the response headers are:
{
null=[HTTP/1.0 200 OK],
Content-Type=[application/json],
Date=[Mon, 25 Jan 2016 07:47:31 GMT],
Server=[WSGIServer/0.1 Python/2.7.6],
Set-Cookie=[csrftoken=tehrIvP7gXzfY3F9CWrjbLXb2uGdwACn; expires=Mon, 23-Jan-2017 07:47:31 GMT; Max-Age=31449600; Path=/, sessionid=iuza9r2wm3zbn07aa2mltbv247ipwfbs; expires=Mon, 08-Feb-2016 07:47:31 GMT; httponly; Max-Age=1209600; Path=/],
Vary=[Accept, Cookie],
X-Android-Received-Millis=[1453708294595],
X-Android-Sent-Millis=[1453708294184], X-Frame-Options=[SAMEORIGIN]
}
and are sent in body of response. so I need to parse them, but I can't do.
This should be the way to do it:
JSONObject headers = new JSONObject(request.headers());
However, the "toString()" display of the headers seem to be showing a map entry with a null key. That won't work in JSON: an JSON object attribute name cannot be null. My guess is that the null key caused the crash.
So I think you need to filter out the "bad" entry; i.e. code it something like this:
JSONObject headers = new JSONObject()
for (Map.Entry entry: request.headers().entries()) {
if (entry.getKey() != null) {
headers.put(entry.getKey(), entry.getValue());
}
}

Using Jersey to get a CSRF token through REST and use it in a login

Using Jersey 2.19, How do I get a CSRF token from a server which uses Spring Security 3 and make a successful login? I have two projects, a client which uses REST, and a server which was created using JHipster.
First, I'm making a get request to http://localhost:8080 and I'm getting this response headers:
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Language:en
Content-Length:17229
Content-Type:text/html;charset=utf-8
Date:Tue, 21 Jul 2015 19:24:40 GMT
Expires:0
Last-Modified:Thu, 02 Jul 2015 17:07:31 GMT
Pragma:no-cache
Server:Apache-Coyote/1.1
Set-Cookie:CSRF-TOKEN=0902449b-bac7-43e8-bf24-9ec2c1faa48b; Path=/
X-Application-Context:application:dev:8081
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
I extract the Set-Cookie header and I get the CSRF token from there. Then I'm making a post request this way:
http://localhost:8080/api/authentication?j_username=user&j_password=user&submit=Login
With this request headers:
Content-Type: application/x-www-form-urlencoded
X-CSRF-TOKEN: <extracted token>
Using Chrome's plugin postman, I can make a correct post request for login, but with Jersey, I'm unable to send correctly the CSRF token (I get 403 response).
This is the response:
{"timestamp":1437507680089,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/api/authentication"}
This is the jersey code:
WebTarget hostTarget = getClient().target("http://localhost:8080");
Response r = hostTarget.request().get();
String header = r.getHeaderString("Set-Cookie");
String csrf = null;
List<HttpCookie> cookies = HttpCookie.parse(header);
for (HttpCookie c : cookies) {
if("CSRF-TOKEN".equals(c.getName())){
csrf = c.getValue();
break;
}
}
WebTarget loginTarget = hostTarget.path("/api/authentication");
loginTarget = loginTarget.queryParam("j_username", username)
.queryParam("j_password", password)
.queryParam("submit", "Login");
Builder req = loginTarget.request(MediaType.APPLICATION_JSON_TYPE);
if (csrf != null) {
req = req.header("X-CSRF-TOKEN", csrf);
}
Response cr = req.post(Entity.entity(null,
MediaType.APPLICATION_FORM_URLENCODED_TYPE));
System.out.println("Response: " + cr.readEntity(String.class));
Thanks for your time.
After much trial and error, I found the solution. Is important to take in count cookies (as indicated by Roman Vottner) for REST configuration to communicate with spring security. The important cookie that must be present is JSESSIONID and the header X-CSRF-TOKEN (or whatever header name is configured in the server), so capture them in a initial request and send them again.
I've decided to send all the cookies to the server in this way.
WebTarget hostTarget = getClient().target("http://localhost:8080");
Response r = hostTarget.request().get();
String headerCookies = r.getHeaderString("Set-Cookie");
Map<String, NewCookie> cookies = r.getCookies();
String csrf = cookies.get("CSRF-TOKEN").getValue();
WebTarget loginTarget = hostTarget.path("/api/authentication");
loginTarget = loginTarget.queryParam("j_username", username)
.queryParam("j_password", password)
.queryParam("submit", "Login");
Builder req = loginTarget.request(MediaType.APPLICATION_JSON_TYPE);
req = req.header("Cookie", headerCookies);
if (csrf != null) {
req = req.header("X-CSRF-TOKEN", csrf);
}
Response cr = req.post(Entity.entity(null,
MediaType.APPLICATION_FORM_URLENCODED_TYPE));
//The response is empty (in my case) with status code 200
System.out.println("Response: " + cr.readEntity(String.class));

Why are my headers null after a POST?

I'll lay down my code first: Note: I also have log output at the bottom of the question.
Server Side:
#Post
#Consumes("application/octet-stream")
public Representation post(InputStream zip, #HeaderParam(value = "Content-Disposition") HttpHeaders headers) throws Throwable {
System.out.println(headers); //Prints null - want the header to not be null here
String uploadedFileLocation = getStartingDir() + "/" + "abc.zip";
writeToFile(zip, uploadedFileLocation);
return new StringRepresentation("Uploaded!");
}
Client Side:
public static void main(String[] args) throws Exception {
final String BASE_URI = "http://localhost:8080/server/upload";
Client client = Client.create();
WebResource service = client.resource(BASE_URI);
client.setChunkedEncodingSize(1024);
client.addFilter(new LoggingFilter());
File zip = new File("C:/Users/sdery/Desktop/abc.zip");
InputStream fileInStream = new FileInputStream(zip);
String sContentDisposition = "attachment; filename=\"" + zip.getName()+"\"";
ClientResponse response = service.header("Authorization", "Basic xxx=").header("Content-Disposition", (Object)sContentDisposition).type(MediaType.APPLICATION_OCTET_STREAM).post(ClientResponse.class, fileInStream);
System.out.println("Response Status : " + response.getEntity(String.class));
}
First off, the file transfer works, I'm happy. However, I would like to get the headers on the server side so I don't have to hard code the file name. Any ideas as to why it is comin' up null? Does it have to do with me using ClientResponse instead of ClientRequest?
Jul 31, 2013 8:44:12 AM com.sun.jersey.api.client.filter.LoggingFilter log
INFO: 1 * Client out-bound request
1 > POST http://localhost:8080/server/upload
1 > Content-Disposition: attachment; filename="abc.zip"
1 > Authorization: Basic xxx=
1 > Content-Type: application/octet-stream
(zip bytes)
INFO: 1 * Client in-bound response
1 < 200
1 < Date: Wed, 31 Jul 2013 12:44:12 GMT
1 < Date: Wed, 31 Jul 2013 12:44:12 GMT
1 < Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
1 < Content-Length: 88
1 < Set-Cookie: rememberMe=deleteMe; Path=/server; Max-Age=0; Expires=Tue, 30-Jul-2013 12:44:12 GMT
1 < Content-Type: text/plain; charset=UTF-8
1 < Accept-Ranges: bytes
1 < Server: Restlet-Framework/2.0.4
1 < Real-Token: bar
1 <
Uploaded!
From the log output, it seems that the header containing Content-Disposition is there. Does this mean I should be able to retrieve the value from the server side code?
You're parameter is of the wrong type. You should declare the parameter as a String. HttpHeaders is for getting all the headers and is annotated with a #Context. #HttpParam can only be converted to a limited number of types.
From the Jersey documentation for HeaderParam.
Binds the value(s) of a HTTP header to a resource method parameter, resource class field, or resource class bean property. A default value can be specified using the DefaultValue annotation. The type T of the annotated parameter, field or property must either:
Be a primitive type
Have a constructor that accepts a single String argument
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.
So you're code would be more like
#Post
#Consumes("application/octet-stream")
public Representation post(InputStream zip, #HeaderParam(value = "Content- Disposition") String contentDisposition) throws Throwable {
System.out.println(contentDisposition);
String uploadedFileLocation = getStartingDir() + "/" + "abc.zip";
writeToFile(zip, uploadedFileLocation);
return new StringRepresentation("Uploaded!");
}
First off, I apologize that my solution is from a JavaScript/PHP reference and not Java, but I believe your solution may be similar.
Add a new header named 'X-FILENAME' and set the name of your file as the header data. I believe your code would look something like this:
ClientResponse response = service.header("X-FILENAME", "abc.zip");
Then, on your server, you should be able to retrieve that header param (In PHP it is the $_SERVER global, it looks like in yours it may be #HeaderParam).
Also, for reference just in case this applies to you, in PHP when you retrieve the header param you need to use a modified param name by adding 'HTTP_' to the front and changing all dashes to underscores like this 'HTTP_X_FILENAME'. So on the client you sent 'X-FILENAME' while on the server you retrieve that same value with 'HTTP_X_FILENAME'.
I hope this leads you in the right direction.

Categories

Resources