Creating thread dumps of a remote jvm programatically - java

I have been trying to invoke an operation on ThreadMXBean in a remote jvm. The code snippet I used invoke the operation is below
bean = new ObjectName("java.lang:type=Threading");
memoryInfo = RemoteConnector.getRemote().getMBeanInfo(bean);
RemoteConnector.getRemote().getObjectInstance(bean);
MBeanOperationInfo [] mBeanAttributeInfos = memoryInfo.getOperations();
for(MBeanOperationInfo mBeanAttributeInfo : mBeanAttributeInfos){
System.out.println(mBeanAttributeInfo.getName());
}
long [] allThreadIds = (long [])RemoteConnector.getRemote().getAttribute(bean,"AllThreadIds");
Object [] params = new Object[2];
int maxDepth = 100;
params[0] = allThreadIds;
params[1] = maxDepth;
String [] opSigs = {allThreadIds.getClass().getName(),"I"};
RemoteConnector.getRemote().invoke(bean,"getThreadInfo",params,opSigs);
Note that getRemote() method returns a mbeanserverconnection
I can't invoke the method getThreadInfo() on stub. I am getting this message
2016-05-05 00:17:37 ERROR ThreadDumpCreator:67 - Operation getThreadInfo exists but not with this signature: ([J, I)
Please help me resolve this issue :)
Below is the method i used to connect remote mbeanserver
public class RemoteConnector {
private static MBeanServerConnection remote = null;
private static JMXConnector connector = null;
public static void defaultConnector(){
try {
JMXServiceURL target = new JMXServiceURL
("service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/jmxrmi");
//for passing credentials for password
Map<String, String[]> env = new HashMap<String, String[]>();
String[] credentials = {"admin", "admin"};
env.put(JMXConnector.CREDENTIALS, credentials);
connector = JMXConnectorFactory.connect(target, env);
remote = connector.getMBeanServerConnection();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static MBeanServerConnection getRemote() {
return remote;
}
public static void setRemote(MBeanServerConnection remote) {
RemoteConnector.remote = remote;
}
public static void closeConnection() throws IOException {
if(connector != null){
connector.close();
}
}
}

Apparently I should have used int.class.getName() as the method signature requires from invoke method

Related

WebServiceException: Method beaInvoke is exposed as WebMethod

Below is the code Snippet.. that must call WSDL in other server dynamically
but in the moment of calling
(int i = webServiceModuleService.notificationRecieved("xyz");)
returned exception :(
note: i haven't any beaInvoke method in my service :|
public static void main(String[] args) {
java.sql.Connection conn = null;
InitialContext context;
try {
context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/dataSourceDS");
conn = ds.getConnection();
} catch (SQLException e) {
} catch (NamingException e) {
}
QueryRunner run = new QueryRunner();
SampleResultSetHandler h = new SampleResultSetHandler();
Object[] res = null;
try {
res = run.query(conn, "select SERVER_IP,SERVER_PORT from SERVER where UPPER(SERVER_NAME)=? ", h, "test");
} catch (SQLException e) {
}
String ip = res[0].toString();
String port = res[1].toString();
String endpointURL = "http://" + ip + ":" + port + "/context-root/WebServiceModuleService";
try {
URL tmpURL = new URL(endpointURL + "?wsdl");
System.err.println(tmpURL);
WebServiceModuleService_Service webServiceModuleService_Service = new WebServiceModuleService_Service(tmpURL,
new QName("/org/parsisys/test/mina/model/services/common/",
"WebServiceModuleService"));
WebServiceModuleService webServiceModuleService = null;
webServiceModuleService = webServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort();
BindingProvider bp = (BindingProvider) webServiceModuleService;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
// Configure credential providers
Map<String, Object> requestContext = ((BindingProvider) webServiceModuleService).getRequestContext();
try {
setPortCredentialProviderList(requestContext);
} catch (Exception ex) {
ex.printStackTrace();
}
//Call WebService ... ==> Exception :(
int i = webServiceModuleService.notificationRecieved("xyz");
//logp("successfully call the webservice for [ip&port:" + ip + ":" + port + "] [transid : " +transid + "]");
} catch (Exception e) {
//log
//TODO: Clean This
System.err.println(e.getMessage());
e.printStackTrace();
return;
}
}
#Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required credential values
String username = "";
String password = "";
String clientKeyStore = "";
String clientKeyStorePassword = "";
String clientKeyAlias = "";
String clientKeyPassword = "";
String serverKeyStore = "";
String serverKeyStorePassword = "";
String serverKeyAlias = "";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
// Add the necessary credential providers to the list
// Code commented out due to empty username/password value found in the credential.
// credList.add(getUNTCredentialProvider(username, password));
// Code commented out due to empty server keystore value found in the credential.
// credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
daynamic webservice call is generated with jdeveloper and it's works in clien't tester but in my module when i call webservice return exception :/
StackTrace is: ↓
Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
javax.xml.ws.WebServiceException: Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
at com.sun.xml.ws.model.JavaMethodImpl.freeze(JavaMethodImpl.java:382)
at com.sun.xml.ws.model.AbstractSEIModelImpl.freeze(AbstractSEIModelImpl.java:124)
at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:336)
at com.sun.xml.ws.db.DatabindingImpl.(DatabindingImpl.java:99)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:74)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:58)
at com.sun.xml.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:120)
at com.sun.xml.ws.client.WSServiceDelegate.buildRuntimeModel(WSServiceDelegate.java:882)
at com.sun.xml.ws.client.WSServiceDelegate.createSEIPortInfo(WSServiceDelegate.java:899)
at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:862)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:451)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.internalGetPort(WLSProvider.java:1698)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$PortClientInstanceFactory.createClientInstance(WLSProvider.java:1769)
at weblogic.wsee.jaxws.spi.ClientInstancePool.takeSimpleClientInstance(ClientInstancePool.java:389)
at weblogic.wsee.jaxws.spi.ClientInstancePool.take(ClientInstancePool.java:243)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1555)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1517)
at weblogic.wsee.jaxws.spi.ClientIdentityRegistry.initClientIdentityFeatureAndCall(ClientIdentityRegistry.java:1456)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1513)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:420)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1477)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:402)
at javax.xml.ws.Service.getPort(Service.java:119)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.beaInvokeSuper(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service$beaVersion0_31.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java:51)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved$beaVersion0_11.onMessage(NotificationQueueRecieved.java:330)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved.onMessage(NotificationQueueRecieved.java)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:5107)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:4775)
at weblogic.jms.client.JMSSession.executeMessage(JMSSession.java:4170)
at weblogic.jms.client.JMSSession.access$000(JMSSession.java:127)
at weblogic.jms.client.JMSSession$UseForRunnable.run(JMSSession.java:5627)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
please help me. tnx
For me this occurs when the WSDL does not agree with the generated classes.

