xmppmanager.java

来自「java 开发的sip软电话 源码 jain sip」· Java 代码 · 共 380 行

JAVA
380
字号
package net.java.mais.xmpp;
import java.util.Collection;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.packet.VCard;

/**
 * <p>Title: Netsite TudoMais</p>
 * <p>Description:JAIN-SIP Audio/Video phone application</p>
 * <p>Copyright: Copyright (c) 2006</p>
 * <p>Organisation: CTBC Telecom / Netsite </p>
 * @author Thiago Rocha Camargo (barata7@yahoo.com)
 */

public class XMPPManager implements RosterListener, PacketListener, PacketFilter, ConnectionListener {
	private Roster roster;
	private Timer keepAliveTimer = null;
	private XMPPConnection connection;
	String server;
	String user;
	String password;
	public Vector contacts = new Vector();
	public Vector chats = new Vector();	
	public XMPPListener xmppListener = null;
	private String show="online"; 
	private String status="";
	private VCard myCard = new VCard();
	
	public XMPPManager(XMPPListener xl){
		xmppListener=xl;
	}
	
	public void connect(String s, String u, String p, String status) throws XMPPException{
		
		server = s;
		user = u;
		password = p;
		
		if(connection!=null && connection.isConnected()) return;
		connection = new XMPPConnection(server);
		connection.login(user,password,"TudoMais",false);
		roster=connection.getRoster();
		roster.setSubscriptionMode(Roster.SUBSCRIPTION_ACCEPT_ALL);
		myCard.load(connection);		
		roster.addRosterListener(this);
		connection.addPacketListener(this,this);
		keepAliveTimer = new Timer();
		scheduleKeepAlive(1800);
		setStatus(status);
		loadContacts();
	}	
	
    private void scheduleKeepAlive(int sec){   	
    	KeepAliveTask kat = new KeepAliveTask(sec);
    	if(keepAliveTimer!=null)
    	keepAliveTimer.schedule(kat,sec*1000,sec*1000);    	
    	System.out.println("XMPP KEEP Schedule");
    }
	
	public void connect() throws XMPPException{
		if(connection!=null && connection.isConnected()) return;
		connection = new XMPPConnection(server);
		connection.login(user,password);
	}
	
	public void disconnect() throws XMPPException{
		
		for(int i=0;i<chats.size();i++)
			((ChatWindow)chats.get(i)).close();
		
		chats = new Vector();
		contacts = new Vector();
		if(keepAliveTimer!=null)
		keepAliveTimer.cancel();
		
		connection.close();	
	}
	
	public boolean addContact(String contact, String nick){
		try{
		roster.createEntry(contact,nick,null);
		}catch(XMPPException e){
			return false;
		}
		return true;
	}
	
	public boolean remove(String contact){
    	   RosterEntry re = roster.getEntry(contact);
           try{
           roster.removeEntry(re);
           }catch(XMPPException e){
        	System.out.println("ERRO"); 
        	return false;
           }
      return true;
	}
	
	public void loadContacts(){
		RosterEntry contact;
		contacts = new Vector();
		try{
			for(Iterator i=roster.getEntries();i.hasNext();){
				//roster.removeEntry((RosterEntry)i.next());
				contact = (RosterEntry)i.next();
				contact.getStatus();
				contacts.add(contact);
				//Component cell=IM.getCellRenderer().getTableCellRendererComponent();
			}
		}catch(Exception e){
			
		}
	}
	
	public String getContactsXML(){

		loadContacts();
		
		RosterEntry re=null;
		Presence pe=null;
		String presence=null;
		String subs=null;
		String name=null;
		String status=null;
		String type=null;
		
		String str="";
		String phones="";
		str+="<XMLDocumentObject>";
		
	    str+="<node label=\"Contatos\" isBranch=\"false\" icon=\"teclado\">";
	    phones+="<node label=\"Telefones\" isBranch=\"false\" icon=\"telefone\">";
	    	for(int i=0;i<contacts.size();i++){
	    		re= (RosterEntry)contacts.get(i);
	    		if(re.getUser().indexOf("@")>-1){
	    		pe=roster.getPresence(re.getUser());
   				presence=pe==null?"offline":pe.getMode().toString();
   				name=re.getName()==null||re.getName().equals("")?re.getUser():re.getName();
   				status=pe==null||pe.getStatus()==null?"":pe.getStatus();
   				type=pe==null||pe.getType()==null?"":pe.getType().toString();
	    		str+="<node nick=\"" + re.getName() + "\" label=\"" + name + (status.equals("")?"":" - "+status) + "\" user=\"" + re.getUser() + "\" status=\"" + status + "\" icon=\"" + presence + "\" subscrition=\"" + type + "\" isBranch=\"true\" />";
	    		}else{
    				presence=re.getUser().matches("^0..[7-9][0-9]*$")?"celular":"phone";
	    			phones+="<node nick=\"" + re.getName() + "\" label=\"" + re.getName() +  "\" user=\"" + re.getUser() + "\" status=\"" + status + "\" icon=\"" + presence + "\" subscrition=\"" + type + "\" isBranch=\"true\" />";	    			
	    		}
	    		// 03499778394 - 01699928457
		}
	    str+="</node>";
	    phones+="</node>";

	    // MERGE
	    str+=phones;
	    
		str+="</XMLDocumentObject>";

		System.out.println(str);
		return str;
	}
	
