How to send push notification by serverside using jUnit testing - java

I am using this code for sending push notification in Android devices. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ Its work. But they are using php in server side. and My Server side is JAVA. so I am trying to create jUnit testing for that. so my server will send push notification. But i have not idea about that. I tried by post method but did not work. getting 401 error.
String regID = "";
pairs.add(new BasicNameValuePair("registration_ids",regID));
pairs.add(new BasicNameValuePair("data","test"));
pairs.add(new BasicNameValuePair("key","my key"));
String url = "https://android.googleapis.com/gcm/send";
String data = makePostCall(url, pairs);
Please suggest to me in jUnit.

I was passing incorrect params. It should be header and body. This is way which I used and working nice.
public class SendPushNotification {
public static void main(String[] arg){
PushNotification pushNoti = new PushNotification();
//collect the device_tokens into JSONArray.
// device_tokens is the tokens of user where we needs to send the push Messages.
String id = "APA9******WVWA";
JSONArray deviceTokenArray = new JSONArray();
// if you want to send more than one device then you have to
// add more ids into JSONArray by using put method.
deviceTokenArray.put(id);
try {
pushNoti.sentPushIntoAndroid(deviceTokenArray, "I Love to my sister and sending a push message in Android Device");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and that is another class which is using HTTPHeader and HTTPBody.
public class PushNotification {
public void sentPushIntoAndroid(JSONArray device_token, String message)
throws JSONException {
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
StringEntity stringentity = new StringEntity(generateJSONBodyForHTTPBody(device_token, message).toString(), "UTF-8");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("Authorization", "key=AI**********Mo"");
httppost.setEntity(stringentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
displayLog("HTTP Response ", strresponse);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private JSONObject generateJSONBodyForHTTPBody(JSONArray device_token, String message) throws JSONException {
JSONObject jObj = new JSONObject();
jObj.put(CommonUtilities.REGISTRATION_ID, device_token);
JSONObject dataJson = new JSONObject();
//NOTE:- In Client side, you have to retrieve below param by using getBundle().getString("id") like it. so it will retrieve the id and do for other params too like as i did for id.
dataJson.put("id", "testingID");
dataJson.put("type", "testingType");
dataJson.put("imglink", "testingimgLink");
dataJson.put("seolink", "testingseoLink");
dataJson.put("msg", "Lata Bhulli");
jObj.put("data", dataJson);
displayLog("JSONObject", jObj.toString());
return jObj;
}
private void displayLog(String tag, String message) {
System.out.println(tag+" "+message);
}
Note:- If you are getting compile error than you have to use latest HTTP Libraries and used in libs folder then add all in build path.

Related

How can i create user in salesforce through REST api? Give me some examples

Am trying to create user into my salesforce account through REST api using java.But its returning 400 status code.Can you please guide me?
Here is the code am trying:
public static void createUsers() {
System.out.println("\n_______________ USER INSERT _______________");
String uri = baseUri + "/sobjects/User/";
System.out.println(uri);
try {
//create the JSON object containing the new lead details.
JSONObject lead = new JSONObject();
lead.put("FirstName", "Jake");
lead.put("LastName", "sully");
lead.put("Alias", "Jake");
lead.put("Email", "Jake#gmail.com");
lead.put("Username", "Jake#gmail.com");
lead.put("Name", "jake");
lead.put("UserRoleId","00E28000000oD8EEAU");
lead.put("Id", "10028000000GLSIAA4");
lead.put("EmailEncodingKey", "ISO-8859-1");
lead.put("TimeZoneSidKey", "Asia/Kolkata");
lead.put("LocaleSidKey", "en_US");
lead.put("ProfileId", "00e280000027hnGAAQ");
lead.put("LanguageLocaleKey", "en_US");
//Construct the objects needed for the request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
System.out.println(response.toString());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved lead id to use when we update the lead.
leadId = json.getString("id");
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}

Android send json to Spring

Spring Controller
#RequestMapping(value = "/login", produces="application/json;charset=UTF-8" ,method = RequestMethod.POST)
#ResponseBody
public int checkLoginInfo(#RequestParam Map<String, String> params) {
User user=new Gson().fromJson((String) params.get("user"), User.class);
return userService.getUserInfo(user);
}
HTML
var params={userid:$("#userid").val(),password:$("#password").val()}
$ajax({method:"post",data:{user:JSON.stringify(params)},url:"foo.bar"});
It worked on website.
But I don't know how to send that Json object for android.
data:{user:JSON.stringify(params)}
I have tested
private static String makeJsonMsg() {
String retMsg = "";
JSONStringer jsonStringer = new JSONStringer();
try {
retMsg = jsonStringer.object()
.key("user").object()
.key("userid").value("userid")
.key("password").value("1234")
.endObject()
.endObject().toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retMsg;
}
like that,
But return 500 error.
Do I need to add header or something else?
The simple way
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
How to use
JSONObject requestObject = new JSONObject();
requestObject.put("userid", email);
requestObject.put("password", password);
postData("http://your/login/url",requestObject)
For more info check How to send a JSON object over Request with Android?. Credit of the postData method is for #Sachin Gurnani answer
Hope this helps!!

Passing data between android and server using JSON parsing

I'm trying to send and receive data between android app and server using JSON but unfortunately i am unable to do it i searched a lot but it didn't help. My code is as follows:
In android
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("fromDate", from);
jsonObject.put("toDate", to);
jsonObject.put("reason", reas);
new SendData().execute(jsonObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and then my asynctask's doInBackground method
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
CmsInter.TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CmsInter.TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(getResources().getString(
R.string.URL));
StringEntity se = new StringEntity(object.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
message = Sync.convertResponseToString(response);
} catch (Exception e) {
e.printStackTrace();
message = e.toString();
}
and then on server side within the doPost() method of servlet code is as follows :
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
sb.append(line);
} catch (Exception e) { /* report an error */
e.printStackTrace();
}
String str = sb.toString();
try {
org.json.JSONObject json = new org.json.JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and I think this is not the right way to read JSONObject on the server side because when I run this I get org.json.JSONException: A JSONObject text must begin with '{' at character 1 exception , Can anyone please help me out in this. Any help will be appreciated. Thanks.
Finally got it this line was wrong object.toString() while sending it should have been object[0].toString() because asynctask's doInBackground methods parameter is an array i.e. protected String doInBackground(JSONObject... object).

Android: Uploading Strings To Server

I'm trying to let my users be able to report small errors my android application automatically catches to my server. It's nothing big, just a small text box and send button.
It's supposed to send 3 strings (error, optional user description, and time) to a file on my website made specifically to capture those errors. The thing is, I have absolutely no idea how to do so. I only know how to let my application read info from my website but not the other way around.
Do I have to have a special script on my website? Are JSON Strings necessary? I need the string to be saved there. (Not temporarily)
I'm a bit of a newbie so any help is appreciated. Thanks!
- There has to be a script running on your server, eg: php script.
- Its actually a web-service published on the server so that a client can access it.
- Then you will need to do a HTTP Post to the Server, its better to use NameValuePair along with it to send the data.
This is my code for doing HTTP POST:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now", sb + "");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method " + sb.toString());
return sb.toString();
}
//////////////////////////// Edited Part ///////////////////////////////////
Server side php code:
<?php
require_once(ROOT.'/lab/lib/xyz_api_int.php');
try {
//setup the sdk
$api = YumzingApiInt::_get(
Config::get('api_int','url'),
Config::get('api_int','key'),
Config::get('api_int','secret')
);
//connect to the api
$api->connect();
//check our token
echo $api->getToken();
} catch(Exception $e){
sysError($e->getMessage());
}
You just need to post values by http to a php script on your server that will save those values in your file or a database.

Not getting JSON value in Spring Controller method

I need to send some data from my Android device to my server. I am doing this through JSON. I have implemented the JSON post on Android, and I am trying to do a mapping on the server side in order to retrieve that data. My problem is that I keep getting an empty string.
Android method used to send JSON:
private void sendJson(final String json, final String URL) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
try{
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
client.execute(post);
}
catch(Exception e){
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Server-side method:
#RequestMapping(value = "/getLatestCalls", method = RequestMethod.POST)
public void getData(#ModelAttribute String json){
//... do something
}
The thing is that in this method my json String is "" every time. I have also tried using #RequestParam but with that it doesn't enter the method anymore. I have also tried with #ModelAttribute("json").
Can someone enlighten me a little here? Thank you in advance.
Here is the solution and it works fine.
server-side
#Controller
public class DataCollector {
#RequestMapping(value = "/clientdatacollector", method = RequestMethod.POST)
public #ResponseBody
void abc(Writer writer, #RequestParam("gpsdata") String gpsJSON) {
try {
// here is your jsonstring ;)
writer.write(gpsJSON.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
client-side
public static void httptest() {
ArrayList<TravellingData> tdArray = new ArrayList<TravellingData>();
Gson gson = new Gson();
String jsonString = "";
for (int i = 0; i < 1; i++) {
tdArray.add(ObjectCreater.createMockTravellingDataObject());
}
jsonString = gson.toJson(tdArray);
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
try {
post = new HttpPost(
"http://localhost:8080/uygulama/clientdatacollector");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("gpsdata", jsonString));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = null;
try {
response = client.execute(post);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try using #RequestBody. It should work.

Categories