posts - 13,comments - 19,trackbacks - 0

          WebLogic Server包含了Timer Service功能,你可以指定某一時刻或某一時間間隔產生Timer事件,同時你可以使用委托代理的機制,為這個事件注冊事件監聽器,以實現Timer Service功能。

            WebLogic Server 7.0以后的版本,WebLogic Timer Service擴展自標準的JMX Timer Service,使其可以運行于WebLogic Server的執行線程中,并且享有WebLogic Server的安全上下文環境,也就是說,可以在代碼中得到安全信息,如用戶名等。下面結合一個實例演示其功能。

          File:TimerServiceListener.java

          package org.yekki.weblogic.timer;

          import java.util.Date;

          import java.util.Random;

          import javax.jms.JMSException;

          import javax.jms.Queue;

          import javax.jms.QueueConnection;

          import javax.jms.QueueConnectionFactory;

          import javax.jms.QueueSender;

          import javax.jms.QueueSession;

          import javax.jms.Session;

          import javax.jms.TextMessage;

          import javax.management.InstanceNotFoundException;

          import javax.management.Notification;

          import javax.management.NotificationListener;

          import javax.naming.Context;

          import javax.naming.InitialContext;

          import javax.servlet.ServletContext;

          import javax.servlet.ServletContextEvent;

          import javax.servlet.ServletContextListener;

          import org.apache.ecs.xml.XML;

          import weblogic.management.timer.Timer;

          public class TimerServiceListener

                 implements ServletContextListener, NotificationListener {

                 private long period;

                 private boolean debug;

                 private Timer timer;

                 private Integer notificationId;

                 private QueueConnectionFactory factory;

                 private QueueConnection connection;

                 private QueueSession session;

                 private QueueSender sender;

                 private Queue queue;

                 private Context ctx;

                 public void contextInitialized(ServletContextEvent event) {

                        initParams(event);

                        initJMS();

                        debug(">>> contextInitialized called.");

                        timer = new Timer();

                        timer.addNotificationListener(this, null, "Message Broker ");

                        Date timerTriggerAt = new Date((new Date()).getTime() + 5000L);

                        notificationId =

                               timer.addNotification(

                                      "Timer Type",

                                      "Timer Message",

                                      this,

                                      timerTriggerAt,

                                      period);

                        timer.start();

                        debug(">>> timer started.");

                        printBrief();

                 }

                 public void initParams(ServletContextEvent event) {

                        ServletContext ctx = event.getServletContext();

                        try {

                               debug = Boolean.valueOf((String)ctx.getInitParameter("debug")).booleanValue();

                        }

                        catch (Exception e) {

                               debug = false;

                               e.printStackTrace();

                        }

                        try {

                               /*

                                second:1000L

                                minute:60000L

                                hour:3600000L

                                day:86400000L

                                week:604800000L

                                */

                               period =

                                      Long

                                             .valueOf((String)ctx.getInitParameter("period"))

                                             .longValue();

                        }

                        catch (Exception e) {

                               period = Timer.ONE_MINUTE;

                               e.printStackTrace();

                        }

                        debug(">>> initialized application parameters.");

                 }

                 private void initJMS() {

                        try {

                               ctx = new InitialContext();

                               factory =

                                      (QueueConnectionFactory)ctx.lookup(

                                             "javax.jms.QueueConnectionFactory");

                               queue = (Queue)ctx.lookup("queue");

                               connection = factory.createQueueConnection();

                               session =

                                      connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

                               sender = session.createSender(queue);

                               connection.start();

                               debug(">>> initialized jms.");

                        }

                        catch (Exception e) {

                               e.printStackTrace();

                        }

                 }

                 public void sendMessage(String message) {

                        try {

                               TextMessage msg = session.createTextMessage();

                               msg.setText(message);

                               sender.send(msg);

                               debug(">>> ################################");

                               debug("Send a message on " + new Date());

                               debug(message);

                               debug(">>> ################################");

                        }

                        catch (JMSException e) {

                               e.printStackTrace();

                        }

                 }

                 public void contextDestroyed(ServletContextEvent event) {

                        debug(">>> contextDestroyed called.");

                        try {

                               timer.stop();

                               timer.removeNotification(notificationId);

                               debug(">>> timer stopped.");

                        }

                        catch (InstanceNotFoundException e) {

                               e.printStackTrace();

                        }

                        try {

                               if (session != null)

                                      session.close();

                               if (connection != null)

                                      connection.close();

                               debug(">>> closed jms connection and session.");

                        }

                        catch (JMSException e) {

                               e.printStackTrace();

                        }

                 }

                 private void printBrief() {

                        String d = "";

                        d = debug ? "ON" : "OFF";

                        print(">>> ################################");

                        print(">>> Author: Niu Xiuyuan");

                        print(">>> EMail: niuxiuyuan@bea.com.cn");

                        print(">>> Company: BEA Systems");

                        print("");

                        print(">>> Debug: " + d);

                        print(">>> Period: " + getPeriodInfo(period));

                        print(">>> ################################");

                 }

                 private void print(String str) {

                        System.out.println(str);

                 }

                 private String getPeriodInfo(long p) {

                        if (p == Timer.ONE_DAY)

                               return "One Day";

                        if (p == Timer.ONE_HOUR)

                               return "One Hour";

                        if (p == Timer.ONE_MINUTE)

                               return "One Minute";

                        if (p == Timer.ONE_SECOND)

                               return "One Second";

                        if (p == Timer.ONE_WEEK)

                               return "One Week";

                        return "Unsupported time period!! period=" + p;

                 }

                 public void handleNotification(Notification notif, Object handback) {

                        Random rnd = new Random();

                        sendMessage(genXML(rnd.nextInt(10)));

                 }

                 public String genXML(int id) {

                        String username = "guru";

                        String password = "niu986";

                        XML usernameXML = null;

                        XML idXML = null;

                        XML passwordXML = null;

                        XML userXML = null;

                        XML profileXML = new XML("profiles");

                        for (int i = 1; i <= id; i++) {

                               usernameXML = (new XML("user")).addElement(username);

                               idXML = (new XML("id")).addElement(Integer.toString(id));

                               passwordXML = (new XML("password")).addElement(password);

                               userXML =

                                      (new XML("user"))

                                             .addXMLAttribute("age", "27")

                                             .addElement(idXML)

                                             .addElement(usernameXML)

                                             .addElement(passwordXML);

                               profileXML.addElement(userXML);

                        }

                        return profileXML.toString();

                 }

                 private void debug(String msg) {

                        if (debug) {

                               System.out.println(msg);

                        }

                 }

                 public static void main(String[] args) {

                 }

          }

            說明:為了方便演示,此類中包含了事件產生器代碼與事件監聽器代碼。使用ServletContextListener接口來控制Timer的啟動與停止。

          File:web.xml

          <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

          <web-app>

            <context-param>

              <param-name>debug</param-name>

              <param-value>false</param-value>

            </context-param>

            <context-param>

              <param-name>period</param-name>

              <param-value>60000</param-value>

            </context-param>

            <listener>

              <listener-class>org.yekki.weblogic.timer.TimerServiceListener</listener-class>

            </listener>

            <login-config>

              <auth-method></auth-method>

            </login-config>

          </web-app>

            說明:我們將webappLisener注冊,并且指定事件產生的時間間隔

              將此WebApp部署到WebLogic Server上,然后通過中端(例如:DOS窗口)查看實驗結果。

            附:本例中使用了ApacheECS項目類庫,您可以訪問如下URL:

            http://jakarta.apache.org/ecs/index.html

          posted on 2008-06-23 10:16 南山隱士 閱讀(749) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 黄陵县| 清涧县| 介休市| 眉山市| 南川市| 洛川县| 克什克腾旗| 玉林市| 于田县| 女性| 民丰县| 乐东| 淳化县| 南丹县| 昭苏县| 佛坪县| 聂拉木县| 甘肃省| 高清| 平顶山市| 宜川县| 五莲县| 金川县| 兴城市| 方城县| 哈密市| 长沙市| 皋兰县| 绥棱县| 电白县| 加查县| 闽清县| 来凤县| 玛曲县| 滨海县| 舞阳县| 盐津县| 公主岭市| 二手房| 金华市| 黔江区|