How to get wifi connected device list in alljoyn? - java

I have use alljoyn for wifi share. I want device list connected to wifi network on channel base.
I have follow one demo but it not call implemented method announced
AboutListener is part of alljoyn.
import org.alljoyn.bus.AboutListener;
public class OnboardingApplication extends Application implements AboutListener {
#Override
public void announced(String busName, int version, short port, AboutObjectDescription[] objectDescriptions, Map<String, Variant> aboutMap) {
Map<String, Object> newMap = new HashMap<String, Object>();
try {
newMap = TransportUtil.fromVariantMap(aboutMap);
String deviceId = (newMap.get(AboutKeys.ABOUT_APP_ID).toString());
String deviceFriendlyName = (String) newMap.get(AboutKeys.ABOUT_DEVICE_NAME);
m_logger.debug(TAG, "onAnnouncement received: with parameters: busName:" + busName + ", port:" + port + ", deviceid" + deviceId + ", deviceName:" + deviceFriendlyName);
addDevice(deviceId, busName, port, deviceFriendlyName, objectDescriptions, newMap);
} catch (BusException e) {
e.printStackTrace();
}
}
}

In order to get the announced method called you'll need to register your AboutListener:
org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
//Bus Connection
Status status = mBus.connect();
//Check if connection is established
if (status != Status.OK) {
return;
}
//Setup Bus Attachment
mBus.useOSLogging(true);
mBus.setDebugLevel("ALLJOYN_JAVA", 7);
mBus.registerAboutListener(mListener);
//Start AboutData Listener
status = mBus.whoImplements(null);
if (status != Status.OK) {
Log.e(TAG, "whoImplements Error");
} else {
Log.w(TAG, "whoImplements Success");
}
mListener is your object that implements AboutListener.
When you call whoImplements(null) you are saying you want all announcements from all interfaces.

In addition to what LopesFigueiredo said, try creating your BusAttachment with a remote message policy of Receive. For example:
BusAttachment mBus = new BusAttachment("My Attachment", BusAttachment.RemoteMessage.Receive);

Related

Broadcasting device using jmDNS

