Jini/JavaSpaces discovery error - java

On this article: http://java.sun.com/developer/technicalArticles/tools/JavaSpaces/ is a tutorial how to run JavaSpaces client. I wrote these classes in Eclipse, started Launch-All script and Run example. It works.
After that I exported these classes into executable jar (JavaSpaceClient.jar) and tried that jar with following command:
java -jar JavaSpaceClient.jar
It works fine, gives me result:
Searching for a JavaSpace...
A JavaSpace has been discovered.
Writing a message into the space...
Reading a message from the space...
The message read is: Здраво JavaSpace свете!
My problem is when I move this jar file on my other LAN computer, it shows me error when I type same command. Here is error:
cica#cica-System-Name:~/Desktop$ java -jar JavaSpaceClient.jar
Searching for a JavaSpace...
Jul 27, 2011 11:20:54 PM net.jini.discovery.LookupDiscovery$UnicastDiscoveryTask run
INFO: exception occurred during unicast discovery to biske-Inspiron-1525:4160 with constraints InvocationConstraints[reqs: {}, prefs: {}]
java.net.UnknownHostException: biske-Inspiron-1525
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:175)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at com.sun.jini.discovery.internal.MultiIPDiscovery.getSingleResponse(MultiIPDiscovery.java:134)
at com.sun.jini.discovery.internal.MultiIPDiscovery.getResponse(MultiIPDiscovery.java:75)
at net.jini.discovery.LookupDiscovery$UnicastDiscoveryTask.run(LookupDiscovery.java:1756)
at net.jini.discovery.LookupDiscovery$DecodeAnnouncementTask.run(LookupDiscovery.java:1599)
at com.sun.jini.thread.TaskManager$TaskThread.run(TaskManager.java:331)
I just writes "Searching for JavaSpace..." and after a while prints these error messages.
Can someone help me with this error?
EDIT:
For discovery I am using LookupDiscovery class I've found on Internet:
import java.io.IOException;
import java.rmi.RemoteException;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.discovery.LookupDiscovery;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryEvent;
/**
A class which supports a simple JINI multicast lookup. It doesn't register
with any ServiceRegistrars it simply interrogates each one that's
discovered for a ServiceItem associated with the passed interface class.
i.e. The service needs to already have registered because we won't notice
new arrivals. [ServiceRegistrar is the interface implemented by JINI
lookup services].
#todo Be more dynamic in our lookups - see above
#author Dan Creswell (dan#dancres.org)
#version 1.00, 7/9/2003
*/
public class Lookup implements DiscoveryListener {
private ServiceTemplate theTemplate;
private LookupDiscovery theDiscoverer;
private Object theProxy;
/**
#param aServiceInterface the class of the type of service you are
looking for. Class is usually an interface class.
*/
public Lookup(Class aServiceInterface) {
Class[] myServiceTypes = new Class[] {aServiceInterface};
theTemplate = new ServiceTemplate(null, myServiceTypes, null);
}
/**
Having created a Lookup (which means it now knows what type of service
you require), invoke this method to attempt to locate a service
of that type. The result should be cast to the interface of the
service you originally specified to the constructor.
#return proxy for the service type you requested - could be an rmi
stub or an intelligent proxy.
*/
Object getService() {
synchronized(this) {
if (theDiscoverer == null) {
try {
theDiscoverer =
new LookupDiscovery(LookupDiscovery.ALL_GROUPS);
theDiscoverer.addDiscoveryListener(this);
} catch (IOException anIOE) {
System.err.println("Failed to init lookup");
anIOE.printStackTrace(System.err);
}
}
}
return waitForProxy();
}
/**
Location of a service causes the creation of some threads. Call this
method to shut those threads down either before exiting or after a
proxy has been returned from getService().
*/
void terminate() {
synchronized(this) {
if (theDiscoverer != null)
theDiscoverer.terminate();
}
}
/**
Caller of getService ends up here, blocked until we find a proxy.
#return the newly downloaded proxy
*/
private Object waitForProxy() {
synchronized(this) {
while (theProxy == null) {
try {
wait();
} catch (InterruptedException anIE) {
}
}
return theProxy;
}
}
/**
Invoked to inform a blocked client waiting in waitForProxy that
one is now available.
#param aProxy the newly downloaded proxy
*/
private void signalGotProxy(Object aProxy) {
synchronized(this) {
if (theProxy == null) {
theProxy = aProxy;
notify();
}
}
}
/**
Everytime a new ServiceRegistrar is found, we will be called back on
this interface with a reference to it. We then ask it for a service
instance of the type specified in our constructor.
*/
public void discovered(DiscoveryEvent anEvent) {
synchronized(this) {
if (theProxy != null)
return;
}
ServiceRegistrar[] myRegs = anEvent.getRegistrars();
for (int i = 0; i < myRegs.length; i++) {
ServiceRegistrar myReg = myRegs[i];
Object myProxy = null;
try {
myProxy = myReg.lookup(theTemplate);
if (myProxy != null) {
signalGotProxy(myProxy);
break;
}
} catch (RemoteException anRE) {
System.err.println("ServiceRegistrar barfed");
anRE.printStackTrace(System.err);
}
}
}
/**
When a ServiceRegistrar "disappears" due to network partition etc.
we will be advised via a call to this method - as we only care about
new ServiceRegistrars, we do nothing here.
*/
public void discarded(DiscoveryEvent anEvent) {
}
}
My client program tries simply to search for JavaSpaces service write MessageEntry into and then retrieves message and prints it out. Here is client program:
import net.jini.space.JavaSpace;
public class SpaceClient {
public static void main(String argv[]) {
try {
MessageEntry msg = new MessageEntry();
msg.content = "Hello JavaSpaces wordls!";
System.out.println("Searching for JavaSpaces...");
Lookup finder = new Lookup(JavaSpace.class);
JavaSpace space = (JavaSpace) finder.getService();
System.out.println("JavaSpaces discovered.");
System.out.println("Writing into JavaSpaces...");
space.write(msg, null, 60*60*1000);
MessageEntry template = new MessageEntry();
System.out.println("Reading message from JavaSpaces...");
MessageEntry result = (MessageEntry) space.read(template, null, Long.MAX_VALUE);
System.out.println("Message: "+result.content);
} catch(Exception e) {
e.printStackTrace();
}
}
}
And of course this is MessageEntry class:
import net.jini.core.entry.*;
public class MessageEntry implements Entry {
public String content;
public MessageEntry() {
}
public MessageEntry(String content) {
this.content = content;
}
public String toString() {
return "MessageContent: " + content;
}
}
EDIT2:
I did discovery on two Windows computers.
After that I tried Windows - Ubuntu combiantion and it doesn't work. Maybe there are some network problems? When I ping each another everything is ok. Maybe there are some DNS issues on Ubuntu..
EDIT3:
Windows - Ubuntu combination works if JavaSpaces service is started up on Windows and client program is on Ubuntu. When I try to do reverse, to run JavaSpaces service on Ubuntu and run client on Windows error occurs.
Obviously there is some problem with Ubuntu. Ubuntu has installed OpenJDK installed by default. I installed Oracle JDK, and set JAVA_HOME and put JAVA_HOME/bin into PATH variable. I wonder maybe there is some problem with different versions of Java, maybe I am not using right one.

