How to handle add request in smack API - smack

I use Smack API to write my Google talk Client . Now i need to handle add request for this .
I set SubscriptionMode to manual & now I have to registering a listener for presence packets but i don't know how !!
can any body help ?

I have not tried it yet, but I guess the below should work. If using the manual mode, a PacketListener should be registered that listens for Presence packets that have a type of Presence.Type.subscribe.
First set the roster:
Roster roster = connection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
Then add a packet listner to the above connection, eg :
connection.addPacketListener(new SubscriptionListener(), new PacketFilter(){
public boolean accept(Packet packet) {
if(packet instanceof Presence)
if(((Presence)packet).getType().equals(Presence.Type.subscribe))
return true;
return false;
}});
The above code just returns true for all requests, But you can customize it i.e set it to true or false based on user GUI input.

public static void admitFriendsRequest() {
connection.getRoster().setSubscriptionMode(
Roster.SubscriptionMode.manual);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet paramPacket) {
System.out.println("\n\n");
if (paramPacket instanceof Presence) {
Presence presence = (Presence) paramPacket;
String email = presence.getFrom();
System.out.println("chat invite status changed by user: : "
+ email + " calling listner");
System.out.println("presence: " + presence.getFrom()
+ "; type: " + presence.getType() + "; to: "
+ presence.getTo() + "; " + presence.toXML());
Roster roster = connection.getRoster();
for (RosterEntry rosterEntry : roster.getEntries()) {
System.out.println("jid: " + rosterEntry.getUser()
+ "; type: " + rosterEntry.getType()
+ "; status: " + rosterEntry.getStatus());
}
System.out.println("\n\n\n");
if (presence.getType().equals(Presence.Type.subscribe)) {
Presence newp = new Presence(Presence.Type.subscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
Presence subscription = new Presence(
Presence.Type.subscribe);
subscription.setTo(presence.getFrom());
connection.sendPacket(subscription);
} else if (presence.getType().equals(
Presence.Type.unsubscribe)) {
Presence newp = new Presence(Presence.Type.unsubscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
if (packet instanceof Presence) {
Presence presence = (Presence) packet;
if (presence.getType().equals(Presence.Type.subscribed)
|| presence.getType().equals(
Presence.Type.subscribe)
|| presence.getType().equals(
Presence.Type.unsubscribed)
|| presence.getType().equals(
Presence.Type.unsubscribe)) {
return true;
}
}
return false;
}
});
connection.getRoster().addRosterListener(new RosterListener() {
public void presenceChanged(Presence presence) {
System.out.println(presence.getFrom() + "presenceChanged");
}
public void entriesUpdated(Collection<String> presence) {
System.out.println("entriesUpdated");
}
public void entriesDeleted(Collection<String> presence) {
System.out.println("entriesDeleted");
}
public void entriesAdded(Collection<String> presence) {
System.out.println("entriesAdded");
}
});
}

Related

How to update pin information on google map using xamarin

It is necessary to replace the direct connection to the database with API.
I use this code to directly connect to MySQL db and change pin information:
public async void DatabaseConnection(List<CustomPin> pins)
{
string ConnectionString = "server=192.168.0.1;uid=user;port=4444;pwd=pass;database=dbName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
try
{
Conn.Open();
string query = "SELECT * FROM sel_alert_level s;";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
int codeNum = myReader.GetInt32(4);
int level = myReader.GetInt32(3);
int mapCode = myReader.GetInt32(0);
foreach (var item in pins)
{
if (item.CodeNum == codeNum)
{
item.AlertLevel = level;
item.CodeNum = codeNum;
item.MapCode = mapCode;
//await DisplayAlert("Alert", mapCode.ToString(), "ok");
}
}
//await DisplayAlert("Database Connection", "Connected .." + Environment.NewLine + myReader.GetInt32(0) + Environment.NewLine + myReader.GetString(1) + Environment.NewLine + myReader.GetString(2) + Environment.NewLine + myReader.GetInt32(3) + Environment.NewLine + myReader.GetInt32(4), "OK");
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
await DisplayAlert("Database Connection", "Not Connected ..." + Environment.NewLine + ex.ToString(), "OK");
}
}
With this code I successfully update the pin information.
Now I create the same method with API Response and what to do the same like DatabaseConnection(); just try to update the information, but not work for me :(
public async void APIConnection(List<CustomPin> pins)
{
try
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var water in waterData.WaterStation.Stations)
{
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = water.AlertLevelStation;
item.CodeNum = water.CodeNum;
item.MapCode = water.MapCode;
}
}
}
}
catch (Exception ex)
{
await DisplayAlert("Data Alert", "Error:" + Environment.NewLine + ex.ToString(), "OK");
}
}
I not have any errors here. waterData come with the data, but data not changed in the pins.. I don't know why...
And Now my information are not changed ..
MapCode and other variables not changed.
I call this two methods in the constructor like that:
DatabaseConnection(customMap.CustomPins);
APIConnection(customMap.CustomPins);
So... When I start the project I receive message like this:
/Applications/Visual Studio.app/Contents/Resources/lib/monodevelop/bin/MSBuild/Current/bin/Microsoft.Common.CurrentVersion.targets(5,5): Warning MSB3276: Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects" property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190. (MSB3276) (MaritsaTundzhaForecast.iOS)
And I check this link but I not have properties option, because I use mac. I have only options on the projects.
Is it possible that this does not change the content in the pins аnd what would be the reason it didn't work ?
I checked the if statement in the loop and she work:
Since it is an asynchronous method , I suggest you try to assign customMap.CustomPins in APIConnection method .
Something like that
//constructor
List<CustomPin> pins = xxxxx;
APIConnection(pins);
public async void APIConnection(List<CustomPin> pins)
{
try
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var water in waterData.WaterStation.Stations)
{
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = water.AlertLevelStation;
item.CodeNum = water.CodeNum;
item.MapCode = water.MapCode;
}
}
}
customMap.CustomPins = pins; //assign the value in this line
}
catch (Exception ex)
{
await DisplayAlert("Data Alert", "Error:" + Environment.NewLine + ex.ToString(), "OK");
}
}

