Use Google volley api to send HTTP POST request of RDF data - rest

So, I have recently integrated the Volley API in my app in order to provide a Cloud storage solution (REST). Since, i have never used the API before i have some trouble trying to send RDF (text/turtle) data via HTTP POST. The REST server is working perfectly since I send GET and POST requests (via the Postman Chrome app) and every time i receive 200 and 201 responses. Although i managed to send a simple GET request via the API, i get a 400 error when i send an HTTP POST.
The code is the following:
//the RDF turtle payload to send over HTTP POST
final String bodyPost = "#prefix : <http://xxx.xxx.xxx.gr/xxx/schema/xxx#> ." + "\n" +
"#prefix xsd: <http://www.w3.org/2001/XMLSchema#> ." + "\n" +
"[a :Patient ;" + "\n" +
":lastName "+'"'+"Aylakiotis"+'"'+"^^xsd:string ; " + "\n" +
":firstName "+'"'+"Yiannis"+'"'+"^^xsd:string ;" + "\n" +
":dateOfBirth "+'"'+"1970-04-14"+'"'+"^^xsd:date ;" + "\n" +
":amka "+'"'+"12345678903"+'"'+"^^xsd:string ;" + "\n" +
":gender :Male ;" + "\n" +
"] .";
RequestQueue queue = Volley.newRequestQueue(this);
final String URL ="http://xxx.xxx.xxx:8080/xxx/";
EditText folderTitle = (EditText) findViewById(R.id.folderTitle);
StringRequest strReq = new StringRequest(Request.Method.POST, URL,
new Response.Listener() {
#Override
public void onResponse(Object response) {
folderTitle.setText("Response is: " + response.toString().substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
folderTitle.setText("Error: " + error.getMessage());
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
System.out.println("string post data: " + bodyPost);
if (params != null && params.size() > 0) {
System.out.println("string post data: " + bodyPost);
return encodeParameters(params, getParamsEncoding());
}
return bodyPost.getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String creds = String.format("%s:%s", "xxx", "xxx");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
headers.put("Content-Type", "text/turtle");
return headers;
}
};
// Add the request to the RequestQueue.
queue.add(strReq);
String bodyPost is the data payload i want to send in a turtle RDF format. I am putting this in my getBody() method, however i still get a 400 bad request. I have already sent this String via POST http through the Postman Chrome app and it works (201 Created). I saw that most implementations had getParams() but this requires key/value pairs whereas i am using triples that i want to send as a whole string of raw data

Set your Content-type to text/turtle. Override your request header like this:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final HashMap<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "text/turtle");
return params;
}

Related

How to display error message in multi file uploading with Rest webservices