I'm currently trying to have my device (program) show up as a mock chromecast on the network. The application itself can see the Mock-Caster as a chromecast but if i try searching for it using Youtube or any other sender app, the "Mock-Caster" does not appear in the list.
I registered a service on jmDNS with all the criteria that would be available on an actual chromecast as well.
Is there something that I am missing or getting wrong?
Here's what I have so far.
public void postConstruct() throws Exception {
InetAddress discoveryInterface = InetAddress.getByName("192.168.1.1");
CAST_DEVICE_MONITOR.startDiscovery(discoveryInterface, "Mock-Server");
CAST_DEVICE_MONITOR.registerListener(new DeviceDiscoveryListener() {
#Override
public void deviceDiscovered(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
#Override
public void deviceRemoved(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
});
JmDNS jmdns = JmDNS.create(discoveryInterface, "Mock-Server");
final String name = "Mock-Caster";
final String id = UUID.randomUUID().toString();
// Register a service
HashMap<String, String> properties = new HashMap<>();
//values scraped from chromecast or another java project
properties.put("sf", "1");
properties.put("id", id);
properties.put("md", name);
properties.put("fd", name);
properties.put("s#", "1");
properties.put("ff", "0");
properties.put("ci", "1");
properties.put("c#", Integer.toString(1));
properties.put("pv", "1.1");
properties.put("cd", "E465315D08CFDEF2742E1264D78F6035");
properties.put("rm", "ED724E435DA8115C");
properties.put("ve", "05");
properties.put("ic", "/setup/icon.png");
properties.put("ca", "201221");
properties.put("st", "0");
properties.put("bs", "FA8FCA771881");
properties.put("nf", "1");
properties.put("rs", "");
ServiceInfo serviceInfo = ServiceInfo.create("_googlecast._tcp.local.", name, 8009, 1, 1, properties);
jmdns.registerService(serviceInfo);
}
//This is where i know that the mock-caster is registered and available
#Bean
public IntegrationFlow tcpServer() throws Exception {
TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(8009);
DefaultTcpSSLContextSupport defaultTcpSSLContextSupport = new DefaultTcpSSLContextSupport(keystore, keystore, password, password);
defaultTcpSSLContextSupport.setProtocol("TLS");
factory.setTcpNioConnectionSupport(new DefaultTcpNioSSLConnectionSupport(defaultTcpSSLContextSupport));
factory.setTcpSocketSupport(new DefaultTcpSocketSupport(false));
factory.setDeserializer(TcpCodecs.lengthHeader4());
factory.setSerializer(TcpCodecs.lengthHeader4());
TcpInboundGatewaySpec inboundGateway = Tcp.inboundGateway(factory);
return IntegrationFlows
.from(inboundGateway)
.handle(message -> {
String ip_address = message.getHeaders().get("ip_address").toString();
if(ip_address.equalsIgnoreCase("192.168.1.1")) {
System.out.println("Self IP Address received");
System.out.println("Payload: " + message.getPayload());
System.out.println("MessageHeaders: " + message.getHeaders());
}else{
System.out.println("Other IP address received: " + ip_address);
}
})
.get();
}
//Mock-Caster detected here
#Scheduled(fixedRate = 15000)
public void checkCasters() throws Exception {
Set<CastDevice> casters = CAST_DEVICE_MONITOR.getCastDevices();
System.out.println("Current CCs: " + casters.size());
for (CastDevice device : casters) {
System.out.println("CC (" + device.getDisplayName() + ")");
var receiver = new CastEvent.CastEventListener() {
#Override
public void onEvent(#Nonnull CastEvent<?> castEvent) {
System.out.println("Event: " + castEvent);
}
};
var appId = DEFAULT_MEDIA_RECEIVER_APP;
try {
if (!device.isConnected()) {
device.connect();
}
device.addEventListener(receiver);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
device.removeEventListener(receiver);
device.disconnect();
}
}

FCM android client randomly stops receiving data messages

I've implemented FCM on my server with an Android client, and it worked fine for a while. All of a sudden, the client stopped receiving notifications for 5-10 minutes at a time, after which it would get all the pending notifications at once. The logs show that the server is sending the messages correctly.
When the message queue gets stuck, not even test messages from the Firebase console get through.
The only relevant thing I've found in the official documentation was regarding the lifetime of a message:
If the device is not connected to FCM, the message is stored until a connection is established (again respecting the collapse key rules). When a connection is established, FCM delivers all pending messages to the device.
But my network is working fine, and this issue has arisen on other networks and clients as well. When I freshly install the app, a new token is being generated and successfully received by my server. It's just the server-to-client messages that aren't going through.
How can I determine if the connection is established and fix it? Or what else could be the cause of this?
This is my client-side code
AndroidManifest.xml
<application
android:name=".App"
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<service
android:name=".service.NotificationService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
NotificationService.java
public class NotificationService extends FirebaseMessagingService {
private static final String TAG = "NotificationService";
private static String token;
public NotificationService() {
token = PreferenceManager
.getDefaultSharedPreferences(App.getContext())
.getString("firebase-token", null);
}
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
token = task.getResult().getToken();
Log.d(TAG, "onComplete: token = " + token);
PreferenceManager
.getDefaultSharedPreferences(App.getContext())
.edit()
.putString("firebase-token", token)
.apply();
}
});
}
#Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "Received message of size " + remoteMessage.getData().size());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
int left = -1, right = -1;
if (remoteMessage.getData().get("left") != null) {
left = Integer.parseInt(Objects.requireNonNull(remoteMessage.getData()
.get("left")));
}
if (remoteMessage.getData().get("right") != null) {
right = Integer.parseInt(Objects.requireNonNull(remoteMessage.getData()
.get("right")));
}
if (remoteMessage.getData().get("REFRESH") != null) {
Util.sendTitleBroadcast(getApplicationContext(),
left, right,
Util.REFRESH_TITLE);
} else {
Util.sendTitleBroadcast(getApplicationContext(),
left, right,
Util.TITLE_DATA_RECEIVED);
}
}
});
}
}
public static String getToken() {
if (token == null) {
token = PreferenceManager
.getDefaultSharedPreferences(App.getContext())
.getString("firebase-token", null);
}
return token;
}
}
Code for server-side
FirebaseMessagingService.java
public class FirebaseMessagingService {
private static final Logger logger = Logger
.getLogger(FirebaseMessagingService.class);
private static FirebaseMessagingService instance;
/**
* Path to resource file that contains the credentials for Admin SDK.
*/
private final String keyPath = "firebase-adminsdk.json";
/**
* Maps a token list to each topic Object.
*/
private static Map<Object, List<String>> topicTokenMap;
public synchronized static FirebaseMessagingService getInstance() {
if (instance == null) {
instance = new FirebaseMessagingService();
}
return instance;
}
private FirebaseMessagingService() {
init();
}
/**
* Initializes the Firebase service account using the credentials from the
* json file found at keyPath.
*/
private void init() {
try {
InputStream serviceAccount
= getClass().getClassLoader().getResourceAsStream(keyPath);
if (serviceAccount != null) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials
.fromStream(serviceAccount))
.setDatabaseUrl(databaseUrl)
.build();
FirebaseApp.initializeApp(options);
logger.debug("FirebaseMessagingService: init successful");
} else {
logger.debug("FirebaseMessagingService: Input stream null from"
+ " path: " + keyPath);
}
} catch (IOException ex) {
logger.debug("FirebaseMessagingService: Failed to get credentials "
+ "from inputStream." + ex.getMessage());
}
}
/**
* Sends the messages given as parameters to the list of tokens mapped to
* the given topic Object.
*
* #param topic
* #param messages
*/
public void sendMessage(Object topic,
Map<String, String> messages) {
logger.debug("FirebaseMessagingService: sending Message "
+ messages.toString());
try {
if (topicTokenMap != null) {
List<String> tokenList = topicTokenMap.get(topic);
if (tokenList != null) {
tokenList.removeAll(Collections.singleton(null));
MulticastMessage message = MulticastMessage.builder()
.putAllData(messages)
.addAllTokens(tokenList)
.build();
FirebaseMessaging.getInstance().sendMulticast(message);
logger.debug("FirebaseMessagingService: message sent successfully");
}
}
} catch (FirebaseMessagingException ex) {
logger.debug(ex.getMessage());
}
}
/**
* Registers the token given as a parameter to the topic Object.
*
* #param topic
* #param token
*/
public void registerTokenToTopic(Object topic, String token) {
if (topicTokenMap == null) {
topicTokenMap = new HashMap<Object, List<String>>();
}
List<String> tokens = topicTokenMap.get(topic);
if (tokens == null) {
tokens = new ArrayList<String>();
}
if (!tokens.contains(token)) {
tokens.add(token);
}
topicTokenMap.put(topic, tokens);
}
/**
* Unregisters all instances of the token given as a parameter from the topic
* given.
*
* #param topic
* #param token
*/
public void unregisterTokenFromTopic(Object topic, String token) {
if (topicTokenMap != null) {
List<String> tokens = topicTokenMap.get(topic);
if (tokens != null) {
tokens.removeAll(Collections.singleton(token));
}
}
}
/**
* Looks for a topic that has a field with the name equal to topicFieldName
* and the value equal to topicFieldValue and sends a notification to the
* tokens subscribed to that topic, telling them to ask for an update.
*
* #param topicFieldName
* #param topicFieldValue
*/
public void notifyChangeForTopicField(String topicFieldName,
Object topicFieldValue) {
logger.debug("FirebaseMessagingService: notifyChangeForTopicField: "
+ "topicFieldValue = " + topicFieldValue.toString());
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("REFRESH", "true");
if (topicTokenMap != null
&& topicTokenMap.entrySet() != null
&& topicTokenMap.entrySet().size() > 0) {
Iterator it = topicTokenMap.entrySet().iterator();
while (it.hasNext()) {
try {
Map.Entry pair = (Map.Entry) it.next();
Object topic = pair.getKey();
logger.debug("FirebaseMessagingService: "
+ "notifyChangeForTopicField topic = " + topic.toString());
Field field = topic.getClass().getDeclaredField(topicFieldName);
logger.debug("FirebaseMessagingService: "
+ "notifyChangeForTopicField field = " + field.toString());
field.setAccessible(true);
logger.debug("FirebaseMessagingService: "
+ "notifyChangeForTopicField field contains topic: "
+ (field.get(topic) != null ? "true" : "false"));
if (field.get(topic) != null
&& field.get(topic).equals(topicFieldValue)) {
sendMessage(topic, messageMap);
break;
}
it.remove();
} catch (NoSuchFieldException ex) {
java.util.logging.Logger.getLogger(FirebaseMessagingService.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
java.util.logging.Logger.getLogger(FirebaseMessagingService.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
java.util.logging.Logger.getLogger(FirebaseMessagingService.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FirebaseMessagingService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
EDIT: after a few more tests I've found that when one client stops working, the others receive the messages just fine
Your onMessageReceived() looks a bit overkill to me. I do not think you have to create your own Handler to process data. Just stick to the Firebase example: FirebaseExample
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob()
} else {
// Handle message within 10 seconds
handleNow()
}
}
}
I've found the answer here: https://stackoverflow.com/a/23902751/10702209
What happened was that I was getting router timeouts after 5 minutes, randomly. I've fixed the issue by manually sending out heartbeats to FCM after 4 minutes, instead of the default 15 minutes.
context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
I've implemented this fix a couple of months ago and haven't had the issue come up again since.

Send pussh crossplatform, hub Azure

I have an application that is now being developed for IOS. I need them pushed between the platforms. As it is written today, in the backend, it works from Android for Android, but I changed the registration of the devices, so that they were registered with the respective templates (of each platform).
More, it stopped working obviously because it is written from Android to Android.
The record in the hub is correct. What should I change for push to be sent?
Backend code:
public static async void enviarPushNotification(ApiController controller, DataObjects.Notification notification)
{
// Get the settings for the server project.
HttpConfiguration config = controller.Configuration;
MobileAppSettingsDictionary settings =
controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
// Get the Notification Hubs credentials for the Mobile App.
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings
.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
// Create a new Notification Hub client.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
data.Add("Tipo", notification.Tipo);
data.Add("Id_usuario", notification.Id_usuario);
//data.Add("Informacao", notification.Informacao);
data.Add("Informacao", notification.Informacao);
data.Add("Status", notification.Status);
//alteração com a colocação da tag priority em caso de erro teste sem \"priority\": \"high\"
var androidNotificationPayload = "{ \"priority\": \"high\", \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
// var androidNotificationPayload = "{ \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:" + notification.Id_usuario;
//var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload, tag);
// Write the success result to the logs.
config.Services.GetTraceWriter().Info(result.State.ToString());
}
catch (System.Exception ex)
{
// Write the failure result to the logs.
config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
}
}
Device code:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private NotificationHub hub;
public RegistrationIntentService() {
super(TAG);
}
public ApplicationUtils getApplicationUtils() {
return (ApplicationUtils) getApplication();
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
if (FirebaseInstanceId.getInstance() == null) {
FirebaseApp.initializeApp(this);
}
String FCM_token = FirebaseInstanceId.getInstance().getToken();
SaveSharedPreferences.setFCM(getApplicationContext(), FCM_token);
String registrationID = sharedPreferences.getString("registrationID", null);
if (registrationID == null) {
registerDevice(sharedPreferences, FCM_token);
} else {
String fcMtoken = sharedPreferences.getString("FCMtoken", "");
if (!fcMtoken.equals(FCM_token)) {
registerDevice(sharedPreferences, FCM_token);
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to complete registration", e);
}
}
private void registerDevice(SharedPreferences sharedPreferences, String FCM_token) throws Exception {
String tag = "_UserId:" + getApplicationUtils().getUsuario().Id;
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
String templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";
TemplateRegistration registration = hub.registerTemplate(FCM_token, "simpleGCMTemplate", templateBodyGCM, tag);
String regID = registration.getRegistrationId();
sharedPreferences.edit().putString("registrationID", regID).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token).apply();
}
}

Iphone emoji Unicode decode issue for push notification dispatch by APNs

My web service publish push notification to APNs and APNs send to destination IOS device.
When apns contain Unicode emoji on alert body push notification and Iphone os can't decode my Unicode emoji '\uD83D\uDE0A' app already kill.
Push notification show same '\uD83D\uDE0A', No emoji shown on banner notification bar on top.
Android application works fine by GCM dispatches push notification But IOS not support.
Iphone-Ios supports only this format '\ue415'
Here code that from ActiveMQ subscribe chat payload get into web-service
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
try {
String body = msg.utf8().toString();
if (logger.isInfoEnabled()) {
logger.info("MQTT connection.listener.onPublish(), msg Received ["
+ body + "]");
}
if (body.contains("\"cmd\":\"chat\"")
&& body.contains("\"is_sender_msg\":true")) {
QueueMgr.addToChatQueue(body); //Changed true to false
}
else if(body.contains("\"cmd\":\"msg_seen\"")){
QueueMgr.addToChatReadSeenQueue(body);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ack.run();
}
}
My code for create push notification on java
public static JSONObject constructePushJson(JSONObject jsonObject,String[] cloudkeyWithDevice) throws JSONException {
if(cloudkeyWithDevice[0] != null){
JSONObject pnAPIdata = new JSONObject();
if(cloudkeyWithDevice[1].equals("a") || cloudkeyWithDevice[1].equals("d")){
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_ANDROID_PUSH);
}
else{
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_IOS_PUSH);
}
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_APP_TOKEN, com.anyorg.constants.AppConstants.DEFAULT_APP_TOKEN);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_TOKEN, cloudkeyWithDevice[0]);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_USER_ID, jsonObject.getInt(com.anyorg.constants.AppConstants.FLD_TO_USER_ID));
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_ID, 0);
String alertMsg=StringEscapeUtils.unescapeJava(jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY));
jsonObject.put(com.anyorg.constants.AppConstants.FLD_BODY,alertMsg);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_ALERT_MSG, "AryaConnect: "+alertMsg);//(jsonObject.isNull("body")) ? jsonObject.getString("from_user_name")+": Sent a file" : jsonObject.getString("from_user_name")+": "+jsonObject.getString("body")
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_MSG, jsonObject);//jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY)
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CALLBACK_URL, callbackUrl);
pnAPIdata.put(com.anyorg.constants.AppConstants.MAC_ADDRESS_ID, jsonObject.getString("mobile_rec_id"));
return pnAPIdata;
}
else{
return null;
}
}
Publish to APNs code
public class ANSNotificationDispatcher implements NotificationDispatcher {
protected static final Logger logger = Logger
.getLogger(ANSNotificationDispatcher.class);
public static final String OS_NAME = AppConstants.OS_TYPE_IPHONE;
String keystore;
String password;
boolean production;
public ANSNotificationDispatcher() {
try {
keystore = AppConfig.getAPNKeystore();
password = AppConfig.getAPNKeystorePassword();
PushyAPNMgr.init(keystore, password, AppConfig.isAPNProdcution());
} catch (Throwable e) {
e.printStackTrace();
}
}
private void push(Payload payload, String token, String userId,
String deviceId) throws ConfigurationException,
DeviceUnregisteredException {
// QueueManager.addToIOsQueue(payLoad, token, userId, ivUserDeviceId);
long stime = System.currentTimeMillis();
try {
PushyAPNMgr.push(token, payload.toString());
if (logger.isInfoEnabled())
logger.info("push(): APN PN userId [" + userId
+ "], device id [" + deviceId + "] payoad [" + payload
+ "] Response time ["
+ (System.currentTimeMillis() - stime) + "]ms");
} catch (Exception e) {
e.printStackTrace();
throw new ConfigurationException();
}
}
public static Payload createComplexPayload(JSONObject jsonObject) {
PushNotificationPayload complexPayload = null;
try {
complexPayload = createPayload(jsonObject);
String msg = Common.getStringAsNull(jsonObject,
AppConstants.FLD_MSG);
if (!Common.isEmpty(msg)) {
complexPayload.addCustomDictionary(AppConstants.FLD_MSG, msg);
}
if (logger.isInfoEnabled()) {
logger.info("createComplexPayloadV2(): payload ["
+ complexPayload.getPayload().toString() + "]");
}
} catch (JSONException e) {
e.printStackTrace();
}
return complexPayload;
}
public void dispatch(JSONObject jsonObject, String jsonData)
throws NotificationException, DeviceUnregisteredException,
MultipleRegistartionIdException, ConfigurationException {
String deviceToken = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_TOKEN);
if (Common.isEmpty(deviceToken)) {
logger.error("dispatch(): device token is null, cmd [" + jsonData
+ "]");
return;
}
Payload payload = createComplexPayload(jsonObject);
String userId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_USER_ID);
String deviceId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_ID);
push(payload, deviceToken, userId, deviceId);
}
public static void handleInvalidTokeException(String token) {
}
public static void handleDeviceUnregisteredException(String token) {
}
}
Ios push notification managed by Ios OS
My Apache Catalina log
I am a web service cloud developer faceing this issue last one days for only Ios app. So please, if some body have knowledge or done before. please advise and refer me some idea.
Emoji in my push notifications link.
https://mixpanel.com/help/questions/articles/how-do-i-send-custom-parameters-like-emoji-in-my-push-notifications
Thanks
Finally, APNs issue resolve in (Ios app) on java web service code by this Unicode encode and decode process. (unescapeJava and escapeJava) from lib commons-lang-2.6.jar and class org.apache.commons.lang.StringEscapeUtils
emojiBytes = alertMsg.getBytes("UTF-8"); text = new String(emojiBytes, "UTF-8");
private static PushNotificationPayload createPayload(JSONObject jsonObject)
throws JSONException {
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
byte[] emojiBytes=null;
String text=null;
try {
emojiBytes = alertMsg.getBytes("UTF-8");
text = new String(emojiBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String emojiAsString = new String(emojiBytes, Charset.forName("UTF-8"));
//System.out.println("#####alertMsg: "+text);
Integer badgeCnt;
if (jsonObject.has(AppConstants.FLD_BADGE_CNT)){
badgeCnt = Common.getIntegerAsNull(jsonObject,
AppConstants.FLD_BADGE_CNT);
}else{
badgeCnt = AppConstants.VAL_ZERO;
}
PushNotificationPayload payload = createPayload(badgeCnt, text);
return payload;
}
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
public static String getStringUnicodeAsNull1(JSONObject jsonObject,
String key) {
try {
if(jsonObject.isNull(key))
return null;
else
return StringEscapeUtils.unescapeJava(jsonObject.getString(key));
} catch (JSONException je) {
return null;
}
}
Respected sir and ma'am, If there is any other solution of java APNs emoji Unicode on IOS Push Notification.
Then please give me some hints.Thanks
you shouldn't need to mess about with html decoding. As you say the code point for smiling face is \u263A. In PHP you can represent that in a UTF8-encoded string as "\xE2\x98\xBA"
Lightning bolt (actually 'high voltage sign') is \u26A1 or "\xE2\x9A\xA1" in UTF-8.
Both these characters are present in some non-emoji fonts as regular Unicode symbols. You can see with:
<?php
header('Content-type: text/html; charset=utf-8');
echo "\xE2\x9A\xA1";
echo "\xE2\x98\xBA";
or other things...
for the googlers. json_encode() adds double \
$message = "\ue04a";
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'type' => $type,
'param' => $param
);
$payload = json_encode($body);
$payload = str_replace("\", "\\", $payload);
Please check with this two way... i think this is helpfull for you.

Thread contention in Asynctask

I'm having a thread contention issue when my program gets to executing an asynctask whose current purpose is to connect to an ftp server and based on a successful connection then make a get HTTP parsing request in order to access JSON data I need to write into a local SQLite database.
I'm slightly new in understanding thread contention but having read around particulalry this article I suspect it is a deadlock.
Below is my debug window which is called when I run my app. I'm doing so on a device and not an emulator:
Below is the asynctask code:
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(AllProductsActivity.this);
//pDialog.setMessage("Loading products. Please wait...");
Log.i("LoadAllProducts", "LoadAllProducts - Loading products. Please wait...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.i("LoadAllProducts", "URL: " + url_all_products);
ftpConnectLoginAndUpload = new FTPConnectLoginAndUpload();
if(ftpConnectLoginAndUpload.execute()) {
// Check your log cat for JSON response
Log.d("LoadAllProducts ", "About to execute JSONObject json = jParser.makeHttpRequest(url_all_products, \"GET\", params);");
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON response
Log.d("LoadAllProducts ", json.toString());
/*try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS); // products is a variable holding the value from the 2nd key-value pairing.
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String price = c.getString("price");
String created_at = c.getString("created_at");
String updated_at = c.getString("updated_at");
Log.d("LoadAllProducts ", "JSON item var i.e. id:" + id);
Log.d("LoadAllProducts ", "JSON item var i.e. name:" + name);
Log.d("LoadAllProducts ", "JSON item var i.e. price:" + price);
Log.d("LoadAllProducts ", "JSON item var i.e. created_at:" + created_at);
Log.d("LoadAllProducts ", "JSON item var i.e. updated_at:" + updated_at);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}*/
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
Log.i("LoadAllProducts", "LoadAllProducts - dismiss the dialog after getting all products");
// updating UI from Background Thread
/*runOnUiThread(new Runnable() {
public void run() {
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});*/
}
}
Below is the FTP log in code:
//!< FTP Connect, Login And Upload
public class FTPConnectLoginAndUpload {
//!<
private void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("---> showServerReply(FTPClient ftpClient) - SERVER: " + aReply);
}
}
}
//!<
public boolean execute() {
// Boston's FTP login credentials
String server = "XX.XXX.XXX.XX";
int port = 21;
String user = "XXXXXXXX_XXXXXX";
String pass = "XXXXXXXX";
// Time out period after connection attempt
int timeOut = 5000;
boolean ftpResult;
// FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server
// This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface
FTPClient ftpClient = new FTPClient();
// Execute FTP process
try {
// Set connection timeout in milliseconds
ftpClient.setConnectTimeout(timeOut);
// Sets the timeout in milliseconds to use when reading from the data connection.
ftpClient.setDataTimeout(timeOut);
// Connect using provided server and port numb
ftpClient.connect(server, port);
System.out.println("\n---> ftpClient.connect(server, port) has been executed.\n---> Server used was "
+ server + " and port number used was: " + port);
System.out.println("\n---> ftpClient.getReplyString() returns: " + ftpClient.getReplyString());
// Returns server reply
System.out.println("\n---> Server reply is as follows:");
showServerReply(ftpClient);
System.out.println("---> End of server reply");
// Get server reply code
int replyCode = ftpClient.getReplyCode();
System.out.println("\n---> ftpClient replyCode is: " + replyCode);
// Determine if a reply code is a positive completion response. All codes beginning with a 2 are positive completion responses.
// The FTP server will send a positive completion response on the final successful completion of a command.
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("\n---> Operation failed. Server reply code: " + replyCode);
ftpResult = false;
return ftpResult;
} else {
System.out.println("\n---> Operation successful. Server reply code: " + replyCode);
// Attempt login
boolean success = ftpClient.login(user, pass);
System.out.println("\n---> ftpClient.login(user, pass); has been called.");
// Determine log in success
if (!success) {
System.out.println("\n ---> Unable to login to the server");
ftpResult = false;
return ftpResult;
} else {
System.out.println("\n---> Successfully logged into server");
ftpResult = true;
}
//
ftpClient.enterLocalPassiveMode();
// Show server reply after logging in
System.out.println("\n---> Server response after logging in is as follows:");
showServerReply(ftpClient);
System.out.println("---> End of server response after logging");
return ftpResult;
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
ftpResult = false;
return ftpResult;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
ftpResult = false;
return ftpResult;
}
} catch (IOException ex) {
ex.printStackTrace();
ftpResult = false;
return ftpResult;
}
}
}
}

Categories