DCM4CHE, Network operations,Handling a C-Move call

Hi I'm trying to make a PACS server using Java. dcm4che appears to be quite popular. But I'm unable to find any good examples about it.
As a starting point I inspected dcmqrscp and it successfully stores a DICOM image. But I cannot manage to handle a C-MOVE call. Here's my CMove handler. It finds requested the DICOM file adds a URL and other stuff, it doesn't throw any exception yet client doesn't receive any files.
private final class CMoveSCPImpl extends BasicCMoveSCP {
private final String[] qrLevels;
private final QueryRetrieveLevel rootLevel;
public CMoveSCPImpl(String sopClass, String... qrLevels) {
super(sopClass);
this.qrLevels = qrLevels;
this.rootLevel = QueryRetrieveLevel.valueOf(qrLevels[0]);
}
#Override
protected RetrieveTask calculateMatches(Association as, PresentationContext pc, final Attributes rq, Attributes keys) throws DicomServiceException {
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(keys, qrLevels);
try {
level.validateRetrieveKeys(keys, rootLevel, relational(as, rq));
} catch (Exception e) {
e.printStackTrace();
}
String moveDest = rq.getString(Tag.MoveDestination);
final Connection remote = new Connection("reciverAE",as.getSocket().getInetAddress().getHostAddress(), 11113);
if (remote == null)
throw new DicomServiceException(Status.MoveDestinationUnknown, "Move Destination: " + moveDest + " unknown");
List<T> matches = DcmQRSCP.this.calculateMatches(keys);
if (matches.isEmpty())
return null;
AAssociateRQ aarq;
Association storeas = null;
try {
aarq = makeAAssociateRQ(as.getLocalAET(), moveDest, matches);
storeas = openStoreAssociation(as, remote, aarq);
} catch (Exception e) {
e.printStackTrace();
}
BasicRetrieveTask<T> retrieveTask = null;
retrieveTask = new BasicRetrieveTask<T>(Dimse.C_MOVE_RQ, as, pc, rq, matches, storeas, new BasicCStoreSCU<T>());
retrieveTask.setSendPendingRSPInterval(getSendPendingCMoveInterval());
return retrieveTask;
}
private Association openStoreAssociation(Association as, Connection remote, AAssociateRQ aarq)
throws DicomServiceException {
try {
return as.getApplicationEntity().connect(as.getConnection(),
remote, aarq);
} catch (Exception e) {
throw new DicomServiceException(
Status.UnableToPerformSubOperations, e);
}
}
private AAssociateRQ makeAAssociateRQ(String callingAET,
String calledAET, List<T> matches) {
AAssociateRQ aarq = new AAssociateRQ();
aarq.setCalledAET(calledAET);
aarq.setCallingAET(callingAET);
for (InstanceLocator match : matches) {
if (aarq.addPresentationContextFor(match.cuid, match.tsuid)) {
if (!UID.ExplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ExplicitVRLittleEndian);
if (!UID.ImplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ImplicitVRLittleEndian);
}
}
return aarq;
}
private boolean relational(Association as, Attributes rq) {
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
return QueryOption.toOptions(extNeg).contains(
QueryOption.RELATIONAL);
}
}
I added the code below to send a DICOM file as a response:
String cuid = rq.getString(Tag.AffectedSOPClassUID);
String iuid = rq.getString(Tag.AffectedSOPInstanceUID);
String tsuid = pc.getTransferSyntax();
try {
DcmQRSCP.this.as=as;
File f = new File("D:\\dcmqrscpTestDCMDir\\1.2.840.113619.2.30.1.1762295590.1623.978668949.886\\1.2.840.113619.2.30.1.1762295590.1623.978668949.887\\1.2.840.113619.2.30.1.1762295590.1623.978668949.888");
FileInputStream in = new FileInputStream(f);
InputStreamDataWriter data = new InputStreamDataWriter(in);
// !1! as.cmove(cuid,1,keys,tsuid,"STORESCU");
as.cstore(cuid,iuid,1,data,tsuid,rspHandlerFactory.createDimseRSPHandler(f));
} catch (Exception e) {
e.printStackTrace();
}
Throws this exception
org.dcm4che3.net.NoRoleSelectionException: No Role Selection for SOP Class 1.2.840.10008.5.1.4.1.2.2.2 - Study Root Query/Retrieve Information Model - MOVE as SCU negotiated
You should add a role to the application instance like:
applicationEntity.addTransferCapability(
new TransferCapability(null, "*", TransferCapability.Role.SCP, "*"));