It is possible that the service registrar that you are running (on host biske-Inspiron-1525 at port 4160), is discovering it's hostname incorrectly (without domain name) and is therefore sending out the announcements with a short hostname. Therefore, after discovering the service registrar, it is possible that subsequently the client is trying to make a connection to the service registrar it cannot resolve the hostname if it is on a different domain.
To ensure that the service registrar is running with the correct hostname, try starting it with the following command line attribute:
-Dcom.sun.jini.reggie.unicastDiscoveryHost="biske-Inspiron-1525.and.its.domain"

It appears that you are doing unicast discovery to a specific host and port and that you can't look up that host.
Assuming you can resolve the name biske-Inspiron-1525 with DNS try removing the ":4160" part and see if the unicast lookup succeeds then.
Here is an example of the code I use to look up a service. It's a bit more complicated because I implement ServiceDiscoveryListener and handle service discovery that way. I actually keep a list of services and dynamically switch between then when one fails but I stripped that part out of the example. I am also using the Configuration part of Jini which I'll explain afterwards. The service interface I am using here is called "TheService":
public class JiniClient implements ServiceDiscoveryListener {
private TheService service = null;
private Class[] serviceClasses;
private ServiceTemplate serviceTemplate;
public JiniClient(String[] configFiles) throws ConfigurationException {
Configuration config = ConfigurationProvider.getInstance(configFiles,
getClass().getClassLoader());
// Set the security manager
System.setSecurityManager(new RMISecurityManager());
// Define the service we are interested in.
serviceClasses = new Class[] {TheService.class};
serviceTemplate = new ServiceTemplate(null, serviceClasses, null);
// Build a cache of all discovered services and monitor changes
ServiceDiscoveryManager serviceMgr = null;
DiscoveryManagement mgr = null;
try {
mgr = (DiscoveryManagement)config.getEntry(
getClass().getName(), // component
"discoveryManager", // name
DiscoveryManagement.class); // type
if (null == mgr) {
throw new ConfigurationException("entry for component " +
getClass().getName() + " name " +
"discoveryManager must be non-null");
}
} catch (Exception e) {
/* This will catch both NoSuchEntryException and
* ConfigurationException. Putting them both
* below just to make that clear.
*/
if( (e instanceof NoSuchEntryException) ||
(e instanceof ConfigurationException)) {
// default value
try {
System.err.println("Warning, using default multicast discover.");
mgr = new LookupDiscoveryManager(LookupDiscovery.ALL_GROUPS,
null, // unicast locators
null); // DiscoveryListener
} catch(IOException ioe) {
e.printStackTrace();
throw new RuntimeException("Unable to create lookup discovery manager: " + e.toString());
}
}
}
try {
serviceMgr = new ServiceDiscoveryManager(mgr, new LeaseRenewalManager());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Unable to create service discovery manager: " + e.toString());
}
try {
serviceMgr.createLookupCache(serviceTemplate,
null, // no filter
this); // listener
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to create serviceCache: " + e.getMessage());
}
}
public void serviceAdded(ServiceDiscoveryEvent evt) {
/* Called when a service is discovered */
ServiceItem postItem = evt.getPostEventServiceItem();
//System.out.println("Service appeared: " +
// postItem.service.getClass().toString());
if(postItem.service instanceof TheService) {
/* You may be looking for multiple services.
* The serviceAdded method will be called for each
* so you can use instanceof to figure out if
* this is the one you want.
*/
service = (TheService)postItem.service;
}
}
public void serviceRemoved(ServiceDiscoveryEvent evt) {
/* This notifies you of when a service goes away.
* You could keep a list of services and then remove this
* service from the list.
*/
}
public void serviceChanged(ServiceDiscoveryEvent evt) {
/* Likewise, this is called when a service changes in some way. */
}
The Configuration system allows you to dynamically configure the discovery method so you can switch to discover specific unicast systems or multicast without changing the app. Here is an example of a unicast discovery configuration file that you could pass to the above objects constructor:
import net.jini.core.discovery.LookupLocator;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.discovery.LookupDiscovery;
com.company.JiniClient {
discoveryManager = new LookupDiscoveryManager(
LookupDiscovery.ALL_GROUPS,
new LookupLocator[] { new LookupLocator("jini://biske-Inspiron-1525.mycompany.com")},
null,
this); // the current config
}

I found solution! That was dns issue. On Ubuntu my /etc/hosts file was:
192.168.1.3 biske-Inspiron-1525 # Added by NetworkManager
127.0.0.1 localhost.localdomain localhost
::1 biske-Inspiron-1525 localhost6.localdomain6 localhost6
127.0.1.1 biske-Inspiron-1525
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
I've just removed line 127.0.1.1 biske-Inspiron-1525 and now it works fine.
Little thing was destroyed million of my nerves :)

