KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > petals > binding > xquarebc > listeners > XQuareBCTestTemplate


1 /**
2  * PETALS - PETALS Services Platform.
3  * Copyright (c) 2005 EBM Websourcing, http://www.ebmwebsourcing.com/
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * -------------------------------------------------------------------------
19  * $Id : $
20  * -------------------------------------------------------------------------
21  */

22 package org.objectweb.petals.binding.xquarebc.listeners;
23
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.sql.Connection JavaDoc;
29 import java.sql.DriverManager JavaDoc;
30 import java.sql.ResultSet JavaDoc;
31 import java.sql.SQLException JavaDoc;
32 import java.sql.Statement JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.logging.Logger JavaDoc;
36
37 import javax.jbi.component.ComponentContext;
38 import javax.jbi.messaging.ExchangeStatus;
39 import javax.jbi.messaging.MessageExchange;
40 import javax.jbi.messaging.MessagingException;
41 import javax.jbi.messaging.NormalizedMessage;
42 import javax.xml.namespace.QName JavaDoc;
43 import javax.xml.transform.Source JavaDoc;
44
45 import junit.framework.TestCase;
46
47 import org.easymock.IArgumentMatcher;
48 import org.easymock.classextension.EasyMock;
49 import org.objectweb.petals.binding.xquarebc.XQuareBCException;
50 import org.objectweb.petals.binding.xquarebc.XQuareSUHandler;
51 import org.objectweb.petals.binding.xquarebc.mock.MockDeliveryChannel;
52 import org.objectweb.petals.binding.xquarebc.mock.MockServiceEndpoint;
53 import org.objectweb.petals.component.common.MEPConstants;
54 import org.objectweb.petals.component.common.util.SourceHelper;
55
56 import static org.easymock.EasyMock.expect;
57 import static org.easymock.classextension.EasyMock.createMock;
58 import static org.easymock.classextension.EasyMock.replay;
59 import static org.easymock.classextension.EasyMock.verify;
60
61 /**
62  *
63  * This is a helper class for testing the XQuareBC capabilities.
64  * It sets up the test sample environment and provides helper
65  * methods.
66  *
67  * @version $Rev: 250 $Date: {date}
68  * @since Petals 1.0
69  * @author Marc Dutoo - Open Wide
70  *
71  */