How to reuse redis(JRedis) pool connection in Java

I am using Redis(3.2.100) for Windows to cache my database data in Java.This is my redis init code:
private static Dictionary<Integer, JedisPool> pools = new Hashtable();
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(2);
config.setMaxTotal(10);
config.setTestOnBorrow(true);
config.setMaxWaitMillis(2000);
for (int i = 0; i < 16; i++) {
JedisPool item = new JedisPool(config, "127.0.0.1", 6379,10*1000);
pools.put(i, item);
}
}
This is the cache code:
public static String get(String key, Integer db) {
JedisPool poolItem = pools.get(db);
Jedis jredis = poolItem.getResource();
String result = jredis.get(key);
return result;
}
The problem is when the program run for a while,the getResource method throws:
redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
So how to reuse the connection or close the connection.I am using this command to find out that the client has reached the max value.
D:\Program Files\Redis>redis-cli.exe info clients
# Clients
connected_clients:11
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0
How to fix it?
Remember to close the redis connection,modify this function like this:
public static String get(String key, Integer db) {
JedisPool poolItem = pools.get(db);
Jedis jredis = null;
String result = null;
try {
jredis = poolItem.getResource();
result = jredis.get(key);
} catch (Exception e) {
log.error("get value error", e);
} finally {
if (jredis != null) {
jredis.close();
}
}
return result;
}