	public ChatWindow addChat(String user){
			
		if(user.indexOf("@")==-1){
			user="0"+user;
		}
		System.out.println("TRY to ADD CHAT WITH: "+user);
		
		ChatWindow co = findChat(user);
		
		System.out.println("Not found");
		
		if(co!=null){
			co.shell.setVisible(true);
			return co;
		}
		
		try{
		Chat chat = connection.createChat(user);
		if(chat!=null){
		RosterEntry re = roster.getEntry(user);		
		ChatWindow cw = null;
		if(re!=null)
		cw = new ChatWindow(chat,re,this);
		else
		cw = new ChatWindow(chat,user,this);		
			if(cw!=null){
				chats.add(cw);
				System.out.println("CHAT ADDED");
				return cw;
			}
		}
		return null;
		}catch(Exception e){
			System.out.println("ERRO ADDCHAT: "+e.toString());
			return null;
		}
	}
	
	public void sendMessage(String user,String msg){
		ChatWindow c=findChat(user);
//		Message message = new Message(user);
//		message.setBody(msg);
		c.sendMessage(msg);
	}
	
	public ChatWindow findChat(String user){
		ChatWindow c=null;
		for(int i=0;i<chats.size();i++){
			c=(ChatWindow)chats.get(i);
			if(c!=null){
			//System.out.println("LOOK: "+c.chat.getParticipant());
			if(c.jid.equals(user))
				return c;
			}
		}
		return null;
	}
	
	public void removeChat(String user){
		ChatWindow c=null;
		for(int i=0;i<chats.size();i++){
			c=(ChatWindow)chats.get(i);
			if(c.jid.equals(user)){
			chats.remove(i);
			}
		}
	}
	
	// Roster Listeners
	
	public void entriesAdded(Collection addresses){		
/*		System.out.println(addresses.toArray()[0].toString());
		Object adr[]=addresses.toArray();
		
		for(int i=0;i<adr.length;i++)
			addContact(adr[i].toString(),adr[i].toString());
*/					
		xmppListener.handlePresenceChanged("","");
	}
    
	public void entriesDeleted(Collection addresses){
		xmppListener.handlePresenceChanged("","");
	}
    
	public void entriesUpdated(Collection addresses){
		xmppListener.handlePresenceChanged("","");
	}
    
	public void presenceChanged(String XMPPAddress){
		xmppListener.handlePresenceChanged("","");
	}
	
	// Presence Changes
	
	public void setShow(String str){
		show=str;
		Presence p = new Presence(Presence.Mode.fromString(str)!=Presence.Mode.INVISIBLE?Presence.Type.AVAILABLE:Presence.Type.UNAVAILABLE);	
		p.setMode(Presence.Mode.fromString(str));
		connection.sendPacket(p);
	}
	
	public String getShow(){
		return show;
	}
	
	public void setStatus(String stat){
		String st[] = stat.split("/");
 		Presence p = new Presence(Presence.Type.AVAILABLE); 		
 		show=st.length>0?st[0]:"online";
		p.setMode(Presence.Mode.fromString(show));
		status=st.length>1?st[1]:"online";
		p.setStatus(status);
		connection.sendPacket(p);
	}
	
	// Connection Listener
	
	public void connectionClosed(){
		
	}
	
	public void connectionClosedOnError(Exception e){
		
		for(int i=0;i<3;i++)		
			try{
				connect(server,user,password,show);
			}catch(Exception ee){
				try{
				Thread.currentThread().sleep(3000);
				}catch(Exception eee){}			
				i=3;
			}
		
	}
	
	// Packet Listeners
	
	public void processPacket(Packet packet){
 		
 		if(packet instanceof Message) {
 			Message msg = (Message)packet;
			String jid = msg.getFrom().split("/")[0];
			ChatWindow chat = findChat(jid);
			if(chat==null) chat=addChat(jid);
			chat.receiveMessage(msg.getBody());	
 		}
 		
 		if(packet instanceof Presence){
 			Presence p = (Presence)packet;
 			if(p.getType()==Presence.Type.AVAILABLE){ 				
 				Presence o = new Presence(Presence.Type.SUBSCRIBED);
 				o.setTo(p.getFrom());
 				connection.sendPacket(o);
 			}
 		} 		
 		//System.out.println("PACKET: "+packet.toString());
 		
 	}
	
	public boolean accept(Packet packet){
		return true;
	}
	
	// Private Classes
	
    private class KeepAliveTask
    extends TimerTask
    {
    	private int sec=0;
    	 
    	public KeepAliveTask(int s){
    		sec=s;    		
    	}
    	
    	public void run(){
    		try{
    			if(connection!=null && connection.isConnected()){
    				setStatus(show+"/"+status);
    			}
    		}finally{
        		try{
   				this.finalize();
    			}catch(Throwable e){    				
    			}
    		}
    		//System.out.println("KEEP SENT");
    	}    	    	
    }

    // VCARD METHODS
    
    public void setNick(String str){    
    	myCard.setNickName(str);
    	try{
    		myCard.save(connection);
    	}catch(XMPPException e){
    		System.out.println("ERRO VCARD: "+e.toString());
    	}
    }
    
    public String getNick(){    
    	return myCard.getNickName();
    }    
    
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?