Related

Angular 8 socket.io-client 2.2.0 and Java netty-socket.io message not being received?

I am using netty-socket.io and I implemented the server like the demo.
I receive onConnect event both on server and client, but when I sent a message {message: message} I don't get anything on the server event though I see the message being sent in the network tab.
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(9092);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(socketIOClient -> System.out.println("Connection test"));
server.addEventListener("messageevent", MessageEventObject.class, new DataListener<MessageEventObject>() {
#Override
public void onData(SocketIOClient socketIOClient, MessageEventObject messageEventObject, AckRequest ackRequest) throws Exception {
System.out.println("message received!");
}
});
server.start();
My MessageEventObject has String message property, constructor getters and setters, looking the same as client-sided.
And this is my websocket service client-sided:
export class WebsocketService {
private socket;
private subject = new Subject < any > ();
constructor() {
console.log('test!');
}
public connect(host: string, port: number) {
this.socket = io(`http://${host}:${port}`, {
'reconnection': false
});
this.socket.on('connect', this.onConnected);
this.socket.on('connect_error', this.onConnectionFailure);
}
public getConnectionStateUpdate(): Observable < any > {
return this.subject.asObservable();
}
public sendMessage(message: string) {
console.log('test');
this.socket.emit('messageevent', {
message: message
});
}
private onConnected = () => {
this.subject.next({
connected: true
});
}
private onConnectionFailure = () => {
this.subject.next({
connected: false
});
}
}
Is there anything that I did wrong?
I would love to answer my own question after tons of debugging and breaking my head, my laziness to use Engine IO with tomcat or jetty, and just wanting to use that awesome netty package which does not require any servlets, I tried to fix it and figure out.
At first I thought it was the client's protocol version, so I used the exact same client as the demo shows on their github page here but that didn't work so the problem is server-sided.
It appears that your object (MessageEventObject) must have a default empty constructor aswell in addition to your other constructors, probably because netty tries to build an empty object and it fails which causes an exception that you don't see.

