I am trying to call an RPG Logon program on an AS400 system from JAVA. The issue is whenever I give incorrect parameters, I get a response, such as user ID is incorrect, password is incorrect. When I give an incorrect path to the program, I do get the response saying "Object does not exist." However, when all the parameters are right, I don't get any response and the java program keep running without ending. What could be wrong? Code below:
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
import java.beans.PropertyVetoException;
import java.io.IOException;
/**
* Test program to test the RPG call from Java.
*/
public class CallingAS400PGM {
private static final String HOST = "xxxxxx";
private static final String UID = "yyyyyyy";
private static final String PWD = "zzzzzzz";
public static void main(String[] args) {
String input = "testuser";
String fullProgramName = "/QSYS.lib/SEOBJP10.lib/LOGON.pgm";
AS400 as400 = null;
byte[] inputData;
byte[] outputData;
ProgramParameter[] parmList;
ProgramCall programCall;
try {
// Create an AS400 object
as400 = new AS400(HOST, UID, PWD);
// Create a parameter list
// The list must have both input and output parameters
parmList = new ProgramParameter[2];
// Convert the Strings to IBM format
inputData = input.getBytes("IBM285");
// Create the input parameter
parmList[0] = new ProgramParameter(inputData);
// Create the output parameter
//Prarameterised Constructor is for the OUTPUT LENGTH. here it is 10
parmList[1] = new ProgramParameter(10);
/**
* Create a program object specifying the name of the program and
* the parameter list.
*/
programCall = new ProgramCall(as400);
programCall.setProgram(fullProgramName, parmList);
// Run the program.
if (!programCall.run()) {
/**
* If the AS/400 is not run then look at the message list to
* find out why it didn't run.
*/
AS400Message[] messageList = programCall.getMessageList();
for (AS400Message message : messageList) {
System.out.println(message.getID() + " - " + message.getText());
}
} else {
/**
* Else the program is successfull. Process the output, which
* contains the returned data.
*/
System.out.println("CONNECTION IS SUCCESSFUL");
outputData = parmList[1].getOutputData();
String output = new String(outputData, "IBM285").trim();
System.out.println("Output is " + output);
}
} catch (PropertyVetoException | AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException e) {
System.err.println(":: Exception ::" + e.toString());
} finally {
try {
// Make sure to disconnect
if (as400 != null) {
as400.disconnectAllServices();
}
} catch (Exception e) {
System.err.println(":: Exception ::" + e.toString());
}
}
}
}
Carefully think about what parameter type,number of parameters are accepting from AS400 RPG program, and use communication only USERID.
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400Text;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
public class CallingAS400PGM {
private static final String HOST = "192.168.1.1";//AS400 IP
private static final String UID = "UNAME"; //userid
private static final String PWD = "PWORD"; //password
public static void main(String[] args) {
//AS400 RPG progam path
String fullProgramName = "/QSYS.LIB/PBFORM12.LIB/PBFORM12CL.PGM";
AS400 as400 = null;
ProgramParameter[] parmList;//parameter list witch is accepting AS400 RPG program
ProgramCall programCall;
try {
// Create an AS400 object
as400 = new AS400(HOST, UID, PWD);
// Create a parameter list
// The list must have both input and output parameters
parmList = new ProgramParameter[2];
// Convert the Strings to IBM format
AS400Text nametext1 = new AS400Text(2);
AS400Text nametext2 = new AS400Text(200);
// Create the input parameter // get the exact patameter type and
length, if not this not be working
parmList[0] = new ProgramParameter(nametext1.toBytes("1"),2);
parmList[1] = new ProgramParameter(nametext2.toBytes("Ravinath
Fernando"),200);
// Create the output parameter
programCall = new ProgramCall(as400);
programCall.setProgram(fullProgramName, parmList);
if (!programCall.run()) {
/**
* If the AS/400 is not run then look at the message list to
* find out why it didn't run.
*/
AS400Message[] messageList = programCall.getMessageList();
for (AS400Message message : messageList) {
System.out.println(message.getID() + " - " + message.getText());
}
} else {
System.out.println("success");
/**
* Else the program is successfull. Process the output, which
* contains the returned data.
*/
//use same parameter type which will be return from AS400 program
AS400Text text1 = new AS400Text(2);
System.out.println(text1.toObject(parmList[0].getOutputData()));
AS400Text text2 = new AS400Text(200);
System.out.println(text2.toObject(parmList[1].getOutputData()));
}
as400.disconnectService(AS400.COMMAND);
//-----------------------
} catch (Exception e) {
e.printStackTrace();
System.err.println(":: Exception ::" + e.toString());
} finally {
try {
// Make sure to disconnect
if (as400 != null) {
as400.disconnectAllServices();
}
} catch (Exception e) {
System.err.println(":: Exception ::" + e.toString());
}
}
}
}
Related
I called eFinans e-Archive service. faturaOlustur method expects me a json string. I created an variable and assing json string value and giving input parameter. Input parameter expects me String. But variable side expects me only string. I can't solve a solution that problem. Please examine and give me a clue please.
public static void eArsivConnectorClient(){
String username = "username";
String password = "password";
String endPointUrl = "https://earsivtest.efinans.com.tr:443/earsiv/ws/EarsivWebService";
try{
EarsivWebService_Service earsivService = new EarsivWebService_Service(new URL (endPointUrl + "?wsdl"));
earsivService.setHandlerResolver(new SoapHandlerResolver(username, password));
EarsivWebService earsivPort = earsivService.getEarsivWebServicePort();
WSBindingProvider bindingProvider = (WSBindingProvider) earsivPort;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endPointUrl);
try
{
EarsivServiceResult srvResult = new EarsivServiceResult();
Holder<Belge> output = null;
String[] input = new String[]{"vkn","4250566851", "sube","DFLT1", "kasa","DFLT1",
"islemId","12232", "erpKodu","ERP1"};**
Belge fatura = new Belge();
fatura.setBelgeFormati(BelgeFormatiEnum.UBL);
Path path = Paths.get("C:\\RNK2022000002605.xml");
byte[] value = Files.readAllBytes(path);
fatura.setBelgeIcerigi(value);
EarsivServiceResult arsivBelge = earsivPort.faturaOlustur(input, fatura , output);
System.out.println(arsivBelge.getResultCode());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}catch(Throwable t){
t.printStackTrace();
}
}
I am using smack API & made 2 client using java, I am using prosody XMPP server on windows platform this is my code (prosody is quite similar to open-fire server)
import java.util.Collection;
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.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class TextMessageReceive implements MessageListener {
XMPPConnection connection;
public void login(String userName, String password)throws XMPPException{
ConnectionConfiguration config = new ConnectionConfiguration("localhost",5222,"example.com");
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection = new XMPPConnection(config);
//connection.connect();
// System.out.println("Connected to " + connection.getHost());
//connection.login(userName, password);
onTimerExpiry(userName, password);
System.out.println("Logged in as " + connection.getUser());
}
public void onTimerExpiry(String userName, String password) {
if (connection != null && connection.isConnected()) {
connection.disconnect();
System.out.println("disconnecting...................");
}
try{
if (connection != null) {
connection.connect();
System.out.println("Logged in as " + connection.getHost());
connection.login(userName, password);
System.out.println("Logged in as " + connection.getUser());
}
}catch(XMPPException e){
e.printStackTrace();
}
}
public void sendMessage(String message, String to) throws XMPPException{
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
System.out.println("message= "+message+ " received from " +to );
}
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){
System.out.println("Inside the process message");
String string =message.getBody();
String from=message.getFrom();
// byte[] byteArray = Base64.decodeBase64(string.getBytes());
// if(message.getType() == Message.Type.chat)
// {
//// // Print the decoded string
// String decodedString = new String(byteArray);
// System.out.println( "Decoded message = " + decodedString);
System.out.println("message= "+string+ " received from " +from );
}
public static void main(String args[]) throws XMPPException {
TextMessageReceive c = new TextMessageReceive();
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
// Enter your login information here
c.login("yuvi", "yuvi");
/*
* Displays the users list
*/
//c.displayBuddyList();
try{
Thread.sleep(30000);
String string ="We are sending message to mhealth";
// byte[] byteArray = Base64.encodeBase64(string.getBytes());
// String encodedString = new String(byteArray);
c.sendMessage(string, "mhealth#example.com");
// Print the encoded string
System.out.println( "Message = " + string);
// c.sendMessage("Message coming from yuvi", "yuvi#inpudw014438a");
}catch (Exception e) {
e.printStackTrace();
}
}
}
actually I am using prosody configure for that particular code if first time I do login then no problem with the code but whenever I am trying to connect second time I am getting exception unless I close the client from telnet admin console.here I made onTimerExpiry() method for disconnecting the client if client is already connect but my client is being disconnect & gave me below exception. guys please tell this right or wrong please suggest me...
The exception I get is:
stream:error (text) at
org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:260) at
org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:43) at
org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)
I got the answer .I have to call the disconnect() method from main()
public static void main(String args[]){
TextMessageReceive c = new TextMessageReceive();
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
// Enter your login information here
c.login("yuvi", "yuvi");
c.disconnect();
/*
* Displays the users list
*/
}
this is working & not getting any exception in o/p
so here is my problem. I simply can't get my applet&php communication going. I'm using the below class for communication
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;
public class POST {
private String postParameters = "";
private String webPage;
private Vector<String>names;
private Vector<String>values;
public POST(){
values = new Vector<String>();
names = new Vector<String>();
}
/**
* Adds a post variable (page.php?name=value)
*
* #param name the variable name
* #param value the variable value, can be set to null, the url will simply become &name instead of &name=value
* null
*/
public void addPostValue(String name, String value) throws UnsupportedEncodingException {
if (value == null) {
try {
postParameters += "&" + URLEncoder.encode(name, "UTF-8");
names.add(name);
values.add("");
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
postParameters += "&" + URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
names.add(name);
values.add(value);
}
}
/**
* Send post data without waiting for site output
*
* #return true if sending data terminated succesfully
*/
public boolean sendPost() {
try {
if (webPage == null || webPage.equals("")) {
throw new Exception("Empty url");
}
URL url = new URL(webPage);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postParameters);
wr.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
}
postParameters = "";
return true;
}
/**
* Sends data, then waits for site output
*
* #return null if no data is received, or a String containing the data
*/
public String sendPostWithReturnValue() {
String returnValue = "";
try {
if (webPage == null || webPage.equals("")) {
throw new Exception("Empty url");
}
URL url = new URL(webPage);
URLConnection conn =
url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr =
new OutputStreamWriter(conn.getOutputStream());
wr.write(postParameters);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
returnValue += line + "\n";
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
postParameters = "";
values = null;
names=null;
values = new Vector<String>();
names = new Vector<String>();
return returnValue;
}
/**
* Sets the page to point at for sending post variables
*
* #param webPageToPointAt the page that will receive your post data
*/
public void setWebPageToPointAt(String webPageToPointAt) {
webPage = webPageToPointAt;
}
/**
* #returns A Nx2 matrix containing all parameters name and values
*/
public String[][] getParameters() {
String[][] str = new String[names.size()][2];
for (int i = 0; i < str.length; i++) {
str[i][0] = names.get(i);
str[i][1] = values.get(i);
}
return str;
}
}
And this is the function within my applet that is calling it
public void postajRezultat(int brojP, int brojH) throws IOException{
P = Integer.toString(brojP);
H = Integer.toString(brojH);
POST post = new POST();
post.addPostValue("brojH", H);
post.addPostValue("brojP", P);
post.addPostValue("ime", ime);
post.setWebPageToPointAt(getCodeBase().toString() + "/includes/save.php");
post.sendPost();
And last this is the simple php script that should show the results of POST. Please help me, I've tried everything and i won't work...The error php gives me is "Undefined index "ime", "brojP", "brojH".
<?php
mysql_connect ("127.0.0.1","root","vertrigo");
mysql_select_db ("projekt_db");
$ime=$_POST['ime'];
$brojP=$_POST['brojP'];
$brojH=$_POST['brojH'];
echo("Test");
echo($brojP . "" . $ime . "" . $brojH);
$a=mysql_query("INSERT INTO highscore ('id', 'ime', 'brojP', 'brojH') VALUES (NULL, '" . $ime . "'," . $brojP . "," . $brojH . ")");
?>
Why don't you use some kind of framework for HTTP communication?
In my experience Apache HTTP Client is excelent solution for such operations, it makes request very easy to implement eg.
HttpPost post=new HttpPost("where_to_send_post_request_url")
post.setEntity(createdURLEncodedEntity) // here you add your post parameters as entity
response=client.execute(post); // execute your post
String page=EntityUtils.toString(response.getEntity()); // get response as string content eg html
EntityUtils.consume(response.getEntity()); // release connection etc.
isn't that simple? You don't have to reinvent the wheel again:)
I am using ErrorCollector in my Junit test case with the aim of printing out the errors and not stopping at the erroneous locations.
I successfully tried the ErrorCollector by using methods without parameters. However to reduce code duplicacy (i wrote the same method 6 times
without the parameter ; since i am using 6 files for comparison as seen in my code),
I would like to have a generic method that can be used to achieve the same purpose of printing out errors and continuing with the check.
When i tried using the method with a parameter i got the exception "Method should have no parameters"..
The following is my code.
import org.gdal172.ogr.ogr;
import org.hamcrest.CoreMatchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class DGNTester {
private ReadDGN readDgn = new ReadDGN();
private LinkedHashMap<String, Integer> layerMapCountForCompare = new LinkedHashMap<String, Integer>();
#Rule
public ErrorCollector collector = new ErrorCollector();
private File output = null;
static {
// perform OGR format registration once
if (ogr.GetDriverCount() == 0)
ogr.RegisterAll();
}
/**
* #param args
*/
public static void main(String[] args) {
DGNTester dTest = new DGNTester();
String dgnFileName_43k10 = "input\\43k10.dgn";
String dgnFileName_43k11 = "input\\43k11.dgn";
String dgnFileName_43k12 = "input\\43k12.dgn";
//The six files iam using as input.
dTest.test(dgnFileName_43k10, "dvd");
dTest.test(dgnFileName_43k10, "all");
dTest.test(dgnFileName_43k11, "dvd");
dTest.test(dgnFileName_43k11, "all");
dTest.test(dgnFileName_43k12, "dvd");
dTest.test(dgnFileName_43k12, "all");
}
#Test
public void test(String fileName, String inputType) {
System.out.println("FOR FILE -->" + fileName);
System.out
.println("---------------------------------------------------------------------------------------------------");
String fileIdentifier = fileName.substring(6, 11);
String dstFilePath = null;
String outputName = null;
if (layerMapCountForCompare != null)
layerMapCountForCompare.clear();
if (inputType.equals("dvd")) {
dstFilePath = "F:\\eclipse_helios_3.6.1_64_bit_with_jre_and_add-ons\\eclipse\\Resources\\DST\\dvd.dst";
outputName = "output\\outputfile_" + fileIdentifier
+ "_dvd.dst.txt";
}
if (inputType.equals("all")) {
dstFilePath = "F:\\eclipse_helios_3.6.1_64_bit_with_jre_and_add-ons\\eclipse\\Resources\\DST\\AllLayers.dst";
outputName = "output\\outputfile_" + fileIdentifier + ".txt";
}
layerMapCountForCompare = readDgn.getLayerFeatureCount(fileName,
dstFilePath);
// Read the text output file and Compare with the map. These are the six out put files against each input file
output = new File(outputName);
if (output.exists()) {
try {
Set keys = layerMapCountForCompare.keySet();
Iterator itr = keys.iterator();
String key = "";
Integer val;
String line;
BufferedReader br = new BufferedReader(new FileReader(output));
while ((line = br.readLine()) != null && itr.hasNext()) {
key = (String) itr.next();
val = layerMapCountForCompare.get(key);
String compare = key + "=" + val;
compare.trim();
line.trim();
//When i print this out in a positive scenario; i am able to see the values of 'compare' and 'line' as same
/*System.out.println("COMPARE >>> " + compare
+ " --------------- AND --------- Line " + line);*/
assertEquals("Comparing input and output", line, compare);
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("Output file does not exist");
}
}
public void assertEquals(String msg, Object expected, Object actual) {
collector.checkThat(actual, CoreMatchers.equalTo(expected));
}
}
In my previous example; where i did not use parameters;
Result result = JUnitCore.runClasses(DGNTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
if (result.wasSuccessful()) {
System.out.println("Tests finished successfully...");
}
This code helped in triggering the test methods and print the appropriate methods.
Can you please guide me as to how I can use my generic method thet takes two parameters to utilize the ErrorCollector.
How to utlilize Error Collector for junit testing methods with parameters
The #Test annotation doesn't support test methods with parameters in the signature.
Example:
Trying to run the method brokenTest an exception will be thrown. A correct test method in JUnit should look like correctTest:
/** This method uses parameters in the signature. It will not work! */
#Test
public void brokenTest(String fileName) {...}
/** This correct test method has no parameters in its signature. */
#Test
public void correctTest() {...}
Parameterized tests with JUnit
To support parameterized testing you can use the #RunWith(Parameterized.class) annotation (class-level).
The test class needs a static method that returns the parameters in an Iterable (like a List object). Annotate this method with #Parameters.
Furthermore you need a public(!) member variable for each parameter used, each one annotated with #Parameter(0), #Parameter(1), and so on.
Thus JUnit will run testWithParameters() for each test case produced with the createParameters() method. It will automatically assign the correct parameters to the #Parameter(N) fields (firstParameter/secondParameter).
You can produce as many parameters as you need.
Use these parameters in your test methods as needed by refering to their field names.
Example with an excerpt of the class you provided:
#RunWith(Parameterized.class)
public class DGNTester {
#Rule
public ErrorCollector collector = new ErrorCollector();
/**
* Method that generates the parameters.
* Each testValues.add(...) line produces a new test case.
*
* #return Array with test values.
*/
#Parameters
public static Iterable<Object[]> createParameters() {
List<Object[]> testValues = new ArrayList<>();
try {
testValues.add(new Object[]{"pre-Case1-Value1", "Case1-Value2"});
testValues.add(new Object[]{"Case2-Param1", "Case2-Value2"});
testValues.add(new Object[]{"pre-Case3-Value1", "Case3-Value2"});
}
return testValues;
}
/** The first parameter. */
#Parameter(0)
public String firstParameter;
/** The second parameter. */
#Parameter(1)
public String secondParameter;
/** Test using the parameters generated by createParameters().
* In this example we check, if the first parameter is equal to the
* concatenation of the String "pre-" and the second parameter */
#Test
public void testWithParameters() {
assertThat("Wrong parameter values", firstParameter,
is("pre-" + secondParameter));
}
...
}
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);
}
}