How to access ehcache mbeans on weblogic server

In my weblogic server ehcache is deployed , I need to get ehcahe mbeans from this program through java programming, Through JMX i am not able to connect.how can i get those custom mbeans??
i tried to get mbeans through weblogic t3 protocol
public class Test
{
private String hostName = "";
private String port = "";
private String userName = "";
private String password = "";
private String connectorURL = "service:jmx:rmi:///jndi/rmi://{0}:{1}/jmxrmi";
private JMXConnector jmxc = null;
public static void main(String []args) throws Exception
{
Test t = new Test();
t.hostName = args[0];
System.out.println(args[1]);
t.port = args[1];
t.userName = args[2];
t.password = args[3];
t.jmxc = t.initConnection();
MBeanServerConnection mbsc = t.jmxc.getMBeanServerConnection();
System.out.println(mbsc);
Set<ObjectInstance> st =mbsc.queryMBeans(new ObjectName("net.*:*"), null);
System.out.println(st.toString());
Iterator<ObjectInstance> it = st.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
t.closeConnection();
}
private JMXConnector initConnection()
{
System.out.println("initiate connection");
JMXServiceURL serviceURL = null;
try
{
String jndiroot = "/jndi/";
String mserver = "weblogic.management.mbeanservers.domainruntime";
int port1 = Integer.parseInt(port);
serviceURL = new JMXServiceURL("t3", hostName, port1, jndiroot + mserver);
Hashtable h = new Hashtable();
h.put(Context.SECURITY_PRINCIPAL, userName);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
long lngJmxClientWTO = 10000;
h.put("jmx.remote.x.request.waiting.timeout", lngJmxClientWTO );
return JMXConnectorFactory.connect(serviceURL, h);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* This method closes client connection with server
* #throws IOException
*/
public void closeConnection()
{
if(jmxc != null)
{
try
{
jmxc.close();
}
catch (IOException e) {
jmxc = null;
}
}
}
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
CacheManager manager = CacheManager.newInstance();
Ehcache cache = manager.getEhcache("Some cache name here..."); //<-- PLEASE EDIT THE CACHE NAME...
I don't know if this is what you're asking for....
Once you've obtained your cache, you can use it, pretty much like a java Map.
You can follow the Ehcache documentation to see how to programmatically get the remote cache. Essentially, you will need to create a configuration (or configuration file) which the CacheManager can access.

item-not-found(404) when trying to get a node using Smackx pubsub

I'm trying to use the latest Smackx trunk to get and then subscribe to a pubsub node. However, openfire just sends me a back an error: item not found (404).
I am instantiating the java objects from ColdFusion, so my code snippets might look funny but maybe someone will be able to tell me what I've forgotten.
Here's how I create the node:
ftype = createObject("java", "org.jivesoftware.smackx.pubsub.FormType");
cform = createObject("java", "org.jivesoftware.smackx.pubsub.ConfigureForm").init(ftype.submit);
cform.setPersistentItems(true);
cform.setDeliverPayloads(true);
caccess = createObject("java", "org.jivesoftware.smackx.pubsub.AccessModel");
cform.setAccessModel(caccess.open);
cpublish = createObject("java", "org.jivesoftware.smackx.pubsub.PublishModel");
cform.setPublishModel(cpublish.open);
cform.setMaxItems(99);
manager = createObject("java", "org.jivesoftware.smackx.pubsub.PubSubManager").init(XMPPConnection);
myNode = manager.createNode("subber", cform);
And here's how I am trying to get to it (in a different section of code):
manager = createObject("java", "org.jivesoftware.smackx.pubsub.PubSubManager").init(XMPPConnection);
myNode = manager.getNode("subber");
Immediately upon creating the node I seem to be able to publish to it like so:
payload = createObject("java", "org.jivesoftware.smackx.pubsub.SimplePayload").init("book","pubsub:test:book","<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>");
item = createObject("java", "org.jivesoftware.smackx.pubsub.Item").init(payload);
myNode.publish(item);
However, it is the getNode() call that is causing my code to error.
I have verified that the nodes are being created by checking the DB used by my openfire server. I can see them in there, properly attributed as leaf nodes, etc.
Any advice?
Anyone else out there doing anything with XMPP and ColdFusion?
I have had great success sending and receiving messages with CF and Smack just haven't had the pubsub working yet :)
Thanks!
This has been answered:
There is a second method on the PubSubManager class that accepts two arguments, a connection and a to parameter. Apparently Openfire requires this to parameter and after some experimenting i discovered that it works using pubsub.your.xmpp.address
manager = createObject("java", "org.jivesoftware.smackx.pubsub.PubSubManager").init(XMPPConnection,"pubsub.127.0.0.1");
Maybe this example can be used as a reference for you:
public void login(String Ip,String username,String passwaord)
{
try
{
connConfig = new AndroidConnectionConfiguration(Ip, 5222);
connection = new XMPPConnection(connConfig);
connection.connect();
connection.login(username, passwaord);
pubSubAddress = "pubsub."+ connection.getServiceName();
manager = new PubSubManager(connection,pubSubAddress);
Log.i("MyError","connection success");
}
catch (XMPPException e)
{
Log.i("MyError","connection failed");
e.printStackTrace();
}
}
A normalized example are showed as following:
Publish node:
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.SimplePayload;
public class XmppPubsub_Publisher {
private static XMPPConnection connection = new XMPPConnection("think");
private static String USRE_NAME = "test1";
private static String PASSWORD = "1";
static{
try {
connection.connect();
connection.login(USRE_NAME,PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception{
try{
PubSubManager manager = new PubSubManager(connection);
String nodeId = "test2";
LeafNode myNode = null;
try {
myNode = manager.getNode(nodeId);
} catch (Exception e) {
e.printStackTrace();
}
if(myNode == null){
myNode = manager.createNode(nodeId);
}
String msg = "fsadfasdfsadfasdfd---";
SimplePayload payload = new SimplePayload("message","pubsub:test:message", "<message xmlns='pubsub:test:message'><body>"+msg+"</body></message>");
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>("5", payload);
myNode.publish(item);
System.out.println("-----publish-----------");
}
catch(Exception E)
{E.printStackTrace();}
}
}
Retrieve node:
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.Node;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
public class XmppPubsub_Reciever {
private static XMPPConnection connection = new XMPPConnection("think");
private static String USRE_NAME = "test1";
private static String PASSWORD = "1";
static {
try {
connection.connect();
connection.login(USRE_NAME, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String nodeId = "test2";
PubSubManager manager = new PubSubManager(connection);
Node eventNode = manager.getNode(nodeId);
eventNode.addItemEventListener(new ItemEventListener<PayloadItem>() {
public void handlePublishedItems(ItemPublishEvent evt) {
for (Object obj : evt.getItems()) {
PayloadItem item = (PayloadItem) obj;
System.out.println("--:Payload=" + item.getPayload().toString());
}
}
});
eventNode.subscribe(connection.getUser());
while(true);
}
}

Categories