Friday, September 23, 2005

Writing a XMPP chat client in Java (Google Talk)

I think I just start off to the topic, firstly u need a 3rd-party library "smack.jar"+"smackx.jar" which extracted from "smack-2.0.0.zip". Get the file from here !

I'm using "javax.swing" classes to build the UI, below is a brief design layout:
+-----------------------------------------------+
| Login : __________ | <---- login name (e.g.: yourmail.google.com)
| Password: ________ | Login| | <---- password (e.g.: google mail password)
+-----------------------------------------------+
| +------------------------------+ | Send | |
| | | |
| | | |
| +------------------------------+ | quit | |
| _____________________________ V | <--- friend's list
| _______________________________ | <---- chat message here
+-----------------------------------------------+

Now u get what u needed, put the libraries in a the classpath so that your Java compiler can find it.
Here's the code and I'll explains line by line in comments (codes are meant to be small to save up space, simply cut and paste to a textpad for the aid of reading):
____________________________________________________________________________

ChatClient.java
____________________________________________________________________________

package com.avatar.chat;

// import swing classes
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

// import smack classes
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.filter.*;


// packet listener will required you to implement a method
// called
"processPacket(Packet packet)" which lets you
// go lower level to handle the in/out packets better

public class ChatClient extends JFrame implements ActionListener, PacketListener{
private JButton btnLogin, btnSend, btnQuit;
private JTextArea taChatArea;
private JTextField tfChatMessage, tfLoginName;
private JComboBox cbOpponent;
private JPasswordField pfLoginPassword;

// GoogleTalkConnection is one of the class by Smack
private GoogleTalkConnection con = null;

// GroupChat will allowed you to listen to more than 1 opponent
private GroupChat chat = null;
private String login_name = "";
private String login_password = "";
private String opponent = "";
private boolean isLogin = false;

// require class -- PacketFilter and PacketCollector, explain below
private PacketFilter filter = null;
private PacketCollector myCollector = null;

// Message is a class to hold all data which extracted from the packet,
// e.g. sender, receiver, timestamp, message ... etc

private Message msg = null;

public ChatClient(){
super("Chat Client");

setSize(400,300);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(0,0));
initComponents();

setVisible(true);
}

public void initComponents(){
btnLogin = new JButton("Login");
btnLogin.addActionListener(this);
btnSend = new JButton("Send");
btnSend.setMnemonic(KeyEvent.VK_ENTER);
btnSend.addActionListener(this);
btnQuit = new JButton("Quit");
btnQuit.addActionListener(this);
taChatArea = new JTextArea(10,40);
taChatArea.setEditable(false);
JScrollPane chatScroller = new JScrollPane(taChatArea);
chatScroller.setPreferredSize(new Dimension(300, 200));
chatScroller.setMinimumSize(new Dimension(300, 200));
chatScroller.setAlignmentX(Component.LEFT_ALIGNMENT);
tfChatMessage = new JTextField(40);
tfLoginName = new JTextField(10);
cbOpponent = new JComboBox();
cbOpponent.setEditable(true);
pfLoginPassword = new JPasswordField(10);

JPanel pnlButton = new JPanel(new GridLayout(2,1,0,0));
JPanel pnlLogin = new JPanel(new GridLayout(3,2,0,0));
JPanel pnlMessage = new JPanel(new GridLayout(2,1,0,0));

pnlLogin.add(new JLabel("User Name:"));
pnlLogin.add(tfLoginName);
pnlLogin.add(new JLabel("Password:"));
pnlLogin.add(pfLoginPassword);
pnlLogin.add(new JLabel("press here to login ->"));
pnlLogin.add(btnLogin);
pnlButton.add(btnSend);
pnlButton.add(btnQuit);
pnlMessage.add(cbOpponent);
pnlMessage.add(tfChatMessage);

setChat(false);

add(pnlLogin, BorderLayout.NORTH);
add(pnlButton, BorderLayout.EAST);
add(chatScroller, BorderLayout.CENTER);
add(pnlMessage, BorderLayout.SOUTH);
}

// disable sending meassage when variable 'mark' is false (offline), and vice-versa
public void setChat(boolean mark){
tfChatMessage.setEnabled(mark);
cbOpponent.setEnabled(mark);
btnSend.setEnabled(mark);
}