Connecting to Siebel using Java databeans hangs forever

Hi Below is a sample code I've written:
import com.siebel.data.*;
import com.siebel.data.SiebelException;
public class DataBeanDemo
{
private SiebelDataBean m_dataBean = null;
private SiebelBusObject m_busObject = null;
private SiebelBusComp m_busComp = null;
public static void main(String[] args)
{
DataBeanDemo demo = new DataBeanDemo();
}
public DataBeanDemo()
{
try
{
m_dataBean = new SiebelDataBean();
m_dataBean.login("Siebel://devServerXYZ:7777/XYZ/
ecommunication_enu", ROSADMIN, ROSADMIN, "enu");
System.out.println("Connected");
m_busObject = m_dataBean.getBusObject("Opportunity");
m_busComp = m_busObject.getBusComp("Opportunity");
m_dataBean.logoff();
}
catch (SiebelException e)
{
System.out.println(e.getErrorMessage());
}
}
}
This code executes without issues, but gets stuck at m_dataBean.login(). And never returns.
What could be the issue?
If I try to change connect string (even port name, from 7777 to any other number like 2320, 2321) then I get error could not open a session in 4 attempts SBL-JCA-00200.
3 things to verify
Parameters in the connect string. Gtway server name, OM comp name, port number etc. (Username/Password error is showed immediately but rest others throw generic errors or hung forever)
(This is something that's specific to Siebel) Ensure that Java subsystem profile has classpath pointing to siebel.jar and siebelJI_lang.jar files
Siebel Server is up and running.
If LDAP is true, then such logins cannot be used using Databeans.
In my case it was 1 & 2, that was causing issues. By the way Comp name is case sensitive.

Establishing a WebSocket client connection in Jetty?

I'm following this tutorial to establish a WebSocket connection to a server:
http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html
The code (same as the tutorial):
import java.net.URI;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
/**
* Example of a simple Echo Client.
*/
public class SimpleEchoClient {
public static void main(String[] args) {
String destUri = "ws://echo.websocket.org";
if (args.length > 0) {
destUri = args[0];
}
WebSocketClient client = new WebSocketClient();
SimpleEchoClient socket = new SimpleEchoClient();
try {
client.start();
URI echoUri = new URI(destUri);
ClientUpgradeRequest request = new ClientUpgradeRequest();
client.connect(socket, echoUri, request);
System.out.printf("Connecting to : %s%n", echoUri);
// socket.awaitClose(5, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Errors:
2014-08-07 21:49:00.346:INFO::main: Logging initialized #86ms
org.eclipse.jetty.websocket.api.InvalidWebSocketException:
SimpleEchoClient is not a valid WebSocket object.
Object must obey one of the following rules:
(1) class implements org.eclipse.jetty.websocket.api.WebSocketListener or
(2) class is annotated with #org.eclipse.jetty.websocket.api.annotations.WebSocket
at org.eclipse.jetty.websocket.common.events.EventDriverFactory.wrap(EventDriverFactory.java:145)
at org.eclipse.jetty.websocket.client.WebSocketClient.connect(WebSocketClient.java:200)
at org.eclipse.jetty.websocket.client.WebSocketClient.connect(WebSocketClient.java:144)
at SimpleEchoClient.main(SimpleEchoClient.java:31)
I'm not too sure what is wrong with my imported jar file. Maybe it is the wrong one? I'm using this: http://mvnrepository.com/artifact/org.eclipse.jetty.websocket/websocket-client/9.2.2.v20140723
Surely there must be an easier way to establish a connection via Jetty Websocket and start receiving data?
As Kayman explained in the comment, your problem with the socket handler implementation, use the latest release here explained with an example(same you used but correct) http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html
It looks like the documentation is out-of-date with the current version you are using. Try rolling back to a more stable version of 9.2.x like:
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
<version>9.2.0.RC0</version>
</dependency>

RMI cannot connect to remote server

I've been plying with RMI recently and while I managed to make it work on locahost I've been having all sorts of problem when trying to use a remote server. Here's the basic code I'm trying to run:
Server:
public class RmiServer extends UnicastRemoteObject implements RmiServerIntf {
public static final String MESSAGE = "Hello world";
public RmiServer() throws RemoteException {
}
public String getMessage() {
return MESSAGE;
}
public static void main(String args[]) {
System.out.println("RMI server started");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
System.out.println("Security manager installed.");
} else {
System.out.println("Security manager already exists.");
}
try {
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
} catch (RemoteException e) {
e.printStackTrace();
}
try {
RmiServer obj = new RmiServer();
Naming.rebind("rmi://localhost/RmiServer", obj);
System.out.println("PeerServer bound in registry");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Remote class interface:
public interface RmiServerIntf extends Remote {
public String getMessage() throws RemoteException;
}
Client:
public class RmiClient {
RmiServerIntf obj = null;
public String getMessage() {
try {
obj = (RmiServerIntf)Naming.lookup("rmi://54.229.66.xxx/RmiServer");
return obj.getMessage();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
RmiClient cli = new RmiClient();
System.out.println(cli.getMessage());
}
}
rmi.policy file:
grant {
permission java.security.AllPermission;
};
I compiled the classes and created a stub for the server. Then I placed client, stub, interface and policy on my machine and server, stub, interface and policy on the remote machine. The remote server being a Linux machine I made all the files executable. I also added a rule on the local firewall allowing port 1099, and opened all ports on the remote machine
After this I navigated to the server's directory on the remote machine and inserted the following command:
java -Djava.security.policy=rmi.policy RmiServer
This didn't give me problems so I went back to the local machine and entered
java -Djava.security.policy=rmi.policy RmiClient
I wait, and wait and I get the error message:
Connection refused to host: 172.31.xx.xx; nested exception is: java.net.ConnectException: Connection timed out: connect
I've been fighting with these connection errors all day yesterday and this is as far as I got. I'm sure there's only one very small thing I'm still doing wrong but I just can't find what it is.
This may not solve your problem, but I've had similar issues with JPPF (via Java RMI) on Linux. The solution was to ensure that the ephemeral port range on the Client-side machine covered only ports that were allowable by the Client-side's local firewall. E.g., if your firewall allows ports 48000 to 64000 to be connected to by an external machine, ensure that your ephemeral port range also falls within 48000 to 64000. Give that a try and let us know what happens.
System.setProperty("java.rmi.server.hostname","10.0.3.73");
Please use the above statements in your RMIServer side code, and try and connect from remote client again. It worked for me

Does Smack work well in Java EE

Does Smack function properly in Java EE?? I am having issues with presence.
I get the credentials from the login form via doPost method..I can able to successfully authenticate as well as connection.getRoster() also works.Next I want to show only users who are online so when I get the presence of user,presence object stores default value "unavailable" for all users even when they are available!!
The whole chat app works without flaw in a normal java class without any change..
String userName = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session=request.getSession();
session.setAttribute("username", userName);
SmackAPIGtalkServlet gtalk = new SmackAPIGtalkServlet();
ConnectionConfiguration config = new ConnectionConfiguration(
"talk.google.com", 5222, "gmail.com");
connection = new XMPPConnection(config);
config.setSASLAuthenticationEnabled(false);
try {
connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
System.out.println(connection.isAuthenticated());
boolean status = connection.isAuthenticated();
if (status == true) {
gtalk.displayOnlineBuddyList();
response.sendRedirect("Roster.jsp");
}
else
{
response.sendRedirect("Failed.jsp");
}
}
public void displayOnlineBuddyList() {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
int count1 = 0;
int count2 = 0;
for (RosterEntry r : entries) {
Presence presence = roster.getPresence(r.getUser());
if (presence.getType() == Presence.Type.unavailable) {
// System.out.println(user + "is offline");
count1++;
} else {
System.out.println(name+user + "is online");
count2++;
}
}
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String>
// addresses) {}
public void entriesDeleted(Collection<String> addresses) {
}
public void entriesUpdated(Collection<String> addresses) {
}
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom()
+ " " + presence);
}
#Override
public void entriesAdded(Collection<String> arg0) {
// TODO Auto-generated method stub
}
});
}
I am stuck with this and not able to get the code working with servlets..Can anyone help me out??
Will Smack work inside of Java EE, yes and no.
Smack will work inside of a web container, but since it creates its own threads it will NOT work inside of an EJB container. So it will work depending on where you are running it.
To understand some of your issues, you have to understand that the lifecycle of your objects in a servlet is tied to the request/response cycle of each request. This is not the same as a standard java app where the objects will typically live as long as you need them to, since you control their lifecycle.
For example, in the code you have shown, you create the connection for each request (I assume, since not all the code is shown). Therefore registering listeners against that connection will be pointless since it will pass out of scope as soon as you leave the method, and eventually get garbage collected. You will have to maintain the connections outside of the scope of the servlet requests for this to work, otherwise you will be opening and closing connections for each request.
XMPP is completely asynchronous by nature whereas servlet requests are synchronous. You have to put some effort in to making them work together, so don't expect code that works in a standalone app to simply work in this environment.
You have to implement the RosterListener interface in which you have to override the presenceChanged method in that you can get the presence of the users.
It works for me.
When you are getting the rosters of GTalk all will have status as unavailable.
But after sometime their presence changes and the presence can be get from the presenceChanged method in the RosterListner but for that you have to implement the RosterListener's presenceChnaged method.
And ya it works well in Java EE, Android as well as WAP.
Does Smack function properly in Java EE?? I am having issues with presence. I get the credentials from the login form via doPost method..I can able to successfully authenticate as well as connection.getRoster() also works.Next I want to show only users who are online so when I get the presence of user,presence object stores default value "unavailable" for all users even when they are available!! here my code
<%
Roster rst = roster;
rst.addRosterListener(new RosterListener() {
public void entriesAdded(final Collection args) {}
public void entriesDeleted(final Collection<String> addresses) {}
public void entriesUpdated(final Collection<String> addresses) {}
public void presenceChanged(final Presence presence) {
final Presence prsence1 = presence;
prsenceChanged(prsence1);
if (prsence1.isAvailable()) {
System.out.println("Is Available: " + presence.isAvailable());
}
}
});
%>
<%!void prsenceChanged(Presence presence){ if(null != presence){%>
<script language="javascript">
alert("hai");
</script>

Categories