1 /*------------------------------------------------------------------------------
  2 Name:      TestFailSafe.java
  3 Project:   xmlBlaster.org
  4 Copyright: xmlBlaster.org, see xmlBlaster-LICENSE file
  5 ------------------------------------------------------------------------------*/
  6 package org.xmlBlaster.test.client;
  7 
  8 import java.util.logging.Logger;
  9 import java.util.logging.Level;
 10 import org.xmlBlaster.util.Global;
 11 import org.xmlBlaster.client.qos.ConnectQos;
 12 import org.xmlBlaster.util.XmlBlasterException;
 13 import org.xmlBlaster.util.def.ErrorCode;
 14 import org.xmlBlaster.util.def.Constants;
 15 import org.xmlBlaster.util.property.PropString;
 16 import org.xmlBlaster.util.EmbeddedXmlBlaster;
 17 import org.xmlBlaster.client.qos.PublishQos;
 18 import org.xmlBlaster.client.I_ConnectionStateListener;
 19 import org.xmlBlaster.client.qos.SubscribeReturnQos;
 20 import org.xmlBlaster.client.qos.EraseReturnQos;
 21 import org.xmlBlaster.client.I_XmlBlasterAccess;
 22 import org.xmlBlaster.util.qos.address.Address;
 23 import org.xmlBlaster.util.MsgUnit;
 24 import org.xmlBlaster.util.dispatch.ConnectionStateEnum;
 25 
 26 import org.xmlBlaster.test.Util;
 27 import org.xmlBlaster.test.MsgInterceptor;
 28 import junit.framework.*;
 29 
 30 
 31 /**
 32  * Tests the fail safe behavior of the I_XmlBlasterAccess client helper class (does not test server side fail safe).
 33  * <br />For a description of what this fail save mode can do for you, please
 34  * read the API documentation of I_XmlBlasterAccess.
 35  * <p>
 36  * This is an interesting example, since it creates a XmlBlaster server instance
 37  * in the same JVM , but in a separate thread, talking over CORBA with it.
 38  * <p>
 39  * Invoke examples:<br />
 40  * <pre>
 41  *   java junit.textui.TestRunner -noloading org.xmlBlaster.test.client.TestFailSafe
 42  *   java junit.swingui.TestRunner -noloading org.xmlBlaster.test.client.TestFailSafe
 43  * </pre>
 44  * @see org.xmlBlaster.client.I_XmlBlasterAccess
 45  */
 46 public class TestFailSafe extends TestCase implements I_ConnectionStateListener
 47 {
 48    private static String ME = "TestFailSafe";
 49    private Global glob;
 50    private static Logger log = Logger.getLogger(TestFailSafe.class.getName());
 51 
 52    private int serverPort = 7604;
 53    private EmbeddedXmlBlaster serverThread;
 54 
 55    private MsgInterceptor updateInterceptor;
 56    private I_XmlBlasterAccess con;
 57    private String senderName;
 58 
 59    private int numPublish = 8;
 60    private int numStop = 3;
 61    private int numStart = 5;
 62    private final String contentMime = "text/plain";
 63 
 64    private final long reconnectDelay = 2000L;
 65 
 66    public TestFailSafe(String testName) {
 67       this(null, testName);
 68    }
 69 
 70    public TestFailSafe(Global glob, String testName) {
 71       super(testName);
 72       this.glob = glob;
 73       this.senderName = testName;
 74    }
 75 
 76    /**
 77     * Sets up the fixture.
 78     * <p />
 79     * Connect to xmlBlaster and login
 80     */
 81    protected void setUp() {
 82       this.glob = (this.glob == null) ? Global.instance() : this.glob;
 83 
 84 
 85       glob.init(Util.getOtherServerPorts(serverPort));
 86 
 87       serverThread = EmbeddedXmlBlaster.startXmlBlaster(glob);
 88       log.info("XmlBlaster is ready for testing on bootstrapPort " + serverPort);
 89       try {
 90          con = glob.getXmlBlasterAccess(); // Find orb
 91 
 92          String passwd = "secret";
 93          ConnectQos connectQos = new ConnectQos(glob, senderName, passwd); // == "<qos>...</qos>";
 94 
 95          // Setup fail save handling ...
 96          Address addressProp = new Address(glob);
 97          addressProp.setDelay(reconnectDelay); // retry connecting every 2 sec
 98          addressProp.setRetries(-1);       // -1 == forever
 99          addressProp.setPingInterval(-1L); // switched off
100          con.registerConnectionListener(this);
101 
102          connectQos.setAddress(addressProp);
103 
104          this.updateInterceptor = new MsgInterceptor(this.glob, log, null); // Collect received msgs
105 
106          con.connect(connectQos, this.updateInterceptor);  // Login to xmlBlaster, register for updates
107       }
108       catch (XmlBlasterException e) {
109           log.warning("setUp() - login failed: " + e.getMessage());
110           fail("setUp() - login fail: " + e.getMessage());
111       }
112       catch (Exception e) {
113           log.severe("setUp() - login failed: " + e.toString());
114           e.printStackTrace();
115           fail("setUp() - login fail: " + e.toString());
116       }
117    }
118 
119    /**
120     * Tears down the fixture.
121     * <p />
122     * cleaning up .... erase() the previous message OID and logout
123     */
124    protected void tearDown() {
125       log.info("Entering tearDown(), test is finished");
126       String xmlKey = "<key oid='' queryType='XPATH'>\n" +
127                       "   //TestFailSafe-AGENT" +
128                       "</key>";
129       String qos = "<qos><forceDestroy>true</forceDestroy></qos>";
130       try {
131          EraseReturnQos[] arr = con.erase(xmlKey, qos);
132 
133          PropString defaultPlugin = new PropString("CACHE,1.0");
134          String propName = defaultPlugin.setFromEnv(this.glob, glob.getStrippedId(), null, "persistence", Constants.RELATING_TOPICSTORE, "defaultPlugin");
135          log.info("Lookup of propName=" + propName + " defaultValue=" + defaultPlugin.getValue());
136          
137          if (defaultPlugin.getValue().startsWith("RAM"))
138             assertEquals("Wrong number of message erased", (numPublish - numStop), arr.length);
139          else
140             assertEquals("Wrong number of message erased", numPublish, arr.length);
141       }
142       catch(XmlBlasterException e) {
143          log.severe("XmlBlasterException: " + e.getMessage());
144       }
145       finally {
146          con.disconnect(null);
147 
148          EmbeddedXmlBlaster.stopXmlBlaster(this.serverThread);
149          this.serverThread = null;
150 
151          // reset to default server bootstrapPort (necessary if other tests follow in the same JVM).
152          Util.resetPorts(glob);
153 
154          this.glob = null;
155          this.con = null;
156          Global.instance().shutdown();
157       }
158    }
159 
160    /**
161     * TEST: Subscribe to messages with XPATH.
162     */
163    public void doSubscribe() {
164       if (log.isLoggable(Level.FINE)) log.fine("Subscribing using EXACT oid syntax ...");
165 
166       String xmlKey = "<key oid='' queryType='XPATH'>\n" +
167                       "   //TestFailSafe-AGENT" +
168                       "</key>";
169       String qos = "<qos></qos>";
170       try {
171          SubscribeReturnQos subscriptionId = con.subscribe(xmlKey, qos);
172          log.info("Success: Subscribe on subscriptionId=" + subscriptionId.getSubscriptionId() + " done");
173          assertTrue("returned null subscriptionId", subscriptionId != null);
174       } catch(XmlBlasterException e) {
175          log.warning("XmlBlasterException: " + e.getMessage());
176          assertTrue("subscribe - XmlBlasterException: " + e.getMessage(), false);
177       }
178    }
179 
180    /**
181     * TEST: Construct a message and publish it.
182     * <p />
183     */
184    public void doPublish(int counter) throws XmlBlasterException {
185       String oid = "Message" + "-" + counter;
186       log.info("Publishing a message " + oid + " ...");
187       String xmlKey = "<key oid='" + oid + "' contentMime='" + contentMime + "'>\n" +
188                       "   <TestFailSafe-AGENT id='192.168.124.10' subId='1' type='generic'>" +
189                       "   </TestFailSafe-AGENT>" +
190                       "</key>";
191       String content = "" + counter;
192       PublishQos qosWrapper = new PublishQos(glob); // == "<qos></qos>"
193       MsgUnit msgUnit = new MsgUnit(xmlKey, content.getBytes(), qosWrapper.toXml());
194 
195       con.publish(msgUnit);
196       log.info("Success: Publishing of " + oid + " done");
197    }
198 
199 
200    /**
201     * TEST: <br />
202     */
203    public void testFailSafe()
204    {
205       //doSubscribe(); -> see reachedAlive()
206       log.info("Going to publish " + numPublish + " messages, xmlBlaster will be down for message 3 and 4");
207       for (int ii=0; ii<numPublish; ii++) {
208          try {
209             if (ii == numStop) { // 3
210                log.info("Stopping xmlBlaster, but continue with publishing ...");
211                EmbeddedXmlBlaster.stopXmlBlaster(this.serverThread);
212                this.serverThread = null;
213             }
214             if (ii == numStart) {
215                log.info("Starting xmlBlaster again, expecting the previous published two messages ...");
216                serverThread = EmbeddedXmlBlaster.startXmlBlaster(serverPort);
217                log.info("xmlBlaster started, waiting on tail back messsages");
218                
219                // Message-4 We need to wait until the client reconnected (reconnect interval)
220                // Message-5
221                assertEquals("", 2, this.updateInterceptor.waitOnUpdate(reconnectDelay*2L, 2));
222                this.updateInterceptor.clear();
223             }
224             doPublish(ii+1);
225             if (ii < numStop || ii >= numStart ) {
226                assertEquals("", 1, this.updateInterceptor.waitOnUpdate(4000L, 1));
227             }
228             this.updateInterceptor.clear();
229          }
230          catch(XmlBlasterException e) {
231             if (e.getErrorCode() == ErrorCode.COMMUNICATION_NOCONNECTION_POLLING)
232                log.warning("Lost connection, my connection layer is polling: " + e.getMessage());
233             else if (e.getErrorCode() == ErrorCode.COMMUNICATION_NOCONNECTION_DEAD)
234                assertTrue("Lost connection, my connection layer is NOT polling", false);
235             else
236                assertTrue("Publishing problems: " + e.getMessage(), false);
237          }
238       }
239    }
240 
241    /**
242     * This is the callback method invoked from I_XmlBlasterAccess
243     * informing the client in an asynchronous mode if the connection was established.
244     * <p />
245     * This method is enforced through interface I_ConnectionStateListener
246     */
247    public void reachedAlive(ConnectionStateEnum oldState, I_XmlBlasterAccess connection) {
248       log.info("I_ConnectionStateListener: We were lucky, reconnected to xmlBlaster");
249       doSubscribe();    // initialize on startup and on reconnect
250    }
251 
252    public void reachedPolling(ConnectionStateEnum oldState, I_XmlBlasterAccess connection) {
253       log.warning("DEBUG ONLY: Changed from connection state " + oldState + " to " + ConnectionStateEnum.POLLING);
254    }
255 
256    public void reachedDead(ConnectionStateEnum oldState, I_XmlBlasterAccess connection) {
257       log.severe("DEBUG ONLY: Changed from connection state " + oldState + " to " + ConnectionStateEnum.DEAD);
258    }
259 
260    /**
261     * Invoke: java org.xmlBlaster.test.client.TestFailSafe
262     * <p />
263     * @deprecated Use the TestRunner from the testsuite to run it:<p />
264     * <pre>   java -Djava.compiler= junit.textui.TestRunner org.xmlBlaster.test.client.TestFailSafe</pre>
265     */
266    public static void main(String args[])
267    {
268       Global glob = new Global();
269       if (glob.init(args) != 0) {
270          System.out.println(ME + ": Init failed");
271          System.exit(1);
272       }
273       TestFailSafe testSub = new TestFailSafe(glob, "TestFailSafe");
274       testSub.setUp();
275       testSub.testFailSafe();
276       testSub.tearDown();
277    }
278 }


syntax highlighted by Code2HTML, v. 0.9.1