1 /*------------------------------------------------------------------------------
  2 Name:      TestSubDispatch.java
  3 Project:   xmlBlaster.org
  4 Copyright: xmlBlaster.org, see xmlBlaster-LICENSE file
  5 Comment:   Demo code for a client using xmlBlaster
  6 Version:   $Id: TestSubDispatch.java 14833 2006-03-06 21:38:58Z laghi $
  7 ------------------------------------------------------------------------------*/
  8 package org.xmlBlaster.test.qos;
  9 
 10 import java.util.logging.Logger;
 11 import java.util.logging.Level;
 12 import org.xmlBlaster.util.Global;
 13 import org.xmlBlaster.util.XmlBlasterException;
 14 import org.xmlBlaster.client.I_XmlBlasterAccess;
 15 import org.xmlBlaster.client.I_Callback;
 16 import org.xmlBlaster.client.qos.ConnectQos;
 17 import org.xmlBlaster.client.key.UpdateKey;
 18 import org.xmlBlaster.client.qos.UpdateQos;
 19 import org.xmlBlaster.client.qos.SubscribeReturnQos;
 20 import org.xmlBlaster.client.qos.EraseReturnQos;
 21 import org.xmlBlaster.util.MsgUnit;
 22 
 23 import junit.framework.*;
 24 
 25 
 26 /**
 27  * This client tests the method subscribe() with a later publish() with XPath query.
 28  * <br />
 29  * The subscribe() should be recognized for this later arriving publish()
 30  * and will be received in the specialized, anonymous, update implementation.
 31  * <p>
 32  * This client may be invoked multiple time on the same xmlBlaster server,
 33  * as it cleans up everything after his tests are done.
 34  * <p>
 35  * Invoke examples:<br />
 36  * <pre>
 37  *    java junit.textui.TestRunner -noloading org.xmlBlaster.test.qos.TestSubDispatch
 38  *    java junit.swingui.TestRunner -noloading org.xmlBlaster.test.qos.TestSubDispatch
 39  * </pre>
 40  */
 41 public class TestSubDispatch extends TestCase implements I_Callback
 42 {
 43    private static String ME = "TestSubDispatch";
 44    private final Global glob;
 45    private static Logger log = Logger.getLogger(TestSubDispatch.class.getName());
 46 
 47    private boolean messageArrived = false;
 48 
 49    private String publishOid = "dummyTestSubDispatch";
 50    private I_XmlBlasterAccess senderConnection;
 51    private String senderName;
 52    private String senderContent;
 53    private String receiverName;         // sender/receiver is here the same client
 54 
 55    private int numReceived = 0;         // error checking
 56    private final String contentMime = "text/xml";
 57    private final String contentMimeExtended = "1.0";
 58            
 59    private SubscribeReturnQos subscribeRetQos = null; // declare here to allow inner class access
 60 
 61    private String assertInUpdate = null;
 62 
 63    /**
 64     * Constructs the TestSubDispatch object.
 65     * <p />
 66     * @param testName  The name used in the test suite
 67     * @param loginName The name to login to the xmlBlaster
 68     */
 69    public TestSubDispatch(Global glob, String testName, String loginName)
 70    {
 71       super(testName);
 72       this.glob = glob;
 73 
 74       this.senderName = loginName;
 75       this.receiverName = loginName;
 76    }
 77 
 78 
 79    /**
 80     * Sets up the fixture.
 81     * <p />
 82     * Connect to xmlBlaster and login
 83     */
 84    protected void setUp()
 85    {
 86       try {
 87          senderConnection = glob.getXmlBlasterAccess(); // Find orb
 88          String passwd = "secret";
 89          ConnectQos connectQos = new ConnectQos(glob, senderName, passwd);
 90          senderConnection.connect(connectQos, this); // Login to xmlBlaster
 91       }
 92       catch (Exception e) {
 93           log.severe("Login failed: " + e.toString());
 94           e.printStackTrace();
 95           assertTrue("Login failed: " + e.toString(), false);
 96       }
 97    }
 98 
 99 
100    /**
101     * Tears down the fixture.
102     * <p />
103     * cleaning up .... erase() the previous message OID and logout
104     */
105    protected void tearDown()
106    {
107       String xmlKey = "<?xml version='1.0' encoding='ISO-8859-1' ?>\n" +
108                       "<key oid='" + publishOid + "' queryType='EXACT'>\n" +
109                       "</key>";
110       String qos = "<qos></qos>";
111       try {
112          EraseReturnQos[] arr = senderConnection.erase(xmlKey, qos);
113          assertEquals("Erase", 1, arr.length);
114       } catch(XmlBlasterException e) { fail("Erase XmlBlasterException: " + e.getMessage()); }
115 
116       senderConnection.disconnect(null);
117    }
118 
119    /**
120     * TEST: Subscribe to messages with XPATH.
121     * <p />
122     * The returned subscribeOid is checked
123     */
124    public void testSubscribeXPath()
125    {
126       if (log.isLoggable(Level.FINE)) log.fine("Subscribing using XPath syntax ...");
127 
128       String xmlKey = "<?xml version='1.0' encoding='ISO-8859-1' ?>\n" +
129                       "<key oid='' queryType='XPATH'>\n" +
130                       "   //TestSubDispatch-AGENT" +
131                       "</key>";
132       String qos = "<qos></qos>";
133       numReceived = 0;
134       try {
135          subscribeRetQos = senderConnection.subscribe(xmlKey, qos, new I_Callback() {
136                public String update(String cbSessionId, UpdateKey updateKey, byte[] content, UpdateQos updateQos) {
137                   log.info("Receiving message with specialized update(" + updateKey.getOid() + ") ... " + updateQos.toXml());
138 
139                   if (updateQos.isErased()) {
140                      return "";
141                   }
142                   numReceived += 1;
143 
144                   assertEquals("Wrong sender", senderName, updateQos.getSender().getLoginName());
145                   assertEquals("engine.qos.update.subscriptionId: Wrong subscriptionId", subscribeRetQos.getSubscriptionId(), updateQos.getSubscriptionId());
146                   assertEquals("Wrong oid of message returned", publishOid, updateKey.getOid());
147                   assertEquals("Message content is corrupted", new String(senderContent), new String(content));
148                   assertEquals("Message contentMime is corrupted", contentMime, updateKey.getContentMime());
149                   assertEquals("Message contentMimeExtended is corrupted", contentMimeExtended, updateKey.getContentMimeExtended());
150 
151                   messageArrived = true;
152                   return "";
153                }
154             });
155          assertTrue("returned null subscribeRetQos", subscribeRetQos != null);
156          assertTrue("returned null subscribeId", subscribeRetQos.getSubscriptionId() != null);
157          assertTrue("returned subscribeId is empty", 0 != subscribeRetQos.getSubscriptionId().length());
158          log.info("Success: Subscribe subscription-id=" + subscribeRetQos.getSubscriptionId() + " done");
159       } catch(XmlBlasterException e) {
160          log.warning("XmlBlasterException: " + e.getMessage());
161          assertTrue("subscribe - XmlBlasterException: " + e.getMessage(), false);
162       }
163    }
164 
165 
166    /**
167     * TEST: Construct a message and publish it.
168     * <p />
169     * The returned publishOid is checked
170     */
171    public void testPublish()
172    {
173       if (log.isLoggable(Level.FINE)) log.fine("Publishing a message ...");
174 
175       numReceived = 0;
176       String xmlKey = "<?xml version='1.0' encoding='ISO-8859-1' ?>\n" +
177                       "<key oid='" + publishOid + "' contentMime='" + contentMime + "' contentMimeExtended='" + contentMimeExtended + "'>\n" +
178                       "   <TestSubDispatch-AGENT id='192.168.124.10' subId='1' type='generic'>" +
179                       "      <TestSubDispatch-DRIVER id='FileProof' pollingFreq='10'>" +
180                       "      </TestSubDispatch-DRIVER>"+
181                       "   </TestSubDispatch-AGENT>" +
182                       "</key>";
183       senderContent = "Yeahh, i'm the new content";
184       try {
185          MsgUnit msgUnit = new MsgUnit(xmlKey, senderContent.getBytes(), "<qos></qos>");
186          String tmp = senderConnection.publish(msgUnit).getKeyOid();
187          assertEquals("Wrong publishOid", publishOid, tmp);
188          log.info("Success: Publishing done, returned oid=" + publishOid);
189       } catch(XmlBlasterException e) {
190          log.warning("XmlBlasterException: " + e.getMessage());
191          assertTrue("publish - XmlBlasterException: " + e.getMessage(), false);
192       }
193    }
194 
195 
196    /**
197     * TEST: Construct a message and publish it,<br />
198     * the previous XPath subscription should match and send an update.
199     */
200    public void testPublishAfterSubscribeXPath()
201    {
202       testSubscribeXPath();
203       try { Thread.sleep(1000L); } catch( InterruptedException i) {}                                            // Wait some time for callback to arrive ...
204       assertEquals("numReceived after subscribe", 0, numReceived);  // there should be no Callback
205       assertTrue(assertInUpdate, assertInUpdate == null);
206 
207       testPublish();
208       waitOnUpdate(5000L);
209       assertEquals("numReceived after publishing", 1, numReceived); // message arrived?
210       assertTrue(assertInUpdate, assertInUpdate == null);
211    }
212 
213    /**
214     * This is the callback method invoked from xmlBlaster
215     * delivering us a new asynchronous message. 
216     * @see org.xmlBlaster.client.I_Callback#update(String, UpdateKey, byte[], UpdateQos)
217     */
218    public String update(String cbSessionId, UpdateKey updateKey, byte[] content, UpdateQos updateQos)
219    {
220       if (updateQos.isErased()) {
221          return "";
222       }
223       assertInUpdate = "Receiving update of message oid=" + updateKey.getOid() + " state=" + updateQos.getState() + " in default update handler ...";
224       log.severe("Receiving update of message oid=" + updateKey.getOid() + " state=" + updateQos.getState() + " in default update handler ...");
225       return "";
226    }
227 
228 
229    /**
230     * Little helper, waits until the variable 'messageArrive' is set
231     * to true, or returns when the given timeout occurs.
232     * @param timeout in milliseconds
233     */
234    private void waitOnUpdate(final long timeout)
235    {
236       long pollingInterval = 50L;  // check every 0.05 seconds
237       if (timeout < 50)  pollingInterval = timeout / 10L;
238       long sum = 0L;
239       while (!messageArrived) {
240          try {
241             Thread.sleep(pollingInterval);
242          }
243          catch( InterruptedException i)
244          {}
245          sum += pollingInterval;
246          if (sum > timeout) {
247             log.warning("Timeout of " + timeout + " occurred");
248             break;
249          }
250       }
251       messageArrived = false;
252    }
253 
254 
255    /**
256     * Method is used by TestRunner to load these tests
257     */
258    public static Test suite()
259    {
260        TestSuite suite= new TestSuite();
261        String loginName = TestSubDispatch.ME;
262        suite.addTest(new TestSubDispatch(new Global(), "testPublishAfterSubscribeXPath", loginName));
263        return suite;
264    }
265 
266 
267    /**
268     * Invoke: java org.xmlBlaster.test.qos.TestSubDispatch
269     * @deprecated Use the TestRunner from the testsuite to run it:<p />
270     * <pre>   java -Djava.compiler= junit.textui.TestRunner org.xmlBlaster.test.qos.TestSubDispatch</pre>
271     */
272    public static void main(String args[])
273    {
274       TestSubDispatch testSub = new TestSubDispatch(new Global(args), "TestSubDispatch", TestSubDispatch.ME);
275       testSub.setUp();
276       testSub.testPublishAfterSubscribeXPath();
277       testSub.tearDown();
278    }
279 }


syntax highlighted by Code2HTML, v. 0.9.1