How to add a friend using smack? - java

I wonder how to confirm a request of adding friends.
Smack Version 4.1.1
As I know now ,
roster = Roster.getInstanceFor(con);
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
roster.createEntry(targetUser, nickname, new String[] {"friends"});
will create a roster in the database, and send a stanza request to the targetUser.
And my stanza listener is as follows:
StanzaListener callback = new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws NotConnectedException {
// TODO Auto-generated method stub
String head = con.getUser() + " : ";
System.out.println(head + "Got the presence stanza");
if(((Presence)stanza).getType().equals(Presence.Type.subscribe)) {
Presence subscribed = new Presence(Presence.Type.subscribed);
subscribed.setTo(stanza.getFrom());
System.out.println(head + subscribed.getFrom());
subscribed.setFrom(stanza.getTo());
con.sendStanza(subscribed);
if( ! roster.contains(stanza.getFrom())) {
System.out.println(head + "Friend added.");
addFriend(stanza.getFrom(),"computer");
}
} else {
System.out.println(head + "Subscribed received from " + stanza.getFrom());
if(roster.contains(stanza.getFrom())) {
System.out.println(head + "OK");
}
}
}
};
It does not work, I wonder when the targetUser receives the stanza request , how to send a callback presence(or something else) to confirm or approve or agree?
How to add a friend?