Hi am in way of uploading multiple files into aws bucket using spring mvc and rest web services.
The positive scenario is working like if I select more one file its saved in aws bucket and am getting 200 here
String json1 = handler.handleResponse(response1);
System.out.println(json1);
My question is I have selected three files called x ,y and z as usual way the first file gets saved into bucket due to some issue y and z files failed to save how to inform the user that y and z are not saved into bucket
#PostMapping("/upload")
public String handleFileUpload(#RequestParam("specifications") MultipartFile[] specifications,
HttpServletRequest request,HttpSession session,final RedirectAttributes redirectAttributes) throws Exception {
for (int i = 0; i < specifications.length; i++) {
MultipartFile file = specifications[i];
String path = "Specification/";
String bucketName="BUcket/";
String inJson = "{\"filename\":\"" + file.getOriginalFilename() + "\",\"bucketname\":\""+ bucketName + "\",\"path\":\""+ path + "\"}";
addLogo(file, inJson);
}
code upload file
public void addLogo(MultipartFile file ,String inJson) throws IOException
{
String message="";
byte[] bytes = file.getBytes();
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(fileUploadURL);
HttpEntity entity = MultipartEntityBuilder.create().addTextBody("json", inJson).addBinaryBody("file", bytes).build();
httppost.setEntity(entity);
HttpResponse response1 = httpclient.execute(httppost);
System.out.print(response1.getStatusLine());
ResponseHandler<String> handler = new BasicResponseHandler();
String json1 = handler.handleResponse(response1);
System.out.println(json1);
message = message + "You successfully uploaded " + file.getOriginalFilename() + "\n";
System.out.println(message);
}
by using ResponseEntity spring object, you can customize your returns based upload results. you catch IOEXception and create a specific return String,
I modified your method to be like this :
#PostMapping("/upload")
public ResponseEntity<?> handleFileUpload(#RequestParam("specifications")
MultipartFile[] specifications,
HttpServletRequest request,HttpSession session,final RedirectAttributes
redirectAttributes) throws Exception {
String failed_upload="";
for (int i = 0; i < specifications.length; i++) {
try{
MultipartFile file = specifications[i];
String path = "Specification/";
String bucketName="BUcket/";
String inJson = "{\"filename\":\"" + file.getOriginalFilename()
+ "\",\"bucketname\":\""+ bucketName + "\",\"path\":\""+ path + "\"}";
addLogo(file, inJson);
}catch(IOException){
failed_upload=failed_upload+specifications[i]+" ,";
}
} if(!failed_upload.equals("")){
return new ResponseEntity<>("Files"+failed_upload+" not uploaded",
HttpStatus.INTERNAL_SERVER_ERROR);
}else{
return new ResponseEntity<>("Everything is ok", HttpStatus.OK);
}

How to intergrate cas restful in Web application?

I'm using CAS build SSO, I want to implement login/logout by using CAS RESTful API in my own Web Application.
and the api like this http://sso.cvs.cn:9990/cas-server-webapp/v1/tickets
i test it by test case, and it succesful. here is the code:
public static void main(String... args) throws Exception {
String username = "123";
String password = "123";
validateFromCAS(username, password);
}
public static boolean validateFromCAS(String username, String password) throws Exception {
String url = "http://sso.cvs.cn:9990/cas-server-webapp/v1/tickets";
try {
HttpURLConnection hsu = (HttpURLConnection) openConn(url);
String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
System.out.println(s);
OutputStreamWriter out = new OutputStreamWriter(hsu.getOutputStream());
BufferedWriter bwr = new BufferedWriter(out);
bwr.write(s);
bwr.flush();
bwr.close();
out.close();
String tgt = hsu.getHeaderField("location");
System.out.println(hsu.getResponseCode());
if (tgt != null && hsu.getResponseCode() == 201) {
System.out.println(tgt);
System.out.println("Tgt is : " + tgt.substring(tgt.lastIndexOf("/") + 1));
tgt = tgt.substring(tgt.lastIndexOf("/") + 1);
bwr.close();
closeConn(hsu);
String serviceURL = "http://sso.cvs.cn:7070/cas-simple-site-alpha/";
String encodedServiceURL = URLEncoder.encode("service", "utf-8") + "=" + URLEncoder.encode(serviceURL, "utf-8");
System.out.println("Service url is : " + encodedServiceURL);
String myURL = url + "/" + tgt;
System.out.println(myURL);
hsu = (HttpURLConnection) openConn(myURL);
out = new OutputStreamWriter(hsu.getOutputStream());
bwr = new BufferedWriter(out);
bwr.write(encodedServiceURL);
bwr.flush();
bwr.close();
out.close();
System.out.println("Response code is: " + hsu.getResponseCode());
BufferedReader isr = new BufferedReader(new InputStreamReader(hsu.getInputStream()));
String line;
System.out.println(hsu.getResponseCode());
while ((line = isr.readLine()) != null) {
System.out.println(line);
}
isr.close();
hsu.disconnect();
return true;
} else {
return false;
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
throw mue;
} catch (IOException ioe) {
ioe.printStackTrace();
throw ioe;
}
}
but how i can use the api in my web application?
If i understand correctly your question is how the api would be usefull for you in general.
So if this is the case, with restful api enabled on cas, when a user gets authenticated by CAS server, he would be allowed to access other applications (cas enabled services) which are configured to have SSO with the same CAS server. Also you can do requests for tickets with POST as the documentation suggests.
Also another reason is that applications need to programmatically access CAS. Say one casified application can invoke other casified application’s REST APIs on behalf of an authenticated user. For this purpose CAS Rest protocol will do the job

google cloud print from android without dialog

Can someone tell me if it is possible to silently print using google cloud print from an android device?
The goal is that my app grabs a file from a URL or from the SD card and then sends it to a specific printer - all without interaction from anyone looking at the screen or touching anything. It will actually be triggered by a barcode scan on a blue tooth connected device.
Thanks
Well, it is possible but I don't know why there's not too much information about it in the documentation...
The tricky part is connecting to the google cloud print API using only the android device (with no third party servers as the documentation explains here: https://developers.google.com/cloud-print/docs/appDevGuide ), so that's what I'm going to explain.
First, you have to include in your app the Google sign-in API, I recommend firebase API https://firebase.google.com/docs/auth/android/google-signin
Then you have to go to your Google API console: https://console.developers.google.com in the menu, go to Credentials scroll to OAuth 2.0 client IDs select Web client (auto created by Google Service) and save into your project the Client ID and Client secret keys... In my project, I saved them as "gg_client_web_id" and "gg_client_web_secret" as you will see below in the code.
Next, I'm going to paste all the code and then I'll explain it:
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final int REQUEST_SINGIN = 1;
private TextView txt;
public static final String TAG = "mysupertag";
public static final String URLBASE = "https://www.google.com/cloudprint/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
mAuth = FirebaseAuth.getInstance();
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.gg_client_web_id))
.requestEmail()
.requestServerAuthCode(getString(R.string.gg_client_web_id))
.requestScopes(new Scope("https://www.googleapis.com/auth/cloudprint"))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "error connecting: " + connectionResult.getErrorMessage());
Toast.makeText(this, "error CONN", Toast.LENGTH_LONG).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == REQUEST_SINGIN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
Toast.makeText(this, "error ", Toast.LENGTH_LONG).show();
}
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQUEST_SINGIN);
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
FirebaseUser user = task.getResult().getUser();
txt.setText(user.getDisplayName() + "\n" + user.getEmail());//todo
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
getAccess(acct.getServerAuthCode());
}
});
}
private void getPrinters(String token) {
Log.d(TAG, "TOKEN: " + token);
String url = URLBASE + "search";
Ion.with(this)
.load("GET", url)
.addHeader("Authorization", "Bearer " + token)
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
Log.d(TAG, "finished " + result.getHeaders().code() + ": " +
result.getResult());
if (e == null) {
Log.d(TAG, "nice");
} else {
Log.d(TAG, "error");
}
}
});
}
private void getAccess(String code) {
String url = "https://www.googleapis.com/oauth2/v4/token";
Ion.with(this)
.load("POST", url)
.setBodyParameter("client_id", getString(R.string.gg_client_web_id))
.setBodyParameter("client_secret", getString(R.string.gg_client_web_secret))
.setBodyParameter("code", code)
.setBodyParameter("grant_type", "authorization_code")
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
Log.d(TAG, "result: " + result.getResult());
if (e == null) {
try {
JSONObject json = new JSONObject(result.getResult());
getPrinters(json.getString("access_token"));
} catch (JSONException e1) {
e1.printStackTrace();
}
} else {
Log.d(TAG, "error");
}
}
});
}}
As you can see, in the onCreate the important part is creating the GoogleSignInOptions WITH the google cloud print scope AND calling the requestIdToken/requestServerAuthCode methods.
Then in the firebaseAuthWithGoogle method call the getAccess method in order to get the OAuth access token, for making all requests I'm using Ion library: https://github.com/koush/ion
Next with the access_token you can now do requests to the google cloud print API, in this case I call the getPrinters method, in this method I call the "search" method (from google cloud print API) to get all the printers associated to the google account that has signed in.. (to associate a printer to a google account visit this: https://support.google.com/cloudprint/answer/1686197?hl=en&p=mgmt_classic ) Note the .addHeader("Authorization", "Bearer " + token), this is the important part of the request, the "token" var is the access_token, you NEED add this Authorization header in order to use the API and don't forget to refresh when it expires, as explained here : https://developers.google.com/identity/protocols/OAuth2ForDevices in the "Using a refresh token" part.
And that's it, you can now print something sending a POST request to the "submit" method of the google cloud print API, I recommend to go here: https://developers.google.com/cloud-print/docs/appInterfaces and see all the methods available and how to use them (wich parameters send to them, etc). Of course in that link explains the "submit" method too.
EDIT:
EXAMPLE OF HOW TO SEND A REQUEST TO "/submit" FOR PRINTING USING ION LIBRARY AND MJSON LIBRARY (https://bolerio.github.io/mjson/) THE MJSON IS FOR CREATING A JSON OBJECT, YOU CAN CREATE IT THE WAY YOU PREFER
private void printPdf(String pdfPath, String printerId) {
String url = URLBASE + "submit";
Ion.with(this)
.load("POST", url)
.addHeader("Authorization", "Bearer " + YOUR_ACCESS_TOKEN)
.setMultipartParameter("printerid", printerId)
.setMultipartParameter("title", "print test")
.setMultipartParameter("ticket", getTicket())
.setMultipartFile("content", "application/pdf", new File(pdfPath))
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
if (e == null) {
Log.d(TAG, "PRINTTT CODE: " + result.getHeaders().code() +
", RESPONSE: " + result.getResult());
Json j = Json.read(result.getResult());
if (j.at("success").asBoolean()) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
Log.d(TAG, e.toString());
}
}
});
}
private String getTicket() {
Json ticket = Json.object();
Json print = Json.object();
ticket.set("version", "1.0");
print.set("vendor_ticket_item", Json.array());
print.set("color", Json.object("type", "STANDARD_MONOCHROME"));
print.set("copies", Json.object("copies", 1));
ticket.set("print", print);
return ticket.toString();
}
Yes, You can achieve silent print using this REST API(https://www.google.com/cloudprint/submit) ,I have done it using WCF Service.
you need to download contents from url as base64 content, then add
contentType=dataUrl
in the request.
Here is the code..
postData = "printerid=" + PrinterId;
postData += "&title=" + JobTitle;
postData += "&ticket=" + ticket;
postData += "&content=data:" + documentContent.ContentType + ";base64," + documentContent.Base64Content;
postData += "&contentType=dataUrl";
postData += "&tag=test";
Then , please make a request to submit REST API in this way.
var request = (HttpWebRequest)WebRequest.Create("https://www.google.com/cloudprint/submit");
var data = Encoding.ASCII.GetBytes(postData);
request.Headers.Add("Authorization: Bearer " + Token);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.UseDefaultCredentials = true;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
PrintJobResponse printInfo = json_serializer.Deserialize<PrintJobResponse>(responseString);
return printInfo;
Thanks.
For anybody reading this now, after a lot of searching around I have found it is a lot easier and faster to set up to just use Zapier to catch a hook and print to google cloud print (from cordova at least, i can't speak for native apps)

Malformed HTTP post using WWWForm

I'm using UnityHTTP (https://github.com/andyburke/UnityHTTP) to call a REST API ( KiiCloud http://www.kii.com ) and it works great but I want to get rid of the 3rd party library if possible and use Unity's WWW and WWWForm to achieve the same.
Here's the code that uses UnityHTTP that works fine:
public static void RunServerExtension (string appId, string appKey, string endpoint, string kii_access_token, string msg)
{
Hashtable data = new Hashtable();
// Add json fields with values here (use as dictionary)
data.Add("message", msg);
// When you pass a Hashtable as the third argument, we assume you want it send as JSON-encoded
// data. We'll encode it to JSON for you and set the Content-Type header to application/json
HTTP.Request myRequest = new HTTP.Request( "post", "https://api.kii.com/api/apps/" + appId + "/server-code/versions/current/" + endpoint, data);
myRequest.AddHeader("x-kii-appid", appId);
myRequest.AddHeader("x-kii-appkey", appKey);
if(kii_access_token != null)
theRequest.AddHeader("Authorization", "Bearer " + kii_access_token);
myRequest.Send( ( request ) => {
// we provide Object and Array convenience methods that attempt to parse the response as JSON
// if the response cannot be parsed, we will return null
// note that if you want to send json that isn't either an object ({...}) or an array ([...])
// that you should use JSON.JsonDecode directly on the response.Text, Object and Array are
// only provided for convenience
Hashtable result = request.response.Object;
if ( result == null )
{
Debug.LogWarning( "Could not parse JSON response!" );
return;
}
Debug.Log ("Got response");
Debug.Log(request.response.Text);
});
}
So the above works just fine but when I switch to WWWForm in this way:
public static WWW RunServerExtension (string appId, string appKey, string endpoint, string kii_access_token, string msg)
{
WWWForm form = new WWWForm();
Hashtable headers = form.headers;
headers["Content-Type"] = "application/json";
headers["x-kii-appid"] = appId;
headers["x-kii-appkey"] = appKey;
if(kii_access_token != null)
headers["Authorization"] = "Bearer " + kii_access_token;
form.AddField("message", msg);
return new WWW("https://api.kii.com/api/apps/" + appId + "/server-code/versions/current/" + endpoint, form.data, headers);
}
private IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
I get a BAD REQUEST on the server side (meaning the request is malformed, not what the server was expecting). Note that the headers must be passed as parameter otherwise the server complains about missing headers.
I suspected this might be related to the fact that the server expects JSON data so I converted the message to JSON using UnityHTTP JSON class (you can use just that isolated class for JSON encoding/decoding) https://github.com/andyburke/UnityHTTP/blob/master/external/JSON.cs so this method passes {"message":"This is echoed!!"} as data:
public static WWW RunServerExtension (string appId, string appKey, string endpoint, string kii_access_token, string msg)
{
WWWForm form = new WWWForm();
Hashtable headers = form.headers;
headers["Content-Type"] = "application/json";
headers["x-kii-appid"] = appId;
headers["x-kii-appkey"] = appKey;
if(kii_access_token != null)
headers["Authorization"] = "Bearer " + kii_access_token;
Hashtable data = new Hashtable();
data["message"] = msg;
byte[] bytes = GetBytes(JSON.JsonEncode(data));
return new WWW("https://api.kii.com/api/apps/" + appId + "/server-code/versions/current/" + endpoint, bytes, headers);
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
But still the same BAD REQUEST. Do you see why this could be failing? Why UnityHTTP works?
As I mentioned in comments: C# converts all strings to UTF-16. If your webserver is expecting a different encoding, simply passing the bytes verbatim will not produce good results.
JSON is typically encoded in UTF-8, but it's best if an API specifies its input/output encodings explicitly.
I took a bit more time, today. If you check UnityHTTP's source, you can see that their Hashtable constructor encodes JSON in UTF-8:
this.bytes = Encoding.UTF8.GetBytes( JSON.JsonEncode( data ) );
Your code does not change the string's encoding, which means you're sending the wrong bytes.

Stackmob is giving 401 error while registering device

I am registering the device to stackmob with username and device token . I am getting valid tokens from c2dn and then storing it into db for that user and then while registering to stackmob i am using these parameters. On dev environment its working fine but same piece of code is giving 401 while registering the device. Please suggest me in this.
The code for this is below :
public String registerWithNotificationServiceProvider(final String userName, final String deviceToken) throws UserException
{
if (userName.isEmpty() || deviceToken.isEmpty()) {
throw new UserException(ResponseCodes.STATUS_BAD_REQUEST, "User Name or device token is null",## Heading ## "label.invalid.user.device.details");
}
StackMobRequestSendResult deviceRegisterResult = null;
deviceRegisterResult = StackMob.getStackMob().registerForPushWithUser(userName, deviceToken,
new StackMobRawCallback() {
#Override
public void done(HttpVerb requestVerb, String requestURL,
List<Map.Entry<String, String>> requestHeaders, String requestBody,
Integer responseStatusCode, List<Map.Entry<String, String>> responseHeaders,
byte[] responseBody) {
String response = new String(responseBody);
logger.info("request Body is " + requestBody);
logger.info("request Url is " + requestURL);
for(Map.Entry<String, String> entry : requestHeaders){
logger.info("Request Header is " + entry.getKey());
logger.info("Request Header content is " + entry.getValue());
}
for(Map.Entry<String, String> entry : responseHeaders){
logger.info("Response Header is " + entry.getKey());
logger.info("Response Header content is " + entry.getValue());
}
logger.info("response while registering the device is " + response);
logger.info("responseCode while registering device " + responseStatusCode);
}
});
String status = null;
if (deviceRegisterResult.getStatus() != null) {
status = deviceRegisterResult.getStatus().name();
logger.debug("For user : " + userName + " Status for registering device is " + status);
}
if (Status.SENT.getStatus().equalsIgnoreCase(status)) {
return Status.SUCCESS.getStatus();
} else {
return Status.FAILURE.getStatus();
}
}
When you setup your StackMob object with the api key and secret, do you remember to use apiVersion 1 with your production key and secret? That's the most likely problem.
StackMobCommon.API_KEY = KEY;
StackMobCommon.API_SECRET = SECRET;
StackMobCommon.USER_OBJECT_NAME = "user";
StackMobCommon.API_VERSION = 1; //! 0 for dev, 1 for production
If that doesn't work also set
StackMob.getStackMob().getLogger().setLogging(true);
at the beginning and post the resulting logs