Hi I am new in Java. And its giving me a lot of stress. I need to chat with smack api and openfire server. For this my java code is below
import java.util.*;
import java.io.*;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class RunJabberSmackAPI implements MessageListener{
XMPPConnection connection;
public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1 ",5222,"localhost");
connection = new XMPPConnection(config);
connection.connect();
connection.login(userName, password);
}
public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}
public void displayBuddyList()
{
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
System.out.println("\n\n" + entries.size() + " buddy(ies):");
for(RosterEntry r:entries) {
System.out.println(r.getUser());
}
}
public void disconnect() {
connection.disconnect();
}
public void processMessage(Chat chat, Message message) {
if(message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
public static void main(String args[]) throws XMPPException, IOException {
// declare variables
RunJabberSmackAPI c = new RunJabberSmackAPI();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg;
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
// Enter your login information here
c.login("admin", "admin"); // I created this user with openfire.
c.displayBuddyList();
System.out.println("-----");
System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();
System.out.println("-----");
System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");
while( !(msg=br.readLine()).equals("bye")) {
c.sendMessage(msg, talkTo);
}
c.disconnect();
System.exit(0);
}
}
I run this code twice in my pc. Each for an individual user. I added these two users as friends in openfire by adding rooster.
But when they logged in by running the java code above they send there presence as available . But they can't send their presence to each other available. Instead they receives two error messages from their buddy .
First error message : www.freeimagehosting.net/image.php?eac15f606a.jpg
Second error message : www.freeimagehosting.net/image.php?b827058d07.jpg
I don't know what is wrong with my code. And i really need to solve this problem very soon. I posted this problem other forums too but can't find any answer. So if anyone can have any solution it would be a very big help. Thank You.
In many threads in IgniteRealtime's web you can see that you need to let Smack asynchronously retrieve Roster, so either you change the displayBuddyList() to use a RosterListener instead, or you simply use a Thread.sleep(5000) between the login and the displayBuddyList() function (if you don't want to use a listener, which is recommended) to let it have some time to populate the roster with updated presences.
Related
I want to develop a simple app that enables me to send SMS to several numbers
and from several numbers.
In the code below, I send from number 5555 to 6666. I want to send, for example, also from number 7777 to number 8888.
What do I need to add to the code?
Meanwhile, I tried to copy TextMessage message but without success.
package getstarted;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.SmsSubmissionResult;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod("xxxxx","yyyy");
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage("5555", "6666", "Hello from Nexmo!");
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
Just instantiate another TextMessage:
TextMessage message2 = new TextMessage("7777", "8888", "Hello from Nexmo!");
SmsSubmissionResult[] responses2 = client.getSmsClient().submitMessage(message2);
for (SmsSubmissionResult response : responses2) {
System.out.println(response);
}
I'm trying to implement a simple websocket client in java using the javax websocket library, here's my code:
import java.io.IOException;
import java.net.URI;
import javax.websocket.*;
#ClientEndpoint
public class Client {
Session session;
private final static String url = "ws://echo.websocket.org";
public static void main(String[] args) throws Exception, IOException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
System.out.println("connecting...");
container.connectToServer(Client.class,
URI.create(url));
}
#OnMessage
public void newMessage(String message, Session session) {
System.out.println(message);
}
#OnOpen
public void newConnection(Session session) throws IOException {
this.session = session;
System.out.println("The connection has been started");
session.getBasicRemote().sendText("hello");
}
#OnClose
public void disconnection() {
System.out.println("The connection has been ended");
}
}
As you can see in the #OnOpen annotation i try to send the "Hello" string message and on the #OnMessage i just want print the message in the console.
I can run the code without errors, but i just got the "connecting..." print so can anyone explain what is wrong with the code?
Note: i added the org.glassfish.tyrus libraries that's needed to work with the javax.websocket to the referenced libraries as well
I'm newbie in Java so sorry for the dumb question
Your program is exiting immediately after calling container.connectToServer(...) so your newConnection(...) and newMessage(...) functions never get a chance to run. You need to keep your program running after the call to container.connectToServer(...). You can do this by, for example, adding the following code after the container.connectToServer(...) line which will cause the program to wait for the ENTER key to be pressed:
System.out.println("Press ENTER key to exit.");
System.in.read();
After making that change, your program worked correctly on my computer and displayed the "The connection has been started" and "hello" messages.
Problem Description
I'm writing chat application using XMPP and Smack Android library. I'm sending messages using code below and everything is working fine.
final ChatManager chatManager = ChatManager.getInstanceFor(connection);
chatManager.addChatListener(this);
....
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(this);
}
#Override
public void processMessage(Chat chat, Message message) {
// Do something here.
}
Chat chat = ChatManager.getInstanceFor(connection).createChat(jid);
chat.sendMessage("message");
Question
Unfortunately the API above is deprecated org.jivesoftware.smack.chat.Chat and instead I should use org.jivesoftware.smack.chat2.Chat, so I am changing implementation as follows
final ChatManager chatManager = ChatManager.getInstanceFor(connection);
chatManager.addOutgoingListener(this);
chatManager.addIncomingListener(this);
....
Chat chat = ChatManager.getInstanceFor(connection).chatWith(jid);
chat.send("message");
In this case I can still get Incoming messages, but when I am trying to send message with chat.send("message"); server does not get anything and addOutgoingListener callback is not called.
Any ideas why?
There is an example with an older version of smack:
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class Test {
public static void main(String args[]) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
XMPPConnection connection = new XMPPConnection(config);
connection.connect();
connection.login("userx", "123456");
ChatManager cm = connection.getChatManager();
Chat chat = cm.createChat("tongqian#tsw-PC", null);
/*
* add listener
*/
cm.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean create) {
chat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message msg) {
System.out.println(chat.getParticipant() + ":" + msg.getBody());
}
});
}
});
chat.sendMessage("hello");
while(true);
//connection.disconnect();
}
}
Answer
Digging a bit deeper I found the answer, the code below will help to send a message
Sending Message Code
final Chat chat = ChatManager.getInstanceFor(connection).chatWith(jid);
Message newMessage = new Message(jid, Message.Type.chat);
newMessage.setBody(message);
chat.send(newMessage);
Conclusion
So instead of sending a string message, you need to create a Message object and I think what is more important is to specify Message.Type.chat in the constructor and also jid and then call chat.send(...)
You can refer to this code snippet:
public void sendMessage(String to, Message newMessage) {
if(chatManager!=null) {
Chat newChat = chatManager.createChat(to);
try {
if (connection.isConnected() && connection.isAuthenticated()) {
newChat.sendMessage(newMessage);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
else
{
Log.d(TAG,”chatmanager is null”);
}
}
And the link is https://ramzandroidarchive.wordpress.com/2016/03/13/send-messages-over-xmpp-using-smack-4-1/ .
new to parallel/distributed computing and having issues with a client-server program I'm trying to write. What's supposed to happen is the server receives an integer from the client and sends back the sum all the numbers leading up to it (ex, user enters 5, server calculates 1+2+3+4+5, server sends back 15). I'm still trying to figure it out, so I've hard coded the input on the client side.
This is what I have on the server side:
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[]args) {
try{
int port = 16790;
String host = "localhost";
CalculateSumServerImpl export = new CalculateSumServerImpl();
LocateRegistry.createRegistry(port);
String registryURL = "rmi://" + host + ":" + port + "/sum";
Naming.rebind(registryURL, export);
System.out.println("Server ready");
} catch (Exception e) {
e.printStackTrace();
}
} }
//to calculate the sum
import java.rmi.*;
import java.rmi.server.*;
public class CalculateSumServerImpl extends UnicastRemoteObject implements CalServerInterface {
public int n; //value entered
public int sum; //sum
protected CalculateSumServerImpl() throws RemoteException {
super();
}
#Override
public int calculateSum(int n) throws RemoteException {
n = (n*(n+1))/2; //sum of 1 + 2 + 3 + .. + n
sum = n;
return sum;
} }
//interface
import java.rmi.Remote;
public interface CalServerInterface extends Remote {
public int calculateSum(int n ) throws java.rmi.RemoteException;
}
And on the client side:
import java.rmi.*;
import java.util.PropertyPermission;
public class Client {
public static void main(String[]args) {
System.setSecurityManager(new java.rmi.RMISecurityManager());
System.setProperty("java.net.preferIPv4Stack" , "true");
try {
int port = 16790;
String host = "localhost";
String registryURL = "rmi://" + host + ":" + port + "/sum";
Project4ServerInterface obj = (Project4ServerInterface)Naming.lookup(registryURL);
System.out.println("Lookup completed.");
int output = obj.calculateSum(3);
System.out.println("Sum is: " + output);
} catch (Exception e) {
e.printStackTrace();
}
System.setProperty("java.net.preferIPv4Stack","true");
} }
And I've implemented the Interface on the client side as well.
The error that I've been getting on the client side is:
Exception in thread "main" java.security.AccessControlException: access denied ("java.util.PropertyPermission" "java.net.preferIPv4Stack" "write")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.security.AccessController.checkPermission(AccessController.java:884)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.System.setProperty(System.java:792)
at project04client.Client.main(Client.java:10)
with the error pointing to the line with this code:
System.setProperty("java.net.preferIPv4Stack" , "true");
Anyone have any experience trouble shooting this error?
Thanks!
The problem is that you have set a security manager for the entire (client) application that won't let you modify system properties.
The simple fix is to set the system properties you need to set before you set the RMI security manager.
Alternatively, you may be able to get rid of the System.setSecurityManager(...) call entirely. You (probably) only need it if you want the client to be able to download classes from your RMI service.
I tried setting the system property before the security manager and got an AccessControlException, denying socket permissions.
That doesn't make much sense. You would only get an AccessControlException if there was a security manager in place at that point. There shouldn't be ... unless this is applet code or similar launched in a web browser. Also, I don't know why a call to set a property would be denied saying that you don't have socket permissions.
When I took the security manager out completely, I got an UnmarshalException pointing to the interface.
You also need to add the classes / interfaces for the objects that tou will be unmarshalling to the client-side classpath.
Actually, I just noticed that the javadoc for RMISecurityManager says:
"RMISecurityManager implements a policy identical to the policy implemented by SecurityManager. RMI applications should use the SecurityManager class or another appropriate SecurityManager implementation instead of this class."
I'm trying to create a twitch bot, and the first thing I'm trying to make it do is respond to chat messages. However, when the bot connects to the chat room, it doesn't seem to stay connected. It sends chat messages fine, but it doesn't recieve them.
Here's the code if you want to look at it. I feel like I'm missing something basic that I should've remembered, so if you can figure out what that is I'd like to know.
package me.acezephyr.lavabot;
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.jibble.pircbot.PircBot;
public class LavaStreamBot extends PircBot {
private static LavaStreamBot INSTANCE = new LavaStreamBot();
public static void main(String[] args) {
INSTANCE.setVerbose(true);
INSTANCE.setName("LavaStreamBot");
try {
INSTANCE.connect("irc.twitch.tv", 6667,
"oauth:******************************");
} catch (NickAlreadyInUseException e) {
System.err
.println("Tried to join Twitch server, but someone else online already has the nick LavaStreamBot.");
} catch (IOException e) {
e.printStackTrace();
} catch (IrcException e) {
e.printStackTrace();
}
join("#AceLava");
}
public static void join(String channel) {
INSTANCE.joinChannel(channel);
INSTANCE.sendMessage(channel, "LavaStreamBot is now in this channel.");
}
#Override
public void onConnect() {
System.out.println("Connected to server");
super.onConnect();
}
#Override
public void onMessage(String channel, String sender, String login, String hostname, String message){
System.out.println("Got a message!");
super.onMessage(channel, sender, login, hostname, message);
}
}
You wrote the channel name ("#AceLava") with capitals. In IRC, this is a different channel than #acelava - Twitch always handles the channels with all lowercase. Just change that and you'll be all fine.
Not related to the question, but you might want to know about the fact that twitch will change their Background messaging service soon™ and it won't be done via IRC so you'll have to change your bot accordingly (as well as I'll have to do >.< ).
For more information and to keep up to date, visit http://discuss.dev.twitch.tv/