How to Retrieve Data from Node Server With Socket? - java

i've got problem getting data from Node server, i've searching many reference from internet, but i haven't found one yet that can solve my problem.
this is my node server
var socket = require('socket.io');
var express = require('express');
var app = express();
/*
var options = {
key: fs.readFileSync('cert/file.key'),
cert: fs.readFileSync('cert/file.crt')
};
var server = require('https').createServer(options, app);
*/
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
//server.listen(port, '103.126.57.4', function () {
server.listen(port, function () {
console.log('Server listening at port %d', port);
//console.log('Server listening at port %d', port, server.address());
});
io.on('connection', function (socket) {
console.log( "New client connected !" );
//console.log(socket.handshake.headers.host);
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'new_chat_kelas', function( data ) {
io.sockets.emit( data.tabelchat, {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'change_chat_status', function( data ) {
io.sockets.emit( 'change_status'+data.tabelchat, {
status: data.status
});
});
/*
socket.on('disconnect', function () {
console.log( "Client disconnected !" );
});
*/});
And this is my Android code
try {
//if you are using a phone device you should connect to same local network as your laptop and disable your pubic firewall as well
socket = IO.socket("http://192.168.100.13:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
refreshChat(url);
getTabelKelas();
getDiskusiChat(sharedDiskusi.getSpdiskusi());
private void getDiskusiChat(String tabelChat) {
socket.on(tabelChat, new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String jsonStr = data.toString();
Log.d("cek", "cek data : "+data);
Toast.makeText(mContext, (CharSequence) data, Toast.LENGTH_LONG).show();
try {
//extract data from fired event
String cek = String.valueOf(data.getJSONArray("idleveluser"));
// String nickname = data.getString("senderNickname");
// String message = data.getString("message");
// make instance of message
//
// Message m = new Message(nickname,message);
// Message m = new Message(nickname,message);
//
//
// //add the message to the messageList
//
// MessageList.add(m);
//
// // add the new updated list to the dapter
// chatBoxAdapter = new ChatBoxAdapter(MessageList);
//
// // notify the adapter to update the recycler view
//
// chatBoxAdapter.notifyDataSetChanged();
//
// //set the adapter for the recycler view
//
// myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
i have try to Toast and log it but did not appear.
Can anyone help me to retrieve data ?I confuse how to get data if the data in the form of an array. I'm helped if someone helps me.
Sry for my bad english brother.
This is my log

Change this code line
String cek = String.valueOf(data.getJSONArray("idleveluser"));
to
String cek = String.valueOf(data.getString("idleveluser"));
as each item in the data object is a string.

Related

How I can replay to WhatsApp notification from java code in android studio

Hello guys I'm using NotificationListenerService to get WhatsApp messages
But now I have a problem that I don't know how to replay to WhatsApp notifications
So here is the code and how I'm getting WhatsApp notifications but my problem is in how actually to replay on them
public class NotificationListener extends NotificationListenerService {
// StaticFields:
public static final String WHATSAPP_PACKAGE_NAME = "com.whatsapp";
// TAGS:
private static final String TAG = "NotificationListener";
private static final String NP_FIELD = "onNotificationPosted: ";
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
// Fields:
ARPreferencesManager manager = new ARPreferencesManager(getApplicationContext());
String currentPackages = manager.getStringPreferences(ARPreferencesManager.PACKAGE_APP_NAME);
List<Chat.Messages> messages = new ArrayList<>();
// CheckingStatusBarNotification:
if (sbn.getPackageName().equals(WHATSAPP_PACKAGE_NAME)) {
// Initializing(DateTime):
String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date());
List<Chat> chats;
// Initializing(Data):
String sender = sbn.getNotification().extras.getString(Notification.EXTRA_TITLE);
String msg = sbn.getNotification().extras.getString(Notification.EXTRA_TEXT);
String currentSenders = manager.getStringPreferences(ARPreferencesManager.SENDER_NAME);
// AddingData:
messages.add(new Chat.Messages(msg));
// Developing:
if (manager.getPreferences().contains(ARPreferencesManager.WHATSAPP_CHATS)) {
// Initializing:
chats = ARUtils.fromJsonToChats(manager.getStringPreferences(ARPreferencesManager.WHATSAPP_CHATS));
// Developing:
for (Chat chat : chats) {
if (chat.getSender().equals(sender)) {
// AddingTheNewMessage:
chat.getMessages().addAll(messages);
// AddingSender($Preferences):
if (!currentSenders.contains(sender)) {
// Initializing:
manager.setStringPreferences(ARPreferencesManager.SENDER_NAME, sender + ",");
// Refreshing:
currentSenders = manager.getStringPreferences(ARPreferencesManager.SENDER_NAME);
}
}
}
// CheckingSenders:
if (!currentSenders.contains(sender)) {
// Initializing:
Chat chat = new Chat(sender, "", date, null, messages);
// AddingTheNewChat:
chats.add(chat);
}
} else {
// Initializing:
chats = new ArrayList<>();
// Developing:
chats.add(new Chat(sender, "", date, null, messages));
}
// SettingPreferences:
manager.setStringPreferences(ARPreferencesManager.WHATSAPP_CHATS, ARUtils.fromChatsToJson(chats));
// Debugging:
ARUtils.debug(TAG, NP_FIELD, manager.getStringPreferences(ARPreferencesManager.WHATSAPP_CHATS));
}
// Debugging:
ARUtils.debug(TAG, NP_FIELD, "Whatsapp Package Was Founded In Preferences");
// Debugging:
ARUtils.debug(TAG, NP_FIELD, "Start");
}
}
Did you try using this function?
fun reply(action: Notification.Action, message: String, exception: Exception.() -> Unit = {}) {
try {
val sendIntent = Intent()
val msg = Bundle()
for (inputable in action.remoteInputs) {
msg.putCharSequence(inputable.resultKey, message)
}
RemoteInput.addResultsToIntent(action.remoteInputs, sendIntent, msg)
action.actionIntent.send(applicationContext, 0, sendIntent)
} catch (exception: Exception) {
exception(exception)
}
}
You can get Notification.Action for this way:
override fun onNotificationPosted(sbn: StatusBarNotification) {
super.onNotificationPosted(sbn)
val wExt = Notification.WearableExtender(sbn.notification)
for (action in wExt.actions) {
...

Kotlin BufferReader is not getting Server response

I'm really new in Kotlin.
I have two application one is Client in Android emulator and one is in Windows Form Application Server (My server is Using SimpleTCP library in C#) .
Here is the Server Code:
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13;
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
messageList.Text += "Server starting...";
server.Start("192.168.1.7", 5000);
messageList.Text += "\r\n Server started...";
}
private void Server_DataReceived(object sender, SimpleTCP.Message e)
{
messageList.Invoke((MethodInvoker)delegate ()
{
messageList.Text += string.Format("\r\n Client Message: {0} \n ", e.MessageString);
});
e.ReplyLine("Hello from Server");
}
I'm communicating via localhost. I can send request and Server can get this request without problem but when i try to get response from Server unfortunately cannot receive response.
val message = input!!.readLine() is always returning null
Can you help me why i cannot do this?
Here my code
var thread: Thread? = null
var etIP: EditText? = null
var etPort: EditText? = null
var tvMessages: TextView? = null
var etMessage: EditText? = null
var btnSend: Button? = null
var SERVER_IP: String? = null
var SERVER_PORT = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
etIP = findViewById(R.id.etIP)
etPort = findViewById(R.id.etPort)
tvMessages = findViewById(R.id.tvMessages)
etMessage = findViewById(R.id.etMessage)
btnSend = findViewById(R.id.btnSend)
val btnConnect: Button = findViewById(R.id.btnConnect)
btnConnect.setOnClickListener {
tvMessages!!.text = ""
SERVER_IP = etIP!!.text.toString().trim { it <= ' ' }
SERVER_PORT = etPort!!.text.toString().trim { it <= ' ' }.toInt()
thread = Thread(Thread1())
thread!!.start()
}
btnSend!!.setOnClickListener {
val message = "Android!"+etMessage!!.text.toString().trim { it <= ' ' }
if (!message.isEmpty()) {
Thread(Thread3(message)).start()
}
}
}
private var output: PrintWriter? = null
private var input: BufferedReader? = null
internal inner class Thread1 : Runnable {
override fun run() {
val socket: Socket
try {
socket = Socket(SERVER_IP, SERVER_PORT)
output = PrintWriter(socket.getOutputStream())
input = BufferedReader(InputStreamReader(socket.getInputStream()))
runOnUiThread(Runnable { tvMessages!!.text = "Connected\n" })
Thread(Thread2()).start()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
internal inner class Thread2 : Runnable {
override fun run() {
while (true) {
try {
val message = input!!.readLine().toString()
run {
runOnUiThread(Runnable { tvMessages!!.append("server: $message\n") })
}
run {
thread = Thread(Thread1())
thread!!.start()
return
}
} catch (e: Exception) {
tvMessages!!.text = e.toString()
}
}
}
}
internal inner class Thread3(private val message: String) : Runnable {
override fun run() {
output!!.write(message)
output!!.flush()
runOnUiThread(Runnable {
tvMessages!!.append("client: $message\n")
tvMessages!!.setMovementMethod(ScrollingMovementMethod())
etMessage!!.setText("")
})
}
}
fun clearAll(view: View){
tvMessages!!.text = ""
}

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