Try this:
public void addFriend(User usuario) {
if (APDApplication.connection != null && APDApplication.connection.isConnected()) {
try {
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
Roster roster = Roster.getInstanceFor(APDApplication.connection);
if (!roster.contains(usuario.getChatId())) {
roster.createEntry(usuario.getChatId() + "#jabber/Smack", usuario.getName(), null);
} else {
logManager.error("Contacto ya existente en la libreta de direcciones");
}
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this helps you!!

Related

JAVA Telegram bots api Error getting updates: Conflict: terminated by other long poll or webhook

I am using JAVA Telegram Bot API with Spring framework , I had a method in my HomeController and i had a class that handle all of the incoming messages from users. I got these errors in my spring log,then i got duplicated response from telegram bot API .whats is the problem ?
#PostConstruct
public void initBots() {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
BotService botService = new BotService();
try {
botsApi.registerBot(botService);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
[abrsystem1_bot Telegram Connection] org.telegram.telegrambots.logging.BotLogger.severe
BOTSESSION
org.telegram.telegrambots.exceptions.TelegramApiRequestException:
Error getting updates: [409] Conflict: terminated by other long poll
or webhook at
org.telegram.telegrambots.api.methods.updates.GetUpdates.deserializeResponse(GetUpdates.java:119)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.getUpdatesFromServer(DefaultBotSession.java:255)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.run(DefaultBotSession.java:186)
#Override
public void onUpdateReceived(Update update) {
try {
if (update.hasMessage() && update.getMessage().hasText()) {
String message_text = update.getMessage().getText();
String wellcome_text = "برای ثبت نام در سایت شماره تلفن همراه خود را به اشتراک بگذارید";
long chat_id = update.getMessage().getChatId();
if (message_text.equals("/start")) {
try {
SendMessage message = new SendMessage()
.setChatId(chat_id)
.setText(wellcome_text);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
List<KeyboardRow> keyboard = new ArrayList<KeyboardRow>();
KeyboardRow row = new KeyboardRow();
row.add((new KeyboardButton().setText("اشتراک شماره موبایل").setRequestContact(true)));
keyboard.add(row);
keyboardMarkup.setKeyboard(keyboard);
message.setReplyMarkup(keyboardMarkup);
try {
execute(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (message_text.equals("تایید مشخصات کاربری")) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chat_id).setText("اطلاعات مورد تایید قرار گرفت");
try {
execute(sendMessage);
removeMarker(chat_id);
showContactInfo(chat_id, update);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (message_text.equals("تغییر مشخصات")) {
} else {
showUnknownCommand(chat_id);
}
} else if (update.getMessage().getContact() != null && update.getMessage().getChat() != null) {
long chat_id = update.getMessage().getChatId();
showContactInfo(chat_id, update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I finally solved my problem after a day!when i was debugging my project with intellij idea on my computer , i created many instances for debug so i got multiple response from same chat id in telegram bot.so boring problem....

How to use UserSearchManager to check user has registered or not in xmpp?

I have started to develop chat application. I needed to check user has registered or not in xmpp server.So when user trying to register,I want check user has already registered or not in xmpp server. After xmpp server connected successfully,Tried to search as number using Usersearchmanager.But Getting error as
java.lang.IllegalArgumentException: Must have a local(user) JID set.Either you didn 't configure one or you where not connected at least once
at org.jivesoftware.smack.filter.IQReplyFilter. < init > (IQReplyFilter.java: 94)
at org.jivesoftware.smack.AbstractXMPPConnection.createPacketCollectorAndSend(AbstractXMPPConnection.java: 699)
at org.jivesoftware.smackx.search.UserSearch.getSearchForm(UserSearch.java: 73)
at org.jivesoftware.smackx.search.UserSearchManager.getSearchForm(UserSearchManager.java: 71)
at com.techno.samplechat.Myxmpp.searchUsers(Myxmpp.java: 335)
at com.techno.samplechat.Myxmpp$XMPPConnectionListener.connected(Myxmpp.java: 284)
at org.jivesoftware.smack.AbstractXMPPConnection.callConnectionConnectedListener(AbstractXMPPConnection.java: 1162)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java: 850)
at org.jivesoftware.smack.AbstractXMPPConnection.connect(AbstractXMPPConnection.java: 365)
at com.techno.samplechat.Myxmpp$1.run(Myxmpp.java: 117)
at java.lang.Thread.run(Thread.java: 818)
Code:
private void CreateAccount() {
org.jivesoftware.smackx.iqregister.AccountManager am = org.jivesoftware.smackx.iqregister.AccountManager
.getInstance(connection);
am.sensitiveOperationOverInsecureConnection(true);
Map < String, String > attributes = new HashMap < String, String > ();
attributes.put("username", loginUser);
attributes.put("email", "Manikandan.s#technoduce.com");
attributes.put("password", passwordUser);
attributes.put("name", UserName);
try {
if (am.supportsAccountCreation()) {
am.createAccount(
loginUser,
passwordUser,
attributes);
login();
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
private void login() {
try {
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ChatManager.getInstanceFor(connection).addChatListener(this);
}
#
Override
public void chatCreated(Chat chat, boolean createdLocally) {
Log.i("service", "chatCreated()");
System.out.println("+chatList++" + chat.getParticipant());
chat.addMessageListener(this);
}
#
Override
public void entriesAdded(Collection < String > addresses) {
}
#
Override
public void entriesUpdated(Collection < String > addresses) {
}
#
Override
public void entriesDeleted(Collection < String > addresses) {
}
#
Override
public void presenceChanged(Presence presence) {
}
#
Override
public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat || message.getType() == Message.Type.normal) {
if (message.getBody() != null) {
// Toast.makeText(this,message.getFrom() + " : " + message.getBody(),Toast.LENGTH_LONG).show();
System.out.println("++From++" + message.getFrom() + "++Body++" + message.getBody());
}
}
}
#
Override
public void pingFailed() {
}
private class XMPPConnectionListener implements ConnectionListener {
#
Override
public void connected(XMPPConnection connection) {
Log.e("success", "Connected");
try {
searchUsers(loginUser);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
// CreateAccount();
}
#
Override
public void authenticated(XMPPConnection connection, boolean resumed) {
}
#
Override
public void connectionClosed() {
}
#
Override
public void connectionClosedOnError(Exception e) {
System.out.println("+_" + e.toString());
}
#
Override
public void reconnectionSuccessful() {
}
#
Override
public void reconnectingIn(int seconds) {
}
#
Override
public void reconnectionFailed(Exception e) {
}
}
public void searchUsers(String userName) throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {
UserSearchManager search = new UserSearchManager(connection);
Form searchForm = search
.getSearchForm("search." + connection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", userName);
ReportedData data = search
.getSearchResults(answerForm, "search." + connection.getServiceName());
if (data.getRows() != null) {
for (ReportedData.Row row: data.getRows()) {
for (String value: row.getValues("jid")) {
Log.i("Iteartor values......", " " + value);
}
}
} else {
CreateAccount();
}
}
String you are looking for must to be a JID, not an username:
you need something like:
user1#myserver
and not just
user1
Then, it's quite useless in your usecase to check for JID.
I have register user using below code on smack 4.1:-
//Login User
public XMPPTCPConnection loginUser(Context objContext, XMPPTCPConnection objXmpptcpConnection, String strUsername, String strPassword) {
try {
AccountManager objAccountManager = AccountManager.getInstance(objXmpptcpConnection);
objAccountManager.createAccount(strUsername, strPassword);
objXmpptcpConnection = loginToServer(objXmpptcpConnection, strUsername, strPassword);
} catch (SmackException | XMPPException e) {
System.out.println("Msg=" + e.getMessage() + "\nCause =" + e.getCause() + "\n Local msg=" + e.getLocalizedMessage() + "\n stack=" + e.getStackTrace() + "\n class " + e.getClass());
System.out.println("Code=" + e.getStackTrace()[0].getLineNumber());
if (e.getMessage().contains("conflict")) {
objXmpptcpConnection = loginToServer(objXmpptcpConnection, strUsername, strPassword);
}
}
return objXmpptcpConnection;
}
private XMPPTCPConnection loginToServer(XMPPTCPConnection objXmpptcpConnection, String strUsername, String strPassword) {
try {
objXmpptcpConnection.login(strUsername + "#" + AppConstants.HOST, strPassword, "example");
// objXmpptcpConnection.sendPacket(new Presence(Presence.Type.unavailable));
//objXmpptcpConnection.sendPacket(new Presence(Presence.Type.available));
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("XMPPChatDemoActivity", "Logged in as "
+ objXmpptcpConnection.getUser());
Toast.makeText(
objContext,
"log in as "
+ objXmpptcpConnection.getUser(),
Toast.LENGTH_SHORT).show();
return objXmpptcpConnection;
}
Using above two methods register user to ejabberd successfully.
And Connect Method is:-
public XMPPTCPConnection connect(String strUsername, String strPassword) throws IOException, XMPPException, SmackException {
objXmpptcpConnection = null;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Create a connection
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(Constants.HOST);
config.setPort(Constants.PORT);
config.setHost(Constants.HOST);
config.setDebuggerEnabled(true);
config.setSendPresence(true);
config.setUsernameAndPassword(strUsername + "#" + Constants.HOST, strPassword);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
objXmpptcpConnection = new XMPPTCPConnection(config.build());
objXmpptcpConnection.setUseStreamManagement(true);
objXmpptcpConnection.setUseStreamManagementResumption(true);
try {
ProviderManager objProviderManager = new ProviderManager();
ProviderManager.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, new DeliveryReceiptRequest().getNamespace(), new DeliveryReceiptRequest.Provider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
// Offline Message Requests
objProviderManager.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
// Offline Message Indicator
objProviderManager.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
objXmpptcpConnection.connect();
System.out.println("Connected to===>" + objXmpptcpConnection.getHost());
objXmpptcpConnection.login();
objDeliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(objXmpptcpConnection);
objDeliveryReceiptManager.autoAddDeliveryReceiptRequests();
objDeliveryReceiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.disabled);
objDeliveryReceiptManager.addReceiptReceivedListener(this);
} catch (XMPPException e) {
e.printStackTrace();
return objXmpptcpConnection;
} catch (SmackException e) {
e.printStackTrace();
return objXmpptcpConnection;
} catch (IOException e) {
e.printStackTrace();
return objXmpptcpConnection;
}
return objXmpptcpConnection;
}
Also you want to check ejabberd side configuration also.
Its working for me tried using the answer :- Smack API User search.
Hope its useful to you.

How do you get an exception when jsoup times out?

So what I want to do is when my Jsoup connection times out I want to bring up an alert dialog. Right now it does nothing. It just skips over there error and doesn't catch a timeout exception or crash. I'm new to java so I'm not sure how to catch this sockettimeoutexception and reroute it to another method. Can someone tell me how to go to another method when jsoup time out?
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500roop").timeout(3000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
alertdialog();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
}
So I add changed the code to this and it gives me what i want:
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500").timeout(4000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
tvWaterLevel.setText("");
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
if (tvWaterLevel.length() < 1){
connectionAlarm();
}
}

How restart bluetooth service in bluecove?

I have desktop and android applications, which connected by bluetooth(in desktop side I use Bluecove 2.1.1 library). Desktop application create bluetooth service then android application connects to it. I want to add logout functionality from both desktop and android sides. For example in desktop app user click disconnect, both desktop and android apps reset their connections and should be able to connect again. Here is bluetoothService code for desktop side:
public class BluetoothService
{
private static final String serviceName = "btspp://localhost:"
// + new UUID("0000110100001000800000805F9B34F7", false).toString()
// + new UUID("0000110100001000800000805F9B34F8", false).toString()
+ new UUID("0000110100001000800000805F9B34F9", false).toString()
+ ";name=serviceName";
private StreamConnectionNotifier m_service = null;
private ListenerThread m_listenerThread;
private DataOutputStream m_outStream;
public BluetoothService()
{
Open();
}
public void Open()
{
try
{
assert (m_service == null);
m_service = (StreamConnectionNotifier) Connector.open(serviceName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void Start()
{
try
{
StreamConnection connection = (StreamConnection) m_service
.acceptAndOpen();
System.out.println("Connected");
m_listenerThread = new ListenerThread(connection);
Thread listener = new Thread(m_listenerThread);
listener.start();
m_outStream = new DataOutputStream(connection.openOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Send(String message)
{
assert (m_listenerThread != null);
try
{
m_outStream.writeUTF(message);
m_outStream.flush();
System.out.println("Sent: " + message);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Close()
{
try
{
m_service.close();
m_listenerThread.Stop();
m_listenerThread = null;
m_outStream.close();
m_outStream = null;
m_service = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ListenerThread implements Runnable
{
private DataInputStream m_inStream;
private boolean m_isRunning;
public ListenerThread(StreamConnection connection)
{
try
{
this.m_inStream = new DataInputStream(connection.openInputStream());
m_isRunning = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
;
}
public void run()
{
while (m_isRunning)
{
try
{
assert (m_inStream != null);
if (m_inStream.available() > 0)
{
String message = m_inStream.readUTF();
System.out.println("Received command: " + message);
CommandManager.getInstance().Parse(message);
}
}
catch (IOException e)
{
System.err.println(e.toString());
}
}
}
public void Stop()
{
m_isRunning = false;
try
{
m_inStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for restarting service I do:
BluetoothService::Close();
BluetoothService::Open();
BluetoothService::Start();
but seems I cannot reconnect. Maybe I should create service with different name?

passive ftp in java - why is the stream not ready

yet another java problem ...
got a client which should connect to a server via passive mode.
it seems to work fine, i get the ip adress and the port and the passivesocket says that it's ready.
but the passivesocket.getInputStream isn't ready at all - so i can't read from it and don't get the response to LIST.
can't figure out why, any suggestions?
public synchronized void getPasvCon() throws IOException, InterruptedException {
// Commands abholen
// IP Adresse holen
Thread.sleep(200);
String pasv = commands.lastElement();
String ipAndPort = pasv.substring(pasv.indexOf("(") + 1,
pasv.indexOf(")"));
StringTokenizer getIp = new StringTokenizer(ipAndPort);
// holt die IP
String ipNew = ""; // IP für den neuen Socket
for (int i = 0; i < 4; i++) {
if (i < 3) {
ipNew += (getIp.nextToken(",") + ".");
} else {
ipNew += (getIp.nextToken(","));
}
}
Integer portTemp1 = new Integer( getIp.nextToken(","));
Integer portTemp2 = new Integer (getIp.nextToken(","));
portNew = (portTemp1 << 8 )+ portTemp2;
System.out.println(">>>>> " + ipNew + ":" + portNew);
try {
pasvSocket = new Socket(ipNew, portNew);
System.out.println("Socket verbunden: "+ pasvSocket.isConnected());
} catch (UnknownHostException e) {
System.out.println("Host unbekannt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fromPasvServer = new BufferedReader(new InputStreamReader(
pasvSocket.getInputStream()));
Thread.sleep(2000);
System.out.println("Streams bereit: " + fromPasvServer.ready() + " | " );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writePasvCommands = new PrintWriter(pasvSocket.getOutputStream(),
true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.sleep(3000);
Thread pasvKonsole = new Thread(new PasvKonsole(this));
pasvKonsole.start();
}
public void LIST() throws IOException {
writeCommands.print("LIST\n");
writeCommands.flush();
}
public void run() {
try {
connect();
// getStatus();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
USER();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PASS();
try {
Thread.sleep(2000);
PASV();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.io.IOException;
public class PasvKonsole extends Thread {
Client client;
public PasvKonsole(Client client) {
this.client = client;
}
public void run() {
System.out.println("========= PasvKonsole started");
while(true) {
try {
String lineP = client.fromPasvServer.readLine();
System.out.println("***" + lineP);
System.out.println("Ich bin da und tue auch was");
} catch (IOException e) {}
}
}
}
Added a Thread.Sleep and it works.

Categories

Resources