1. 程式人生 > >構建可除錯的openfire外掛

構建可除錯的openfire外掛

在http://blog.csdn.net/yezis/article/details/38313151中,以及很多博文都寫過關於openfire的外掛開發方式,都是新建一個專案去編寫openfire外掛,一開始我也是用的這種方式,後來放棄了,因為當外掛功能趨於複雜後,不能除錯是一個很大的問題,所以,我換了一種開發openfire外掛的方式。

首先,必須使用openfire的原始碼,這是必須的,具體的方法可以自行尋找。

當部署完openfire的原始碼後,我們可以看法原始碼中有許多plugins關鍵字,其實這都是一個個外掛


這些包的命名方式都是 src/plugins/外掛名/src/java

之後在src/plugins資料夾下我們隨便開啟一個資料夾:


資料夾的命名就是外掛的名字;lib存放外掛所使用的第三方jar包;src為外掛的原始碼;plugin.xml為外掛的配置檔案,很重要。其餘的是一些圖示與說明文件

好的openfire自帶外掛的結構就是這個樣子,現在我們依照例子,建立自己的openfire外掛。

一、按照下圖操作,建立一個原始碼包


原始碼包的命名規則為:src/plugins/外掛名/src/java


二、建立外掛原始碼

建立完成後,在src/plugins/yezi/src/java下建立一個包,並在包下建立一個外掛入口類,結構與類的原始碼如下:


TestPlugin.java

package net.yezi.openfire.plugin;

import java.io.File;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.xmpp.packet.Packet;

public class TestPlugin  implements Plugin, PacketInterceptor {
	
    private InterceptorManager interceptoerManager;
    
    public TestPlugin() {  
        interceptoerManager = InterceptorManager.getInstance();  
    }
    
    /*
     * message Interceptor
     * @see org.jivesoftware.openfire.MessageRouter.route(Message)
     */
	@Override
    public void interceptPacket(Packet packet, Session session,  
            boolean incoming, boolean processed) throws PacketRejectedException {  
    	
		System.out.println(packet);
    	
    }
    
    @Override  
    public void initializePlugin(PluginManager manager, File pluginDirectory) {  
        interceptoerManager.addInterceptor(this);  
    }  
  
    @Override  
    public void destroyPlugin() {  
        interceptoerManager.removeInterceptor(this);  
    }  
    
}

簡單點說就是,如果openfire收到了來自終端聊天的資料後,就會把聊天說句的節點打印出來,就是運行了interceptPacket方法

三、建立外掛宣告檔案

之後,開啟專案根目錄下開啟src/plugins/yezi資料夾,並建立一個lib資料夾,拷貝其他目錄下的說明檔案:


修改plugins.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<plugin>
	<!-- 這是外掛的入口類地址 -->
	<class>net.yezi.openfire.plugin.TestPlugin</class>
 
	<!-- Plugin meta-data -->
	<name>yezi</name>
	<description>yezi</description>
	<author>yezi</author>
 
	<version>1.0.0</version>
	<date>27/10/2015</date>
	<url>http://yezi.net</url>
	<minServerVersion>1.0.0</minServerVersion>
	<licenseType>gpl</licenseType>
 
	<adminconsole>    
	</adminconsole>
</plugin>
最重要的就是class節點下的值,需要正確宣告外掛的入口類地址

四、編譯外掛

之後修改專案下build下的build.properties.template檔案,重新命名為build.properties

修改build.properties檔案內容,增加一行plugin=yezi(此處為外掛的名稱)


修改完了之後就可以進行編譯了,滑鼠右鍵build目錄下的build.xml,選擇Run AS ——> Ant Build...


在選項中,我們這裡只選擇plugin,選擇後點擊run,等待編譯成功。


當提示程式設計成功後,開啟或重啟openfire,可以在外掛頁面看到新新增的外掛


如果你需要實時除錯外掛的話,那麼需要使用debug的方式執行openfire,待執行到斷點後,就會進入debug模式