这是部署配置管理器代理(CMP)应用程序中大型任务中的一部分。
每当命令完成,或每当受管对象发生更改时都可以通知应用程序。通过使用 OBSERVER 设计模式,可以将带有句柄的 CMP 提供给用户提供的对象,如果修改、删除对象,或者每当有从配置管理器返回的对先前提交的操作的响应,该用户提供的对象都会调用特定方法。
processDelete(…) 如果从配置管理器完全除去侦听器注册于其上的对象,则调用该方法。提供给 processDelete(…) 是一个参数,即已删除的受管对象的句柄;一但该方法返回,则受管对象句柄可能不再有效。大约同时,发生 processDelete(…) 事件,processModify(…) 事件将发送至已删除对象父级的侦听器,以声明子组件的父级列表中的更改。
为了注册侦听器,每个受管对象都有 registerListener() 方法,每当在这些对象上发生事件时,该方法可用于告诉 CMP 调用提供的代码。可以为来自多个受管对象的通知注册相同的 AdministeredObjectListener。此外,可以在同一个受管对象上注册多个 AdministeredObjectListeners。
import com.ibm.broker.config.proxy.*; import com.ibm.broker.config.common.CompletionCodeType; import java.util.List; import java.util.ListIterator; import java.util.Properties; public class MonitorTopology implements AdministeredObjectListener { public static void main(String[] args) { ConfigManagerProxy cmp = null; try { ConfigManagerConnectionParameters cmcp = new MQConfigManagerConnectionParameters( "localhost", 1414, ""); cmp = ConfigManagerProxy.getInstance(cmcp); } catch (ConfigManagerProxyException cmpex) { System.out.println("Error connecting: "+cmpex); } if (cmp != null) { System.out.println("Connected to Config Manager!"); TopologyProxy topology = cmp.getTopology(); listenForChanges(topology); cmp.disconnect(); } } private static void listenForChanges(AdministeredObject obj) { try { if (obj != null) { obj.registerListener(new MonitorTopology()); while(true) { // thread could do something else here instead try { Thread.sleep(10000); } catch (InterruptedException ex) { // ignore } } } } catch(ConfigManagerProxyPropertyNotInitializedException ex) { System.err.println("Comms problem! "+ex); } } public void processActionResponse(AdministeredObject obj, CompletionCodeType cc, List bipMessages, Properties refProperties) { // Event ignored in this example } public void processDelete(AdministeredObject deletedObject) { // Event ignored in this example } public void processModify(AdministeredObject affectedObject, List changedAttributes, List newChildren, List removedChildren) { System.out.println(affectedObject+" has changed:"); ListIterator e = changedAttributes.listIterator(); while (e.hasNext()) { String changedAttribute = (String) e.next(); System.out.println("Changed: "+changedAttribute); } ListIterator e2 = newChildren.listIterator(); while (e2.hasNext()) { String newChildStr = (String) e2.next(); AdministeredObject newChild = affectedObject.getSubcomponentFromString(newChildStr); System.out.println("New child: "+newChild); } ListIterator e3 = removedChildren.listIterator(); while (e3.hasNext()) { String remChildStr = (String) e3.next(); AdministeredObject removedChild = affectedObject.getSubcomponentFromString(remChildStr); System.out.println("Removed child: "+removedChild); } } }
listenForChanges() 方法试图注册 MonitorTopology 类的实例以用于拓扑更改的通知。如果成功,则主线程将无限期暂停以阻止应用程序在该方法返回时退出。一旦注册了侦听器,则每当拓扑更改(例如,如果添加代理),则调用 processModify() 方法。这将在屏幕上显示每个通知的详细信息。