android - AmazonSNS - AwsCredentials.properties - NullPointerException -
i new android studio , intellij.
i trying work amazonsns - push. unable figure out how add awscredentials.properties file classpath of module. npe @ line 57 in image below(at method getresourceasstream()). added required keys in awscredentials.properties file.
error:
in questions have come across on stackoverflow regarding similar issues, suggested file should in root folder, where, src is. placed in same folder of src, still getting npe. tried placing file in com/test/ no use.
how solve this? there other steps involved?
edit after starting bounty - adding java files
here did till now..
create android application called myapplication. imported classes(androidmobilepushapp.java, externalreceiver.java, messagereceivingservice.java) demo application. added required libs, , ran , got registationid response amazon.
in same application, created new module called snspush , imported snsmobilepush.java file it. imported awscredentials.properties file same path of snsmobilepush.java. added keys in awscredentials.properties file.
followed steps in documentation uncomment necessary funtions.
project structure:
java files:
androidmobilepushapp.java:
public class androidmobilepushapp extends appcompatactivity { private textview tview; private sharedpreferences savedvalues; private string numofmissedmessages;
// since activity singletop, there can ever 1 instance. variable corresponds instance. public static boolean inbackground = true; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); numofmissedmessages = getstring(r.string.num_of_missed_messages); setcontentview(r.layout.activity_main); tview = (textview) findviewbyid(r.id.tviewid); tview.setmovementmethod(new scrollingmovementmethod()); startservice(new intent(this, messagereceivingservice.class)); } public void onstop(){ super.onstop(); inbackground = true; } public void onrestart(){ super.onrestart(); tview.settext("");; } public void onresume(){ super.onresume(); inbackground = false; savedvalues = messagereceivingservice.savedvalues; int numofmissedmessages = 0; if(savedvalues != null){ numofmissedmessages = savedvalues.getint(this.numofmissedmessages, 0); } string newmessage = getmessage(numofmissedmessages); if(newmessage!=""){ log.i("displaying message", newmessage); tview.append(newmessage); } } public void onnewintent(intent intent){ super.onnewintent(intent); setintent(intent); } // if messages have been missed, check backlog. otherwise check current intent new message. private string getmessage(int numofmissedmessages) { string message = ""; string linesofmessagecount = getstring(r.string.lines_of_message_count); if(numofmissedmessages > 0){ string plural = numofmissedmessages > 1 ? "s" : ""; log.i("onresume","missed " + numofmissedmessages + " message" + plural); tview.append("you missed " + numofmissedmessages +" message" + plural + ". recent was:\n"); for(int = 0; < savedvalues.getint(linesofmessagecount, 0); i++){ string line = savedvalues.getstring("messageline"+i, ""); message+= (line + "\n"); } notificationmanager mnotification = (notificationmanager) getsystemservice(context.notification_service); mnotification.cancel(r.string.notification_number); sharedpreferences.editor editor=savedvalues.edit(); editor.putint(this.numofmissedmessages, 0); editor.putint(linesofmessagecount, 0); editor.commit(); } else{ log.i("onresume","no missed messages"); intent intent = getintent(); if(intent!=null){ bundle extras = intent.getextras(); if(extras!=null){ for(string key: extras.keyset()){ message+= key + "=" + extras.getstring(key) + "\n"; } } } } message+="\n"; return message; } public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } public boolean onoptionsitemselected(menuitem item) { if(item.getitemid() == r.id.menu_clear){ tview.settext(""); return true; } else{ return super.onoptionsitemselected(item); } }
}
externalreceiver.java
package com.test.awstestapp;
import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.os.bundle;
public class externalreceiver extends broadcastreceiver {
public void onreceive(context context, intent intent) { if(intent!=null){ bundle extras = intent.getextras(); if(!androidmobilepushapp.inbackground){ messagereceivingservice.sendtoapp(extras, context); } else{ messagereceivingservice.savetolog(extras, context); } } }
}
messagereceivingservice.java
public class messagereceivingservice extends service{ private googlecloudmessaging gcm; public static sharedpreferences savedvalues;
public static void sendtoapp(bundle extras, context context){ intent newintent = new intent(); newintent.setclass(context, androidmobilepushapp.class); newintent.putextras(extras); newintent.setflags(intent.flag_activity_new_task); context.startactivity(newintent); } public void oncreate(){ super.oncreate(); final string preferences = getstring(r.string.preferences); savedvalues = getsharedpreferences(preferences, context.mode_private); // in later versions multi_process no longer default if(version.sdk_int > 9){ savedvalues = getsharedpreferences(preferences, context.mode_multi_process); } gcm = googlecloudmessaging.getinstance(getbasecontext()); sharedpreferences savedvalues = preferencemanager.getdefaultsharedpreferences(this); if(savedvalues.getboolean(getstring(r.string.first_launch), true)){ register(); sharedpreferences.editor editor = savedvalues.edit(); editor.putboolean(getstring(r.string.first_launch), false); editor.commit(); } // let androidmobilepushapp know have initialized , there may stored messages sendtoapp(new bundle(), this); } protected static void savetolog(bundle extras, context context){ sharedpreferences.editor editor=savedvalues.edit(); string numofmissedmessages = context.getstring(r.string.num_of_missed_messages); int linesofmessagecount = 0; for(string key : extras.keyset()){ string line = string.format("%s=%s", key, extras.getstring(key)); editor.putstring("messageline" + linesofmessagecount, line); linesofmessagecount++; } editor.putint(context.getstring(r.string.lines_of_message_count), linesofmessagecount); editor.putint(context.getstring(r.string.lines_of_message_count), linesofmessagecount); editor.putint(numofmissedmessages, savedvalues.getint(numofmissedmessages, 0) + 1); editor.commit(); postnotification(new intent(context, androidmobilepushapp.class), context); } protected static void postnotification(intent intentaction, context context){ final notificationmanager mnotificationmanager = (notificationmanager) context.getsystemservice(context.notification_service); final pendingintent pendingintent = pendingintent.getactivity(context, 0, intentaction, notification.default_lights | notification.flag_auto_cancel); final notification notification = new notificationcompat.builder(context).setsmallicon(r.mipmap.ic_launcher) .setcontenttitle("message received!") .setcontenttext("") .setcontentintent(pendingintent) .setautocancel(true) .getnotification(); mnotificationmanager.notify(r.string.notification_number, notification); } private void register() { new asynctask(){ protected object doinbackground(final object... params) { string token; try { token = gcm.register(getstring(r.string.project_number)); log.i("registrationid", token); } catch (ioexception e) { log.i("registration error", e.getmessage()); } return true; } }.execute(null, null, null); } public ibinder onbind(intent arg0) { return null; }
}
snsmobilepush.java
package com.test;
public class snsmobilepush { private amazonsnsclientwrapper snsclientwrapper; public snsmobilepush(amazonsns snsclient) { this.snsclientwrapper = new amazonsnsclientwrapper(snsclient); } public static final map<platform, map<string, messageattributevalue>> attributesmap = new hashmap<platform, map<string, messageattributevalue>>(); static { attributesmap.put(platform.adm, null); attributesmap.put(platform.gcm, null); attributesmap.put(platform.apns, null); attributesmap.put(platform.apns_sandbox, null); attributesmap.put(platform.baidu, addbaidunotificationattributes()); attributesmap.put(platform.wns, addwnsnotificationattributes()); attributesmap.put(platform.mpns, addmpnsnotificationattributes()); } public static void main(string[] args) throws ioexception { /* * todo: sure fill in aws access credentials in * awscredentials.properties file before try run sample. * http://aws.amazon.com/security-credentials */ amazonsns sns = new amazonsnsclient(new propertiescredentials( snsmobilepush.class .getresourceasstream("awscredentials.properties"))); sns.setendpoint("https://sns.us-west-2.amazonaws.com"); system.out.println("===========================================\n"); system.out.println("getting started amazon sns"); system.out.println("===========================================\n"); try { snsmobilepush sample = new snsmobilepush(sns); /* todo: uncomment services wish use. */ sample.demoandroidappnotification(); // sample.demokindleappnotification(); // sample.demoappleappnotification(); // sample.demoapplesandboxappnotification(); // sample.demobaiduappnotification(); // sample.demownsappnotification(); // sample.demompnsappnotification(); } catch (amazonserviceexception ase) { system.out .println("caught amazonserviceexception, means request made " + "to amazon sns, rejected error response reason."); system.out.println("error message: " + ase.getmessage()); system.out.println("http status code: " + ase.getstatuscode()); system.out.println("aws error code: " + ase.geterrorcode()); system.out.println("error type: " + ase.geterrortype()); system.out.println("request id: " + ase.getrequestid()); } catch (amazonclientexception ace) { system.out .println("caught amazonclientexception, means client encountered " + "a serious internal problem while trying communicate sns, such not " + "being able access network."); system.out.println("error message: " + ace.getmessage()); } } public void demoandroidappnotification() { // todo: please fill in following values application. can // change notification payload per preferences using // method // com.amazonaws.sns.samples.tools.samplemessagegenerator.getsampleandroidmessage() string serverapikey = "replaced_with_server_api_key"; string applicationname = "snspushtest"; string registrationid = "replaced_with_reg_id_from_amazon"; snsclientwrapper.demonotification(platform.gcm, "", serverapikey, registrationid, applicationname, attributesmap); } public void demokindleappnotification() { // todo: please fill in following values application. can // change notification payload per preferences using // method // com.amazonaws.sns.samples.tools.samplemessagegenerator.getsamplekindlemessage() string clientid = ""; string clientsecret = ""; string applicationname = ""; string registrationid = ""; snsclientwrapper.demonotification(platform.adm, clientid, clientsecret, registrationid, applicationname, attributesmap); } public void demoappleappnotification() { // todo: please fill in following values application. can // change notification payload per preferences using // method // com.amazonaws.sns.samples.tools.samplemessagegenerator.getsampleapplemessage() string certificate = ""; // should in pem format \n @ // end of each line. string privatekey = ""; // should in pem format \n @ // end of each line. string applicationname = ""; string devicetoken = ""; // 64 hex characters. snsclientwrapper.demonotification(platform.apns, certificate, privatekey, devicetoken, applicationname, attributesmap); } public void demoapplesandboxappnotification() { // todo: please fill in following values application. can // change notification payload per preferences using // method // com.amazonaws.sns.samples.tools.samplemessagegenerator.getsampleapplemessage() string certificate = ""; // should in pem format \n @ // end of each line. string privatekey = ""; // should in pem format \n @ // end of each line. string applicationname = ""; string devicetoken = ""; // 64 hex characters. snsclientwrapper.demonotification(platform.apns_sandbox, certificate, privatekey, devicetoken, applicationname, attributesmap); } public void demobaiduappnotification() { /* * todo: please fill in following values application. if * wish change properties of baidu notification, can * modifying attribute values in method * addbaidunotificationattributes() . can change * notification payload per preferences using method * com.amazonaws * .sns.samples.tools.samplemessagegenerator.getsamplebaidumessage() */ string userid = ""; string channelid = ""; string apikey = ""; string secretkey = ""; string applicationname = ""; snsclientwrapper.demonotification(platform.baidu, apikey, secretkey, channelid + "|" + userid, applicationname, attributesmap); } public void demownsappnotification() { /* * todo: please fill in following values application. if * wish change properties of wns notification, can * modifying attribute values in method * addwnsnotificationattributes() . can change notification * payload per preferences using method * com.amazonaws.sns.samples * .tools.samplemessagegenerator.getsamplewnsmessage() */ string notificationchanneluri = ""; string packagesecurityidentifier = ""; string secretkey = ""; string applicationname = ""; snsclientwrapper.demonotification(platform.wns, packagesecurityidentifier, secretkey, notificationchanneluri, applicationname, attributesmap); } public void demompnsappnotification() { /* * todo: please fill in following values application. if * wish change properties of mpns notification, can * modifying attribute values in method * addmpnsnotificationattributes() . can change * notification payload per preferences using method * com.amazonaws * .sns.samples.tools.samplemessagegenerator.getsamplempnsmessage () */ string notificationchanneluri = ""; string applicationname = ""; snsclientwrapper.demonotification(platform.mpns, "", "", notificationchanneluri, applicationname, attributesmap); } private static map<string, messageattributevalue> addbaidunotificationattributes() { map<string, messageattributevalue> notificationattributes = new hashmap<string, messageattributevalue>(); notificationattributes.put("aws.sns.mobile.baidu.deploystatus", new messageattributevalue().withdatatype("string") .withstringvalue("1")); notificationattributes.put("aws.sns.mobile.baidu.messagekey", new messageattributevalue().withdatatype("string") .withstringvalue("default-channel-msg-key")); notificationattributes.put("aws.sns.mobile.baidu.messagetype", new messageattributevalue().withdatatype("string") .withstringvalue("0")); return notificationattributes; } private static map<string, messageattributevalue> addwnsnotificationattributes() { map<string, messageattributevalue> notificationattributes = new hashmap<string, messageattributevalue>(); notificationattributes.put("aws.sns.mobile.wns.cachepolicy", new messageattributevalue().withdatatype("string") .withstringvalue("cache")); notificationattributes.put("aws.sns.mobile.wns.type", new messageattributevalue().withdatatype("string") .withstringvalue("wns/badge")); return notificationattributes; } private static map<string, messageattributevalue> addmpnsnotificationattributes() { map<string, messageattributevalue> notificationattributes = new hashmap<string, messageattributevalue>(); notificationattributes.put("aws.sns.mobile.mpns.type", new messageattributevalue().withdatatype("string") .withstringvalue("token")); // attribute required. notificationattributes.put("aws.sns.mobile.mpns.notificationclass", new messageattributevalue().withdatatype("string") .withstringvalue("realtime")); // attribute required. return notificationattributes; } }
edit 2:
edit 3:
i changed following code to:
amazonsns sns = new amazonsnsclient(new propertiescredentials( snsmobilepush.class .getresourceasstream("awscredentials.properties")));
to
amazonsns sns = new amazonsnsclient(new basicawscredentials("access_key_replaced", "secret_key_replaced"));
now, there different error: logcat
=========================================== getting started amazon sns =========================================== exception in thread "main" java.lang.noclassdeffounderror: org/xmlpull/v1/xmlpullparserexception @ com.amazonaws.services.sns.amazonsnsclient.invoke(amazonsnsclient.java:2263) @ com.amazonaws.services.sns.amazonsnsclient.createplatformapplication(amazonsnsclient.java:358) @ com.test.tools.amazonsnsclientwrapper.createplatformapplication(amazonsnsclientwrapper.java:49) @ com.test.tools.amazonsnsclientwrapper.demonotification(amazonsnsclientwrapper.java:119) @ com.test.snsmobilepush.demoandroidappnotification(snsmobilepush.java:104) @ com.test.snsmobilepush.main(snsmobilepush.java:71) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:483) @ com.intellij.rt.execution.application.appmain.main(appmain.java:140) caused by: java.lang.classnotfoundexception: org.xmlpull.v1.xmlpullparserexception @ java.net.urlclassloader$1.run(urlclassloader.java:372) @ java.net.urlclassloader$1.run(urlclassloader.java:361) @ java.security.accesscontroller.doprivileged(native method) @ java.net.urlclassloader.findclass(urlclassloader.java:360) @ java.lang.classloader.loadclass(classloader.java:424) @ sun.misc.launcher$appclassloader.loadclass(launcher.java:308) @ java.lang.classloader.loadclass(classloader.java:357) ... 11 more process finished exit code 1
with respect properties credentials
a. sure exporting file in build? have made sure can access file using regular file i/o outside of credentials provider? sure file formatted correctly (see https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-core/src/main/java/com/amazonaws/auth/propertiescredentials.java) accesskey=key secretkey=secret looking @ source should able load file using http://developer.android.com/reference/java/util/properties.html.
however, highly recommend not using credentials provider. extremely unsafe in mobile applications. decompile app , steal credentials. safer approach use amazon cognito, there plethora of examples. (bottom of https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/setup.html , of examples here: https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/getting-started-android.html samples in github repo https://github.com/awslabs/aws-sdk-android-samples
cognito requires little bit of set-up guides tested, , doesn't take more few minutes more secure.
Comments
Post a Comment