Is it possible to switch wifi networks in Appium?

While executing my test suite I have to switch between different wifi networks available in Android Device.
In the middle of the execution I have to change my wifi connection from Wifi_Network_1 to Wifi_Network_2 provided ssid name and password of wifi network is known. How can it be done?
I am using:
Appium server -->1.8.1
java-client --> 6.1.0
selenium-java --> 3.13.0
Since NetworkConnectionSetting has been deprciated, I am not able to find alternate for it.
I can toggle wifi on/off using
driver.toggleWifi();
But it is not suitable for my case as i need to toggle between different wifi network available using SSID name and its password.
Thanks in advance.
Hi I'am using this method due Appium deprecated their switch for wifi, and I've created my own override via console via commands from adb. It is working for me so give it a try:
public synchronized boolean wifiSetup(String udid, boolean flg) {
synchronized (this) {
String flgEnabled = (flg) ? "enable" : "disable";
List<String> output = Console.runProcess(false, "adb -s " + udid + " shell am broadcast -a io.appium.settings.wifi --es setstatus " + flgEnabled);
for (String line : output) {
System.err.println(line);
if (line.equalsIgnoreCase("Broadcast completed: result=-1"))
return true;
}
return false;
}
}
usage to switch off:
wifiSetup("xxxUDIDfromAndroid", false);
usage to switch on:
wifiSetup("xxxUDIDfromAndroid", true);
And here is part for calling console:
public class Console {
private static final String[] WIN_RUNTIME = { "cmd.exe", "/C" };
private static final String[] OS_LINUX_RUNTIME = { "/bin/bash", "-l", "-c" };
private Console() {
}
private static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
#SuppressWarnings({ "hiding"})
private static <String> String[] concatStr(String[] first, String[] second) {
String[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public static List<String> runProcess(boolean isWin, String... command) {
String[] allCommand = null;
try {
if (isWin) {
allCommand = concat(WIN_RUNTIME, command);
} else {
allCommand = concat(OS_LINUX_RUNTIME, command);
}
ProcessBuilder pb = new ProcessBuilder(allCommand);
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String _temp = null;
List<String> line = new ArrayList<String>();
while ((_temp = in.readLine()) != null) {
// system.out.println("temp line: " + _temp);
line.add(_temp);
}
// system.out.println("result after command: " + line);
return line;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Hope this helps,

org.apache.commons.net.ftp hangs timeout

I am in trouble with org.apache.commons.net.ftp.
My client need to detect timeout when uploading (Timeout for downloads works like a charm)
if i unplugged the network cable or switch off the adsl, upload hangs and timeouts are not working. I have made several test but nothing works, it's going to make me crazy
this is my code :
public boolean uploadFile2(String localFile, String serverFile) {
try {
InputStream stO = new FileInputStream(localFile);
OutputStream stD = storeFileStream(serverFile);
setDataTimeout(dataTimeOut);
Util.copyStream(stO, stD, getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE, new CopyStreamAdapter() {
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
System.out.println("On transfert " + "/" + totalBytesTransferred + "/" + bytesTransferred + "/" + streamSize);
}
});
completePendingCommand();
} catch (Exception e) {
}
return false;
}
public boolean connectAndLogin(String host, String userName, String password) throws IOException, UnknownHostException,
FTPConnectionClosedException {
boolean success = false;
setDefaultTimeout(this.defaultTimeOut);
setConnectTimeout(this.connectionTimeOut);
addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
setPassiveMode(true);
connect(host);
int reply = getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
success = login(userName, password);
setKeepAlive(true);
setControlKeepAliveTimeout(keepAliveTimeout);
setControlKeepAliveReplyTimeout(keepAliveResponseTimeout);
setSoTimeout(soTimeOut);
setDataTimeout(dataTimeOut);
setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
setFileType(FTP.BINARY_FILE_TYPE);
}
if (!success) {
disconnect();
}
return success;
}
Any help would be appreciated, thanks
and this does not work either:
FileInputStream in = new FileInputStream(localFile);
boolean result = storeFile(serverFile, in);
in.close();
return result;

Incoming sms listener on blackberry

i've used below code for notify the sms .
Its working on two blackberry simulator.
I've install the app on my device and send sms from android device.
The sms listener not working on device.
Incoming message received on device. but my app not notify the listener .
What is the problem how to resolve it.
What port number need to give for device?
class BackgroundApplication extends Application implements MessageListener
{
int i=0;
static String suffix;
MessageConnection _mc ;
public BackgroundApplication()
{
try {
_mc = (MessageConnection)Connector.open("sms://:0");
_mc.setMessageListener(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void notifyIncomingMessage(MessageConnection conn) {
try {
Message m = _mc.receive();
String address = m.getAddress();
String msg = null;
if ( m instanceof TextMessage )
{
TextMessage tm = (TextMessage)m;
msg = tm.getPayloadText();
}
else if (m instanceof BinaryMessage) {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) m).getPayloadData();
// convert Binary Data to Text
msg = new String(data, "UTF-8");
}
else
System.out.println("Invalid Message Format");
System.out.println("Received SMS text from " + address + " : " + msg);
showDialog("Msg: "+msg);
} catch (Exception e) {
// TODO: handle exception
}
}
private void showDialog(String string) {
synchronized (UiApplication.getEventLock())
{
Status.show(""+string,Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), 5000,
Status.GLOBAL_STATUS, true, false, 1);
}
}
}
Check this
http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-listen-for-SMS-messages/ta-p/445062
DatagramConnection _dc =
(DatagramConnection)Connector.open("sms://");
for(;;)
{
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
byte[] bytes = d.getData();
String address = d.getAddress();
String msg = new String(bytes);
System.out.println( "Received SMS text from " + address + " : " + msg);
}

IOException Radio is off, and Out of memory, on BlackBerry

I am performing HttpConnection in my RIM Blackberry application. I am using wi-fi connection. While performing HttpConnection sometimes it is returning data, sometimes it is giving
java.io.IOException Radio is off
and
java.io.IOException Out of memory
errors. I really do not understand what is the issue exactly. I am posting here my code snippets:
public static String getRemoteData(String url) throws ConnectionNotFoundException{
StringBuffer stringBuff=new StringBuffer();
try {
HttpConnection fconImg = (HttpConnection) Connector.open(url+ NetworkUtils.getConnectionString());
InputStream input = fconImg.openInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int k = 0;
while ((k = input.read()) != -1) {
baos.write(k);
}
byte[] byteArray = baos.toByteArray();
String s = new String(byteArray);
stringBuff.append(s.trim());
return stringBuff.toString();
} catch (Exception e) {
stringBuff.append("Exception : "+e.toString());
return stringBuff.toString();
}
}
And below is my NetworkUtils Class.
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;
public class NetworkUtils {
private static final String COVERAGE_CARRIER = "Carrier full Coverage";
private static final String COVERAGE_MDS = "BES coverage";
private static final String COVERAGE_NONE = "No coverage";
private static final String NOT_SUPPORTED_WAF = "Not supported by the device";
public static String logM;
/**
* Access the net.rim.device.api.system.DeviceInfo class in order to
* understand if the running system is a simulator or a real device.
* #return true if the current application is running on a Blackberry
* simulator, false otherwise
*/
public static boolean isSimulator() {
return DeviceInfo.isSimulator();
}
/**
* Give the information about the presence o a wifi bearer on the device
* #return true if the wifi communication interface bearer is supported by
* the device, false otherwise
*/
protected static boolean isWifiAvailable() {
// Log.info("Checking WIFI Availability");
boolean isWifiEnabled;
if (RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
// Log.info("WIFI Supported");
isWifiEnabled = true;
} else {
// Log.info("WIFI NOT Supported");
isWifiEnabled = false;
}
return isWifiEnabled;
}
/**
* Give information about the presence of active wifi connections.
* #return true if the device is connected to a wifi network with its wifi
* bearer, false otherwise
*/
protected static boolean isWifiActive() {
int active = RadioInfo.getActiveWAFs();
int wifi = RadioInfo.WAF_WLAN;
return active >= wifi;
}
protected static boolean isWapGprsDataBearerOffline() {
return RadioInfo.getState()==RadioInfo.STATE_OFF ||
RadioInfo.getSignalLevel() == RadioInfo.LEVEL_NO_COVERAGE;
}
public static String getNetworkCoverageReport() {
StringBuffer sb = new StringBuffer();
sb.append("\n*********************************************************");
sb.append("\nWireless Access Families:");
sb.append("\n3GPP: " + getNetworkCoverage(RadioInfo.WAF_3GPP));
sb.append("\nCDMA: " + getNetworkCoverage(RadioInfo.WAF_CDMA));
sb.append("\nWLAN: " + getNetworkCoverage(RadioInfo.WAF_WLAN));
sb.append("\nCDMA: " + getNetworkCoverage(RadioInfo.NETWORK_CDMA));
sb.append("\nBands:");
sb.append("\nCDMA_800: " + getNetworkCoverage(RadioInfo.BAND_CDMA_800));
sb.append("\nCDMA_1900: " + getNetworkCoverage(RadioInfo.BAND_CDMA_1900));
sb.append("\nNetworks:");
sb.append("\n802_11: " + getNetworkCoverage(RadioInfo.NETWORK_802_11));
sb.append("\nGPRS: " + getNetworkCoverage(RadioInfo.NETWORK_GPRS));
sb.append("\nNetwork services:");
sb.append("\nVOICE: " + getNetworkCoverage(RadioInfo.NETWORK_SERVICE_VOICE));
sb.append("\nUMTS: " + getNetworkCoverage(RadioInfo.NETWORK_SERVICE_UMTS));
sb.append("\nEDGE: " + getNetworkCoverage(RadioInfo.NETWORK_SERVICE_EDGE));
sb.append("\n*********************************************************");
return sb.toString();
}
private static String getNetworkCoverage(int networkType) {
if (RadioInfo.areWAFsSupported(networkType)) {
int status = CoverageInfo.getCoverageStatus(networkType, false);
switch (status) {
// case CoverageInfo.COVERAGE_DIRECT: //TODO if we switch back to < 4.5 we must use CARRIER
// return COVERAGE_CARRIER;//not support less ver of 4.5
case CoverageInfo.COVERAGE_MDS:
return COVERAGE_MDS;
case CoverageInfo.COVERAGE_NONE:
return COVERAGE_NONE;
default:
break;
}
}
return NOT_SUPPORTED_WAF;
}
public static boolean isDataConnectionAvailable() {
boolean ret = (isWifiAvailable()&&isWifiActive())||!isWapGprsDataBearerOffline();
return ret;
}
/**
* Determines what connection type to use and returns the necessary string to use it.
* #return A string with the connection info
*/
public static String getSubURL()
{
// This code is based on the connection code developed by Mike Nelson of AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable.
if(DeviceInfo.isSimulator())
{
logMessage("Device is a simulator and USE_MDS_IN_SIMULATOR is false");
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
logMessage("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}else{
String uid = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null &&
records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null) {
// WAP2 Connection
connectionString = ";ConnectionUID="+uid;
} else {
connectionString = ";deviceside=true";
}
}
return connectionString + ";ConnectionTimeout=60000";
}
/**
* Looks through the phone's service book for a carrier provided BIBS network
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for(currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if(records[currentRecord].getCid().toLowerCase().equals("ippp"))
{
if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
return records[currentRecord].getUid();
}
}
}
return null;
}
public static void logMessage(String str)
{
logM=str;
}
public synchronized static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
}
Thanks very much in advance....
I don't know if it's the problem but you are not closing your ByteArrayOutputStream (call baos.close() ) before calling .toByteArray()

Resources