// clean up jobs appoint exit
public void logout(){
if(con!=null){
con.close();
}
cbOpponent.removeAllItems();
}

// when user logged in, set the flag to true (online)
public boolean login(String login_name,String login_password){

// get textfield's username
this.login_name = login_name;

// get passwordfield's password
this.login_password = login_password;
boolean flag = false;

try{
con = new GoogleTalkConnection();
con.login(login_name, login_password);

// filter the XML packet into a PacketCollector (much like a queue),
// so that you can get them back later

filter = new AndFilter(
new PacketTypeFilter(Message.class),
new FromContainsFilter(opponent));
myCollector = con.createPacketCollector(filter);

// initialise your chatgroup
chat = con.createGroupChat(login_name+"'s Chat");

// initialise your message
msg = new Message();

// get all user from your friends list
Roster roster = con.getRoster();
for (Iterator i=roster.getEntries(); i.hasNext(); ) {
RosterEntry re = (RosterEntry)i.next();
cbOpponent.addItem(re.getUser());

// Register the listener.
}

con.addPacketListener(this, filter);

setChat(true);
flag = true;
}catch(Exception ex){
ex.printStackTrace();

// any thing during login, disable user to send message
setChat(false);
flag = false;
}finally{
return flag;
}
}

public void windowClosing(WindowEvent we){
logout();
}


// implementing processPacket for PacketListener interface
public void processPacket(Packet packet) {
// Put the incoming message on the chat history or chat board.
Message msg = (Message)packet;
taChatArea.append(msg.getFrom()+
": "+msg.getBody()+"\n");
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==btnLogin){
String test = btnLogin.getLabel();
if(test.equals("Login")){
isLogin = login(tfLoginName.getText().toString().trim(),
pfLoginPassword.getText().toString().trim());
btnLogin.setLabel("Logout");
}else if(test.equals("Logout")){
logout();
setChat(false);
isLogin = false;
btnLogin.setLabel("Login");
}
}else if(e.getSource()==btnSend){
opponent = cbOpponent.getSelectedItem().toString();
String content = tfChatMessage.getText().toString();
if(isLogin){
try{
msg.setTo(opponent);
msg.setBody(content);
chat.sendMessage(msg);

// append your sent message to chat board
taChatArea.append(login_name+": "+tfChatMessage.getText()+"\n");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
else if(e.getSource()==btnQuit){
logout();
System.exit(0);
}
}

public static void main(String[] args){
ChatClient c = new ChatClient();
}
}

___________________________________________________________
End of
"ChatClient.java"
___________________________________________________________
Thanks to Smack by JiveSoftware, online messager never got easier to write!

The final output should looks like this, still depends on platform and versioning of JDK.

Other resoures:

[NOTE: Smack is a trademark of Jive Software, Google Talk is a trademark of Google.]

Thursday, September 08, 2005

WSDL Sample

Before porting the web service module into a J2EE application, firstly lets look at how I get a stock quote in a normal Java concole.

As I will continue on application of WSDL on my next post ... .

Below is the full generic code to demostrate on calling a WSDL:

//
// XMethods sample client for the Stock Quote service
//

import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

public class StockQuoteClient{

public static float getQuote (URL url, String symbol) throws Exception {

Call call = new Call ();

// Service uses standard SOAP encoding
String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
call.setEncodingStyleURI(encodingStyleURI);

// Set service locator parameters
call.setTargetObjectURI ("urn:xmethods-delayed-quotes");
call.setMethodName ("getQuote");

// Create input parameter vector
Vector params = new Vector ();
params.addElement (new Parameter("symbol", String.class, symbol, null));
call.setParams (params);

// Invoke the service ....
Response resp = call.invoke (url,"");

// ... and evaluate the response
if (resp.generatedFault ()) {
throw new Exception();
} else {
// Call was successful. Extract response parameter and return result
Parameter result = resp.getReturnValue ();
Float rate=(Float) result.getValue();
return rate.floatValue();
}
}

// Driver to illustrate service invocation
public static void main(String[] args) {
try {
URL url=new URL("http://services.xmethods.net:80/soap");
String symbol= args[0];
float quote = getQuote(url,symbol);
System.out.println(quote);
}
catch (Exception e) {e.printStackTrace();}
}
}