⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bsbuddyfinderbean.java

📁 一款即时通讯软件
💻 JAVA
字号:
package edu.ou.kmi.buddyspace.plugins.buddyfinder.core;

/*
 * BSBuddyFinderBean.java
 *
 * Project: BuddySpace
 * (C) Copyright Knowledge Media Institute 2005
 *
 *
 * Created on 25 January 2005
 */

import java.util.*;
import javax.swing.JOptionPane;
import org.jabber.jabberbeans.*;
import org.jabber.jabberbeans.util.*;
import edu.ou.kmi.buddyspace.core.*;
import edu.ou.kmi.buddyspace.utils.VectorSet;
import edu.ou.kmi.buddyspace.gui.BSMainFrame;

/**
 * @author  Chris Denham, Knowledge Media Institute, Open University, United Kingdom
 */

public class BSBuddyFinderBean implements PacketListener {
    protected MessengerBean msgBean = null;
    protected BSRosterBean rosterBean = null;
    protected BSPresenceBean presenceBean = null;
    protected final String name = "BuddyFinder";
    protected Vector buddyFinderListeners = null;

    /**
     * Constructor
     */
    private BSBuddyFinderBean() {
        buddyFinderListeners = new Vector();
    }

    private static BSBuddyFinderBean buddyFinderBean = null;
    // use singleton because it causes problems if we have more than one BF bean
    public static BSBuddyFinderBean getInstance()
    {
        if (buddyFinderBean == null) buddyFinderBean = new BSBuddyFinderBean();
        return buddyFinderBean;
    }

    public void setRosterBean(BSRosterBean rosterBean) {
        this.rosterBean = rosterBean;
    }

    public void setPresenceBean(BSPresenceBean presenceBean) {
        this.presenceBean = presenceBean;
    }

    /**
     * Sets existing and connected <code>MessengerBean</code>.
     * Then this is registered as listener for message packets.
     */
    public void setMessengerBean(MessengerBean msgBean) {
        if (this.msgBean != null)
            this.msgBean.delPacketListener(this);
        this.msgBean = msgBean;
        if (msgBean != null)
            msgBean.addPacketListener(this);
    }

    /**
     * Returns currently used <code>MessengerBean</code>.
     */
    public MessengerBean getMessengerBean() {
        return msgBean;
    }