72 public class XQuareBCTestTemplate extends TestCase {
73
74     protected String JavaDoc baseDir;
75
76     protected String JavaDoc workDir;
77
78     protected String JavaDoc auctionDir;
79
80     protected Logger JavaDoc logger;
81     
82     protected Properties JavaDoc testXquareAuctionProperties;
83     
84     protected Connection JavaDoc dbConn = null;
85
86     @Override JavaDoc
87     public void setUp() throws Exception JavaDoc {
88         baseDir = this.getClass().getResource(".").toString();
89         baseDir = baseDir.substring(0, baseDir.indexOf("target"));
90         baseDir = baseDir.substring(baseDir.indexOf(":") + 1);
91         workDir = baseDir + "src" + File.separator + "test-data"
92             + File.separator;
93         auctionDir = workDir + "auction" + File.separator;
94         
95         this.logger = EasyMock.createMock(Logger JavaDoc.class);
96
97
98         this.testXquareAuctionProperties = new Properties JavaDoc();
99         //this.testXquareAuctionProperties.load(new FileInputStream(auctionDir + "xquarebc_auction.properties"));
100
String JavaDoc databaseUrl = "jdbc:mysql://localhost/petals_samples_xquare_auction";
101         String JavaDoc databaseUser = "petals_samples";
102         String JavaDoc databasePassword = "petals_samples";
103         String JavaDoc databaseMappingFilepath = auctionDir + "auction.map";
104         testXquareAuctionProperties.put(XQuareSUHandler.DATABASE_URL, databaseUrl);
105         testXquareAuctionProperties.put(XQuareSUHandler.DATABASE_USER, databaseUser);
106         testXquareAuctionProperties.put(XQuareSUHandler.DATABASE_PASSWORD, databasePassword);
107         testXquareAuctionProperties.put(XQuareSUHandler.DATABASE_MAPPING, databaseMappingFilepath);
108         testXquareAuctionProperties.setProperty(XQuareSUHandler.XML_CONNECTION_BASE_URI, "file://" + auctionDir);
109         testXquareAuctionProperties.setProperty(XQuareSUHandler.WRAP_QUERY_RESULTS_IN_ROOT_TAG, "true");
110         //databaseUrl = testXquareAuctionProperties.getProperty(XQuareSUHandler.DATABASE_URL, "jdbc:mysql://localhost/petals_samples_xquare_auction");
111
//databaseUser = testXquareAuctionProperties.getProperty(XQuareSUHandler.DATABASE_USER, "petals_samples_xquare");
112
//databasePassword = testXquareAuctionProperties.getProperty(XQuareSUHandler.DATABASE_PASSWORD, "petals_samples_xquare");
113
//String databaseMappingFilepath = testXquareAuctionProperties.getProperty(XQuareSUHandler.DATABASE_MAPPING, "auction.map");
114
try {
115             Class.forName("com.mysql.jdbc.Driver");
116             dbConn = DriverManager.getConnection(databaseUrl, databaseUser, databasePassword);
117             dbConn.setAutoCommit(false);
118         } catch (ClassNotFoundException JavaDoc e) {
119             throw new XQuareBCException("Unable to load database driver", e);
120         } catch (SQLException JavaDoc e) {
121             throw new XQuareBCException("Unable to connect to database", e);
122         }
123
124         String JavaDoc delimiterPrefix = XQuareSUHandler.LISTENER_PROP_PREFIX + DelimiterNewDataStrategy.DELIMITER_PROP_PREFIX;
125         testXquareAuctionProperties.put(XQuareSUHandler.LISTENER_SERVICE_PROP, "{http://petals.objectweb.org/}HelloworldService");
126         testXquareAuctionProperties.put(XQuareSUHandler.LISTENER_OPERATION_PROP, "sayHello");
127         testXquareAuctionProperties.put(delimiterPrefix + DelimiterNewDataStrategy.OLD_DATA_DELIMITER_SELECT_PROP, "select max(userid) from users_xqbc");
128         testXquareAuctionProperties.put(delimiterPrefix + DelimiterNewDataStrategy.NEW_DATA_DELIMITER_SELECT_PROP, "select max(userid) from users");
129         testXquareAuctionProperties.put(delimiterPrefix + DelimiterNewDataStrategy.INIT_DATA_DELIMITER_PROP, "U00");
130         testXquareAuctionProperties.put(delimiterPrefix + DelimiterNewDataStrategy.NEW_DATA_DELIMITER_UPDATES_PROP, "delete from users_xqbc;\ninsert into users_xqbc (userid) values (\"##NEW_DATA_DELIMITER##\")");
131         testXquareAuctionProperties.put(delimiterPrefix + DelimiterNewDataStrategy.NEW_DATA_XQUERY_PROP,
132             "for $i in collection(\"users\")/users \n" +
133             "where $i/userid > \"##OLD_DATA_DELIMITER##\" and $i/userid <= \"##NEW_DATA_DELIMITER##\" return \n" +
134             "<user>{ $i/userid }</user>");
135         
136         super.setUp();
137     }
138
139
140     @Override JavaDoc
141     protected void tearDown() throws Exception JavaDoc {
142         super.tearDown();
143         
144         try {
145             if (dbConn != null) {
146                 dbConn.close();
147             }
148         } catch (SQLException JavaDoc e) {
149             throw new XQuareBCException("Unable to close connection to database", e);
150         }
151         
152     }
153     
154
155     protected int getSelectRowNb(String JavaDoc selectStatementString) throws Exception JavaDoc {
156         Statement JavaDoc stmt = dbConn.createStatement();
157         stmt.execute(selectStatementString);
158         ResultSet JavaDoc rs = stmt.getResultSet();
159         int rowNb = 0;
160         while (rs.next()) {
161             rowNb++;
162         }
163         stmt.close();
164         return rowNb;
165     }
166
167     
168     protected void cleanDatabase() throws Exception JavaDoc {
169         Statement JavaDoc stmt = dbConn.createStatement();
170         stmt.executeUpdate("delete from bids;");
171         stmt.close();
172         stmt = dbConn.createStatement();
173         stmt.executeUpdate("delete from items;");
174         stmt.close();
175         stmt = dbConn.createStatement();
176         stmt.executeUpdate("delete from users;");
177         stmt.close();
178         stmt = dbConn.createStatement();
179         stmt.executeUpdate("delete from users_xqbc;");
180         stmt.close();
181         //dbConn.commit(); // not needed when autocommit
182
assert(getSelectRowNb("select * from bids") == 0);
183         assert(getSelectRowNb("select * from items") == 0);
184         assert(getSelectRowNb("select * from users") == 0);
185         assert(getSelectRowNb("select * from users_xqbc") == 0);
186     }
187
188     
189
190
191     public void testOperation(String JavaDoc testOperation, String JavaDoc testInput,
192            String JavaDoc testOutput, Properties JavaDoc testServiceProperties) {
193         MockDeliveryChannel mockDeliveryChannel = new MockDeliveryChannel();
194         ComponentContext mockComponentContext = EasyMock.createMock(ComponentContext.class); // NB. null is ok
195

196         HashMap JavaDoc<String JavaDoc, Properties JavaDoc> mapEndpointProps = new HashMap JavaDoc<String JavaDoc, Properties JavaDoc>();
197         mapEndpointProps.put("myServiceName", testServiceProperties);
198         XQuareBCJBIProcessor xquareProcessor = new XQuareBCJBIProcessor(
199             mockComponentContext, mockDeliveryChannel,
200             logger, mapEndpointProps);
201
202         MockServiceEndpoint mockServiceEndpoint = createMock(MockServiceEndpoint.class);
203         // expect(mockServiceEndpoint.getEndpointName()).andReturn("myEndpointName");
204
expect(mockServiceEndpoint.getServiceName()).andReturn(
205             new QName JavaDoc("myServiceName"));
206
207         QName JavaDoc myOperation = new QName JavaDoc(testOperation);
208
209         NormalizedMessage mockInNormalizedMessage = createMock(NormalizedMessage.class);
210         Source JavaDoc contentSource = SourceHelper.createSource(testInput);
211         expect(mockInNormalizedMessage.getContent()).andReturn(contentSource);
212         NormalizedMessage mockOutNormalizedMessage = createMock(NormalizedMessage.class);
213
214         MessageExchange mockMessageExchange = createMock(MessageExchange.class);
215         expect(mockMessageExchange.getStatus())
216             .andReturn(ExchangeStatus.ACTIVE);
217         expect(mockMessageExchange.getRole()).andReturn(
218             MessageExchange.Role.PROVIDER);
219         expect(mockMessageExchange.getPattern()).andReturn(
220             MEPConstants.IN_OUT_PATTERN).atLeastOnce();
221         expect(mockMessageExchange.getFault()).andReturn(null);
222         try {
223             expect(mockMessageExchange.createMessage()).andReturn(
224                 mockOutNormalizedMessage);
225         } catch (Exception JavaDoc e) {
226             e.printStackTrace();
227         }
228         expect(mockMessageExchange.getEndpoint())
229             .andReturn(mockServiceEndpoint);
230         expect(mockMessageExchange.getOperation()).andReturn(myOperation);
231         expect(mockMessageExchange.getMessage("in")).andReturn(
232             mockInNormalizedMessage);
233
234         try {
235             mockOutNormalizedMessage.setContent(eqSource(SourceHelper
236                 .createSource(testOutput)));
237             // expectLastCall().andAnswer(new IAnswer<void>() {
238
mockMessageExchange.setMessage(mockOutNormalizedMessage, "out");
239         } catch (MessagingException e) {
240             e.printStackTrace();
241         }
242
243         replay(mockServiceEndpoint);
244         replay(mockInNormalizedMessage);
245         replay(mockOutNormalizedMessage);
246         replay(mockMessageExchange);
247
248         try {
249             // Function to test
250
xquareProcessor.process(mockMessageExchange);
251         } catch (XQuareBCException e) {
252             e.printStackTrace();
253         } catch (Exception JavaDoc e) {
254             e.printStackTrace();
255         }
256
257         verify(mockServiceEndpoint);
258         verify(mockInNormalizedMessage);
259         verify(mockOutNormalizedMessage);
260         verify(mockMessageExchange);
261     }
262
263
264     public void testEmitNewData(String JavaDoc testOperation, String JavaDoc testInput,
265            String JavaDoc testOutput, Properties JavaDoc testServiceProperties) {
266         MockDeliveryChannel mockDeliveryChannel = new MockDeliveryChannel();
267         ComponentContext mockComponentContext = EasyMock.createMock(ComponentContext.class); // NB. null is ok
268

269         HashMap JavaDoc<String JavaDoc, Properties JavaDoc> mapEndpointProps = new HashMap JavaDoc<String JavaDoc, Properties JavaDoc>();
270         mapEndpointProps.put("myServiceName", testServiceProperties);
271         XQuareBCJBIProcessor xquareProcessor = new XQuareBCJBIProcessor(
272             mockComponentContext, mockDeliveryChannel,
273             logger, mapEndpointProps);
274
275
276         XQuareBCListener xquareListener = new XQuareBCListener(
277             mockComponentContext, mockDeliveryChannel,
278             logger, mapEndpointProps, xquareProcessor);
279         
280         xquareListener.process(testServiceProperties);
281         boolean isInOut = true;
282         String JavaDoc tagetServiceName = "targetServiceName";
283         String JavaDoc targetOperation = "targetOperation";
284         try {
285             xquareListener.handleNewData(isInOut, QName.valueOf(tagetServiceName),
286                 targetOperation, testServiceProperties);
287         } catch (Exception JavaDoc e1) {
288             // TODO Bloc catch auto-généré
289
e1.printStackTrace();
290         }
291         
292         MockServiceEndpoint mockServiceEndpoint = createMock(MockServiceEndpoint.class);
293         // expect(mockServiceEndpoint.getEndpointName()).andReturn("myEndpointName");
294
expect(mockServiceEndpoint.getServiceName()).andReturn(
295             new QName JavaDoc("myServiceName"));
296
297         QName JavaDoc myOperation = new QName JavaDoc(testOperation);
298
299         NormalizedMessage mockInNormalizedMessage = createMock(NormalizedMessage.class);
300         Source JavaDoc contentSource = SourceHelper.createSource(testInput);
301         expect(mockInNormalizedMessage.getContent()).andReturn(contentSource);
302         NormalizedMessage mockOutNormalizedMessage = createMock(NormalizedMessage.class);
303
304         MessageExchange mockMessageExchange = createMock(MessageExchange.class);
305         expect(mockMessageExchange.getStatus())
306             .andReturn(ExchangeStatus.ACTIVE);
307         expect(mockMessageExchange.getRole()).andReturn(
308             MessageExchange.Role.PROVIDER);
309         expect(mockMessageExchange.getPattern()).andReturn(
310             MEPConstants.IN_OUT_PATTERN).atLeastOnce();
311         expect(mockMessageExchange.getFault()).andReturn(null);
312         try {
313             expect(mockMessageExchange.createMessage()).andReturn(
314                 mockOutNormalizedMessage);
315         } catch (Exception JavaDoc e) {
316             e.printStackTrace();
317         }
318         expect(mockMessageExchange.getEndpoint())
319             .andReturn(mockServiceEndpoint);
320         expect(mockMessageExchange.getOperation()).andReturn(myOperation);
321         expect(mockMessageExchange.getMessage("in")).andReturn(
322             mockInNormalizedMessage);
323
324         try {
325             mockOutNormalizedMessage.setContent(eqSource(SourceHelper
326                 .createSource(testOutput)));
327             // expectLastCall().andAnswer(new IAnswer<void>() {
328
mockMessageExchange.setMessage(mockOutNormalizedMessage, "out");
329         } catch (MessagingException e) {
330             e.printStackTrace();
331         }
332
333         replay(mockServiceEndpoint);
334         replay(mockInNormalizedMessage);
335         replay(mockOutNormalizedMessage);
336         replay(mockMessageExchange);
337
338         try {
339             // Function to test
340
xquareProcessor.process(mockMessageExchange);
341         } catch (XQuareBCException e) {
342             e.printStackTrace();
343         } catch (Exception JavaDoc e) {
344             e.printStackTrace();
345         }
346
347         verify(mockServiceEndpoint);
348         verify(mockInNormalizedMessage);
349         verify(mockOutNormalizedMessage);
350         verify(mockMessageExchange);
351     }
352
353
354
355     /**
356      * Custom argument matcher for Source
357      *
358      * @author mdutoo
359      *
360      */

361     public static class SourceArgumentMatcher implements IArgumentMatcher {
362         private Source JavaDoc expectedSource;
363
364         public SourceArgumentMatcher(Source JavaDoc expectedSource) {
365             this.expectedSource = expectedSource;
366         }
367
368         public boolean matches(Object JavaDoc found) {
369             if (!(found instanceof Source JavaDoc)) {
370                 return false;
371             }
372             Source JavaDoc foundSource = (Source JavaDoc) found;
373             try {
374                 String JavaDoc foundSourceContent = SourceHelper
375                     .createString(foundSource);
376                 String JavaDoc expectedSourceContent = SourceHelper
377                     .createString(expectedSource);
378                 return (foundSourceContent == null) ?
379                     (expectedSourceContent == null) :
380                         foundSourceContent.equals(expectedSourceContent);
381             } catch (Exception JavaDoc e) {
382                 return false;
383             }
384         }
385
386         public void appendTo(StringBuffer JavaDoc sbuf) {
387             String JavaDoc expectedSourceContent;
388             try {
389                 expectedSourceContent = SourceHelper
390                     .createString(expectedSource);
391             } catch (Exception JavaDoc e) {
392                 expectedSourceContent = "<error creating representation>";
393             }
394             sbuf.append("eqSource(with content\"");
395             sbuf.append(expectedSourceContent);
396             sbuf.append("\")");
397         }
398
399     }
400
401     /**
402      * Helps using the source argument matcher
403      *
404      * @param in
405      * @return
406      */

407     public static Source JavaDoc eqSource(Source JavaDoc in) {
408         EasyMock.reportMatcher(new SourceArgumentMatcher(in));
409         return in;
410     }
411     
412     /**
413      * Helper method in place of IOUtils.getStringFromReader()
414      * that has the advantage of not adding any EOL at the end
415      * of the file.
416      * @param in
417      * @return
418      * @throws IOException
419      */

420     public static final String JavaDoc getStringFromInputStream(InputStream JavaDoc in)
421             throws IOException JavaDoc {
422         //in.reset();
423
byte[] byteBuf = new byte[1024];
424         int byteReadNb;
425         ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
426         while ((byteReadNb = in.read(byteBuf)) != -1) {
427             bos.write(byteBuf, 0, byteReadNb);
428         }
429         String JavaDoc res = bos.toString();
430         return res;
431     }
432 }
433
Popular Tags