KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > samples > loanbroker > LoanConsumer


1 /*
2  * $Id: LoanConsumer.java 4219 2006-12-09 10:15:14Z lajos $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.samples.loanbroker;
12
13 import java.io.IOException JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.List JavaDoc;
17
18 import org.mule.MuleManager;
19 import org.mule.config.builders.MuleXmlConfigurationBuilder;
20 import org.mule.extras.client.MuleClient;
21 import org.mule.umo.UMOException;
22 import org.mule.umo.UMOMessage;
23 import org.mule.util.DateUtils;
24 import org.mule.util.StringMessageUtils;
25 import org.mule.util.StringUtils;
26 import org.mule.util.SystemUtils;
27
28 /**
29  * <code>LoanConsumer</code> is a loan broker client app that uses command line
30  * prompts to obtain loan requests
31  */

32
33 public class LoanConsumer
34 {
35     private static boolean synchronous = false;
36
37     private List JavaDoc customers = new ArrayList JavaDoc();
38     private MuleClient client = null;
39
40     public LoanConsumer() throws UMOException
41     {
42         init();
43     }
44
45     public LoanConsumer(String JavaDoc config) throws UMOException
46     {
47         MuleXmlConfigurationBuilder builder = new MuleXmlConfigurationBuilder();
48         builder.configure(config);
49         init();
50     }
51
52     private void init() throws UMOException
53     {
54         client = new MuleClient();
55
56         customers.add(new Customer("Jenson Button", 123));
57         customers.add(new Customer("Michael Schumacker", 456));
58         customers.add(new Customer("Juan Pablo Montoya", 789));
59         customers.add(new Customer("David Colthard", 101));
60         customers.add(new Customer("Rubens Barrichello", 112));
61         customers.add(new Customer("Mark Webber", 131));
62         customers.add(new Customer("Takuma Sato", 415));
63         customers.add(new Customer("Kimi Raikkonen", 161));
64         customers.add(new Customer("Ralf Schumacher", 718));
65         customers.add(new Customer("Jarno Trulli", 192));
66     }
67
68     public void close()
69     {
70         MuleManager.getInstance().dispose();
71     }
72
73     public LoanRequest createRequest()
74     {
75         int index = new Double JavaDoc(Math.random() * 10).intValue();
76         Customer c = (Customer)customers.get(index);
77
78         return new LoanRequest(c, getRandomAmount(), getRandomDuration());
79     }
80
81     private static double getRandomAmount()
82     {
83         return Math.round(Math.random() * 18000);
84     }
85
86     private static int getRandomDuration()
87     {
88         return new Double JavaDoc(Math.random() * 60).intValue();
89     }
90
91     public void request(LoanRequest request, boolean sync) throws Exception JavaDoc
92     {
93         if (!sync)
94         {
95             client.dispatch("vm://LoanBrokerRequests", request, null);
96             System.out.println("Sent Async request");
97             // let the request catch up
98
Thread.sleep(1500);
99         }
100         else
101         {
102             UMOMessage result = client.send("vm://LoanBrokerRequests", request, null);
103             if (result == null)
104             {
105                 System.out.println("A result was not received, an error must have occurred. Check the logs.");
106             }
107             else
108             {
109                 System.out.println("Loan Consumer received a Quote: " + result.getPayload());
110             }
111         }
112     }
113
114     public void requestDispatch(int number, String JavaDoc endpoint) throws Exception JavaDoc
115     {
116         for (int i = 0; i < number; i++)
117         {
118             client.dispatch(endpoint, createRequest(), null);
119         }
120     }
121
122     public List JavaDoc requestSend(int number, String JavaDoc endpoint) throws Exception JavaDoc
123     {
124         List JavaDoc results = new ArrayList JavaDoc(number);
125         UMOMessage result;
126         for (int i = 0; i < number; i++)
127         {
128             result = client.send(endpoint, createRequest(), null);
129             if (result != null)
130             {
131                 results.add(result.getPayload());
132             }
133         }
134         return results;
135     }
136
137     public static void main(String JavaDoc[] args)
138     {
139         LoanConsumer loanConsumer = null;
140         try
141         {
142             String JavaDoc config = SystemUtils.getCommandLineOption("-config", args);
143             if (StringUtils.isNotBlank(config))
144             {
145                 loanConsumer = new LoanConsumer(config);
146
147                 int i = 100;
148                 String JavaDoc requests = SystemUtils.getCommandLineOption("-req", args);
149                 if (requests != null)
150                 {
151                     i = Integer.parseInt(requests);
152                 }
153
154                 String JavaDoc sync = SystemUtils.getCommandLineOption("-sync", args);
155                 if (sync != null)
156                 {
157                     synchronous = Boolean.valueOf(sync).booleanValue();
158                 }
159
160                 if (synchronous)
161                 {
162                     long start = System.currentTimeMillis();
163                     List JavaDoc results = loanConsumer.requestSend(i, "vm://LoanBrokerRequests");
164                     System.out.println("Number or quotes received: " + results.size());
165                     List JavaDoc output = new ArrayList JavaDoc(results.size());
166                     int x = 1;
167                     for (Iterator JavaDoc iterator = results.iterator(); iterator.hasNext(); x++)
168                     {
169                         LoanQuote quote = (LoanQuote)iterator.next();
170                         output.add(x + ". " + quote.toString());
171                     }
172                     System.out.println(StringMessageUtils.getBoilerPlate(output, '*', 80));
173                     long cur = System.currentTimeMillis();
174                     System.out.println(DateUtils.getFormattedDuration(cur - start));
175                     System.out.println("Avg request: " + ((cur - start) / x));
176                 }
177                 else
178                 {
179                     loanConsumer.requestDispatch(i, "vm://LoanBrokerRequests");
180                 }
181             }
182             else
183             {
184                 loanConsumer = new LoanConsumer(getInteractiveConfig());
185                 loanConsumer.run(synchronous);
186             }
187
188         }
189         catch (Exception JavaDoc e)
190         {
191             System.err.println(e.getMessage());
192             e.printStackTrace(System.err);
193             System.exit(1);
194         }
195     }
196
197     protected static String JavaDoc getInteractiveConfig() throws IOException JavaDoc
198     {
199         System.out.println(StringMessageUtils.getBoilerPlate("Welcome to the Mule Loan Broker example"));
200
201         int response = 0;
202         String JavaDoc provider = "axis";
203
204         while (response != 'a' && response != 'g' && response != 'x')
205         {
206             System.out.println("\nWhich SOAP stack would you like to use: [a]xis, [g]lue or [x]fire?");
207             response = readCharacter();
208             switch (response)
209             {
210                 case 'a' :
211                 {
212                     provider = "axis";
213                     break;
214                 }
215
216                 case 'g' :
217                 {
218                     provider = "glue";
219                     break;
220                 }
221
222                 case 'x' :
223                 {
224                     provider = "xfire";
225                     break;
226                 }
227             }
228         }
229
230         response = 0;
231         while (response != 'a' && response != 's')
232         {
233             System.out.println("\nWould you like to run the [s]ynchronous or [a]synchronous version?");
234             response = readCharacter();
235             switch (response)
236             {
237                 case 'a' :
238                 {
239                     System.out.println("Loading Asynchronous Loan Broker");
240                     synchronous = false;
241                     break;
242                 }
243
244                 case 's' :
245                 {
246                     System.out.println("Loading Synchronous Loan Broker");
247                     synchronous = true;
248                     break;
249                 }
250             }
251         }
252
253         String JavaDoc config = "loan-broker-" + provider + "-" + (synchronous ? "sync" : "async") + "-config.xml";
254         return config;
255     }
256
257     protected void run(boolean synchronous) throws Exception JavaDoc
258     {
259
260         int response = 0;
261         while (response != 'q')
262         {
263             System.out.println("\n[1] make a loan request");
264             System.out.println("[2] send 100 random requests");
265             System.out.println("[3] send x requests");
266             System.out.println("[q] quit");
267             System.out.println("\nPlease make your selection: ");
268
269             response = readCharacter();
270
271             switch (response)
272             {
273                 case '1' :
274                 {
275                     LoanRequest request = getRequestFromUser();
276                     request(request, synchronous);
277                     break;
278                 }
279
280                 case '2' :
281                 {
282                     sendRandomRequests(100, synchronous);
283                     break;
284                 }
285
286                 case '3' :
287                 {
288                     System.out.println("Enter number of requests: ");
289                     int number = readInt();
290                     if (number < 1)
291                     {
292                         System.out.println("Number of requests must be at least 1");
293                     }
294                     else
295                     {
296                         sendRandomRequests(number, synchronous);
297                     }
298                     break;
299                 }
300
301                 case 'q' :
302                 {
303                     System.out.println("Exiting now.");
304                     close();
305                     System.exit(0);
306                 }
307
308                 default :
309                 {
310                     System.out.println("That response is not recognised, try again.");
311                 }
312             }
313         }
314     }
315
316     protected void sendRandomRequests(int number, boolean synchronous) throws Exception JavaDoc
317     {
318         if (synchronous)
319         {
320             List JavaDoc list = this.requestSend(number, "vm://LoanBrokerRequests");
321             int i = 1;
322             for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext(); i++)
323             {
324                 System.out.println("Request " + i + ": " + iterator.next().toString());
325             }
326         }
327         else
328         {
329             this.requestDispatch(number, "vm://LoanBrokerRequests");
330         }
331     }
332
333     protected static int readCharacter() throws IOException JavaDoc
334     {
335         byte[] buf = new byte[16];
336         System.in.read(buf);
337         return buf[0];
338     }
339
340     protected static String JavaDoc readString() throws IOException JavaDoc
341     {
342         byte[] buf = new byte[80];
343         System.in.read(buf);
344         return new String JavaDoc(buf).trim();
345     }
346
347     protected static int readInt() throws IOException JavaDoc
348     {
349         try
350         {
351             return Integer.parseInt(readString());
352         }
353         catch (NumberFormatException JavaDoc nfex)
354         {
355             return 0;
356         }
357     }
358
359     protected static LoanRequest getRequestFromUser() throws IOException JavaDoc
360     {
361         System.out.println("Enter your name:");
362         String JavaDoc name = readString();
363
364         System.out.println("Enter loan Amount:");
365         String JavaDoc amount = readString();
366
367         System.out.println("Enter loan Duration in months:");
368         String JavaDoc duration = readString();
369
370         int d = 0;
371         try
372         {
373             d = Integer.parseInt(duration);
374         }
375         catch (NumberFormatException JavaDoc e)
376         {
377             System.out.println("Failed to parse duration: " + duration + ". Using random default");
378             d = getRandomDuration();
379         }
380
381         double a = 0;
382         try
383         {
384             a = Double.valueOf(amount).doubleValue();
385         }
386         catch (NumberFormatException JavaDoc e)
387         {
388             System.out.println("Failed to parse amount: " + amount + ". Using random default");
389             a = getRandomAmount();
390         }
391
392         Customer c = new Customer(name, getRandomSsn());
393         LoanRequest request = new LoanRequest(c, a, d);
394         return request;
395     }
396
397     private static int getRandomSsn()
398     {
399         return new Double JavaDoc(Math.random() * 6000).intValue();
400     }
401
402 }
403
Popular Tags