    /**
      * Handles <code>Message</code> packet.
      */
    protected void handleMessage(Message msg) {

        if ((new String("error")).equals(msg.getType()))
            return;

        JID jid = msg.getFromAddress();
        String originID = new String(jid.getUsername() + "@" + jid.getServer());

        if (!originID.equalsIgnoreCase(BSMainFrame.buddyFinderBotJID)) return;


        String body = msg.getBody();
        String subject = msg.getSubject();
        if (subject == null) return;

        // It's a bit naff to rely on subject line to filter messages
        // from buddyfinder for the map view. What I really need to do
        // is create a new kind of jabber extension packet to hold the
        // information.
        String header = "Results for display in window id=";
        if (!subject.startsWith(header)) return;

        String id = subject.substring(header.length());

        Collection buddies = new VectorSet();
        StringTokenizer st = new StringTokenizer(body, "\n");
        String command = null;
        boolean urlList = false;
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (token.startsWith("query ="))
            {
                buddies.add(token);
                break;
            }
            if (token.equals("URLs"))
            {
                buddies.add(token + st.nextToken(""));
                break;
            }

            String record = token.toLowerCase();
            if (record.startsWith("find "))
                command = record;
            else
                buddies.add(record);

        }
        if (command != null) postProcess(command, buddies);
        fireBuddyFinderResultReceived(buddies, id);
    }

    /**
     * Perform any additional parts of the search that can only be done on the
     * requesting users connection. e.g. roster searches.
     */
    private void postProcess(String command, Collection buddies)
    {
        StringTokenizer st = new StringTokenizer(command, " ");
        if (!st.hasMoreTokens()) return;
        boolean showOffline = false;
        boolean namesearch = false;
        StringBuffer keys = new StringBuffer();
        st.nextToken(); // skip 'find'
        while (st.hasMoreTokens())
        {
            String word = st.nextToken();
            if (word.startsWith("-"))
            {
                if (word.equals("-namesearch")) namesearch = true; else
                if (word.equals("-all")) showOffline = true;
            } else {
                keys.append(word + " ");
            }
        }
        if (namesearch) searchRoster(keys.toString(), buddies);
        if (!showOffline) removeOfflineUsers(buddies);
    }

    /**
     * Invoked when a message packet is received.
     */
    public void receivedPacket(PacketEvent event) {
        Packet packet = event.getPacket();
        if (packet instanceof Message) {
            Message msg = (Message) packet;
            handleMessage(msg);
        }
    }
    /**
     * Invoked when a message packet send failes.
     */
    public void sendFailed(PacketEvent event) {
    }

    /**
     * Invoked when a message packet is sent.
     */
    public void sentPacket(PacketEvent event) {
    }

    /**
     * Frees all object bindings to allow object destroy
     */
    protected void prepareToDestroy() {
        removeAllBuddyFinderListeners();
        if (msgBean != null) {
            msgBean.delPacketListener(this);
            msgBean = null;
        }
    }

    /**
     * Adds <code>BuddyFinderListener</code> to listeners notified when
     * buddyfinder results arrive.
     */
    public void addBuddyFinderListener(BSBuddyFinderListener listener) {
        if (listener == null) return;
        if (!buddyFinderListeners.contains(listener)) {
            buddyFinderListeners.addElement(listener);
        }
    }

    /**
     * Removes <code>BuddyFinderListener</code> from listeners notified when
     * buddyfinder results arrive.
     */
    public void removeBuddyFinderListener(BSBuddyFinderListener listener) {
        if (listener == null) return;
        buddyFinderListeners.removeElement(listener);
    }

    /**
     * Removes all listeners notified when buddyfinder results arrive.
     * This can be used before to free dependencies and allow dispose of
     * all objects.
     */
    public void removeAllBuddyFinderListeners() {
        buddyFinderListeners.clear();
    }

    /**
     * Notifies buddyFinder listeners that a buddyfinder result has arrived.
     */
    protected void fireBuddyFinderResultReceived(Collection users, String requestID) {
        for (Enumeration e = buddyFinderListeners.elements(); e.hasMoreElements(); ) {
            BSBuddyFinderListener listener = (BSBuddyFinderListener) e.nextElement();
            listener.buddyFinderResultReceived(users, requestID);
        }
    }

    /** Calling this method sends command to buddyfinder.
     * Buddyfinder responds with results that are directed back to the
     * the window with the specified id.
     */
    public void buddyFinderRequest(String command, String requestID) {
        if (msgBean == null)return;

        try {
            MessageBuilder mb = new MessageBuilder();
            mb.setToAddress(new JID(BSMainFrame.buddyFinderBotJID));
            mb.setBody(command);
            mb.setType("chat");
            // It's important to identify the request so that the response
            // can be routed back to the window issuing the request.
            mb.setSubject(requestID);
            msgBean.send((Message) mb.build());
        } catch (InstantiationException e) {
            JOptionPane.showMessageDialog(null,
                                          "Error sending message to BuddyFinder",
                                          "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Add JIDs in roster that match keys to the users collection.
     */
    private void searchRoster(String keys, Collection users)
    {
        Enumeration e = rosterBean.entries();
        while (e.hasMoreElements())
        {
            RosterItem item = (RosterItem) e.nextElement();
            String name = item.getFriendlyName();
            String n = name.toLowerCase();
            String j = item.getJID().toString().toLowerCase();
            StringTokenizer st = new StringTokenizer(keys.toLowerCase(), " ");
            while (st.hasMoreTokens())
            {
                String k = st.nextToken();
                if (k.equals("and") || k.equals("or") || k.equals("not"))
                {
                    JOptionPane.showMessageDialog(null, "Logical operators (AND/OR/NOT) are not supported in Username searches.");
                    return;
                }
                if (n.indexOf(k) != -1 || j.indexOf(k) != -1 || k.equals("*")) {
                    String jid = item.getJID().toString().toLowerCase();
                    users.add(jid);
                }
            }
        }
    }

    /**
     * Modifies the specified list so it contains only users that are online.
     */
    private void removeOfflineUsers(Collection users)
    {
        Iterator it = users.iterator();
        Collection onlineUsers = new HashSet();
        while (it.hasNext())
        {
            String user = (String)it.next();
            BSPresenceInfo pi = presenceBean.getPresence(new JID(user));
            if (pi != null) onlineUsers.add(user);
        }
        users.retainAll(onlineUsers);
    }
}

⌨️ 快捷键说明

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