KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > olstore > client > OlstoreSwingClient


1 /**
2  * Copyright (c) 2005 Red Hat, Inc. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or any later version.
8  *
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
17  * USA
18  *
19  * Component of: Red Hat Application Server
20  *
21  * Initial Developers: Gregory Lapouchnian
22  * Patrick Smith
23  * --------------------------------------------------------------------------
24  * $Id: OlstoreSwingClient.java,v 1.2 2005/07/08 14:00:45 glapouch Exp $
25  * --------------------------------------------------------------------------
26  */

27 package olstore.client;
28
29 import java.awt.BorderLayout;
30 import java.awt.Color;
31 import java.awt.Dimension;
32 import java.awt.FlowLayout;
33 import java.awt.Font;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.awt.event.KeyEvent;
37 import java.awt.image.BufferedImage;
38 import java.math.BigDecimal;
39 import java.text.DecimalFormat;
40 import java.util.Iterator;
41 import java.util.List;
42
43 import javax.imageio.ImageIO;
44 import javax.swing.Box;
45 import javax.swing.BoxLayout;
46 import javax.swing.ButtonGroup;
47 import javax.swing.ImageIcon;
48 import javax.swing.JButton;
49 import javax.swing.JFrame;
50 import javax.swing.JLabel;
51 import javax.swing.JMenu;
52 import javax.swing.JMenuBar;
53 import javax.swing.JMenuItem;
54 import javax.swing.JOptionPane;
55 import javax.swing.JPanel;
56 import javax.swing.JProgressBar;
57 import javax.swing.JRadioButton;
58 import javax.swing.JScrollPane;
59 import javax.swing.JSplitPane;
60 import javax.swing.JTextField;
61 import javax.xml.namespace.QName;
62 import javax.xml.rpc.ParameterMode;
63 import javax.xml.soap.AttachmentPart;
64 import javax.xml.soap.SOAPMessage;
65
66 import org.apache.axis.client.Call;
67
68 /**
69  * A GUI client that allows to use some of the functionality of the OLStore
70  * example by connecting to its web service endpoint.
71  */

72 public class OlstoreSwingClient implements ActionListener {
73
74     /** The default URL for the web service. */
75     private static String url = "http://localhost:9000/axis-olstorews";
76
77     /** The path for the olstoreEndpoint. */
78     private static String storeEndpointPath = "/olstoreEndpoint/ItemSpecialHelperLocal";
79
80     /** The path for the wsShoppingCartHelper endpoint. */
81     private static String cartEndpointPath = "/wsShoppingCartHelper/ShoppingCartHelperLocal";
82
83     /** The button to retrieve all specials. */
84     private JButton bSpecials;
85
86     /** The button to select the type of specials. */
87     private JButton bSpecialsByType;
88
89     /** The button to empty the shopping cart. */
90     private JButton bEmpty;
91
92     /**
93      * Progress bar that indicates that the client is in the process of
94      * retrieving the information from the web service.
95      */

96     private JProgressBar progressBar;
97
98     /** The main window of the client. */
99     private JFrame frame;
100
101     /** The main panel of the client. */
102     private JPanel panel;
103
104     /** The scroll pane which contains the displayed items. */
105     private JScrollPane scrollPane;
106
107     /** The "Exit" menu item. */
108     private JMenuItem exitMenuItem;
109
110     /**
111      * The Call object that is used to send/receive information via the web
112      * service.
113      */

114     private Call call;
115
116     /** Contains the different types of items available from the olstore. */
117     private String[] types;
118
119     /**
120      * The panel which holds the "Get all specials" and "Specials by type"
121      * buttons.
122      */

123     private JPanel buttonPane;
124
125     /** Provide a way to modify the URL of the web serice. */
126     private JPanel urlPane;
127
128     /** The field which contains the URL to access the web services from. */
129     private JTextField urlField = new JTextField(url);
130
131     /** A label for the url pane. */
132     private JLabel urlLabel = new JLabel("Web Service URL:");
133
134     /** The handler to drag and drop items into the shopping cart. */
135     private ItemPanelTransferHandler handler;
136
137     /** The panel which contains shopping cart related components. */
138     private JPanel cartPanel;
139
140     /** The panel which contains the individual order items in the shopping cart. */
141     private ShoppingCartPanel cartMainPanel;
142
143     /** The shopping cart's total price. */
144     private JLabel totalPrice;
145
146     /** The checkout button. */
147     private JButton bCheckout;
148
149     /** The value of the shopping cart's total price. */
150     private BigDecimal priceValue = new BigDecimal(0.00f);
151
152     /** The primary item colour */
153     public static final Color itemColor1 = new Color(139, 147, 171);
154
155     /** The secondary item colour */
156     public static final Color itemColor2 = new Color(180, 185, 200);
157
158     /** The colour of buttons. */
159     public static final Color buttonColor = new Color(115, 160, 195);
160
161     /** The formatter used to display the prices with 2 decimal places. */
162     private static DecimalFormat formatter = new DecimalFormat("#0.00");
163
164     /** The scroll pane which individual order items are placed in. */
165     private JScrollPane cartScrollPane;
166
167     /** The maximum of the JProgressBar */
168     private static final int PROGRESSMAX = 100;
169
170     /** Used for small pane sizing. */
171     private static final int PANESIZE_SMALL = 300;
172
173     /** Used for pane sizing. */
174     private static final int PANESIZE_MEDIUM = 500;
175
176     /** Used for slightly larger pane sizing. */
177     private static final int PANESIZE = 600;
178
179     /** Used for larger pane sizing. */
180     private static final int PANESIZE_LARGE = 800;
181
182     /** Used for small spacers. */
183     private static final int SPACER = 15;
184
185     /** Used for large spacers. */
186     private static final int LARGE_SPACER = 200;
187
188     /** Used for defining a maximum pane height. */
189     private static final int PANEL_HEIGHT = 30;
190
191     /** Used for defining a maximum banner height. */
192     private static final int BANNER_HEIGHT = 80;
193
194     /** Used for selecting between getting the WSDL from a textfield or the UDDI registry. */
195     private ButtonGroup bGroup = new ButtonGroup();
196
197     /** Used to get the WSDL url from the textfield. */
198     private JRadioButton bURL = new JRadioButton("Use Web Service URL:");
199
200     /** Used to get the WSDL url from the UDDI registry */
201     private JRadioButton bDiscover = new JRadioButton("Discover via UDDI");
202
203     /** Connect to the UDDI registry to retrieve WSDL URLs. */
204     private RegistryConnector registryConnector = new RegistryConnector();
205
206     /**
207      * The constructor which creates the components and places them into the
208      * appropriate layouts.
209      */

210     public OlstoreSwingClient() {
211         handler = new ItemPanelTransferHandler();
212         frame = new JFrame("Olstore Swing Client");
213
214         // the buttons to display all specials
215
bSpecials = new JButton("Get All Specials");
216         bSpecials.addActionListener(this);
217
218         // the button to select specials from a single category
219
bSpecialsByType = new JButton("Specials By Type");
220         bSpecialsByType.addActionListener(this);
221
222         // the button to checkout the shopping cart
223
bCheckout = new JButton("Checkout");
224         bCheckout.addActionListener(this);
225
226         // the button to empty the shopping cart.
227
bEmpty = new JButton("Empty Cart");
228         bEmpty.addActionListener(this);
229         bEmpty.setBackground(buttonColor);
230
231         // initialize the progress bar
232
progressBar = new JProgressBar(0, PROGRESSMAX);
233         progressBar.setValue(0);
234         progressBar.setStringPainted(true);
235         progressBar.setString("");
236
237         // the main area where all the special are displayed
238
JPanel mainPanel = new JPanel();
239         mainPanel.setLayout(new BorderLayout());
240
241         panel = new JPanel();
242         panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
243         panel.setBackground(itemColor1);
244         scrollPane = new JScrollPane(panel);
245         scrollPane.setMinimumSize(new Dimension(PANESIZE_MEDIUM,
246                 PANESIZE_MEDIUM));
247         scrollPane.setPreferredSize(new Dimension(PANESIZE_LARGE, PANESIZE));
248
249         // add a menu to this application
250
createMenu();
251
252         // creates and fills the url panel.
253
urlPane = new JPanel();
254         urlPane.setLayout(new BoxLayout(urlPane, BoxLayout.X_AXIS));
255         urlPane.add(urlLabel);
256         urlPane.add(urlField);
257         urlPane.setMaximumSize(new Dimension(Integer.MAX_VALUE, PANEL_HEIGHT));
258
259         buttonPane = new JPanel();
260         buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
261         bSpecials.setBackground(buttonColor);
262         bSpecialsByType.setBackground(buttonColor);
263
264         buttonPane.add(bSpecials);
265         buttonPane.add(bSpecialsByType);
266
267         JPanel bannerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
268         bannerPanel.setBackground(Color.BLACK);
269         bannerPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE,
270                 BANNER_HEIGHT));
271         JLabel shadowMan = new JLabel(new ImageIcon("images/olstoreLogo.png"));
272         bannerPanel.add(shadowMan);
273
274         addExplanationPanel();
275
276         // create a shopping cart panel
277
cartPanel = new JPanel();
278         cartPanel.setLayout(new BorderLayout());
279         cartPanel.add(new JLabel("Shopping Cart"), BorderLayout.NORTH);
280
281         cartMainPanel = new ShoppingCartPanel(this);
282         cartMainPanel.setTransferHandler(handler);
283         cartMainPanel.setLayout(new BoxLayout(cartMainPanel, BoxLayout.Y_AXIS));
284         cartMainPanel.setBackground(itemColor1);
285
286         totalPrice = new JLabel("Your total: $0.00");
287         JPanel checkoutPanel = new JPanel();
288         checkoutPanel.setLayout(new BoxLayout(checkoutPanel, BoxLayout.X_AXIS));
289         checkoutPanel.add(totalPrice);
290         checkoutPanel.add(Box.createHorizontalStrut(SPACER));
291         checkoutPanel.add(bCheckout);
292         checkoutPanel.add(bEmpty);
293         checkoutPanel.setBackground(itemColor1);
294         bCheckout.setBackground(buttonColor);
295         cartPanel.add(checkoutPanel, BorderLayout.SOUTH);
296
297         cartScrollPane = new JScrollPane(cartMainPanel);
298         cartScrollPane.setMinimumSize(new Dimension(PANESIZE_SMALL,
299                 PANESIZE_MEDIUM));
300         cartScrollPane.setBackground(itemColor1);
301         cartPanel.add(cartScrollPane, BorderLayout.CENTER);
302         cartPanel.setBackground(itemColor1);
303         // the split pane to display products and the shopping cart side by side
304
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
305                 scrollPane, cartPanel);
306         splitPane.setBackground(itemColor1);
307         splitPane.setForeground(itemColor1);
308         JPanel topPanel = new JPanel();
309         topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
310         topPanel.add(bannerPanel);
311         topPanel.add(buttonPane);
312         topPanel.setBackground(Color.BLACK);
313
314         bURL.setSelected(true);
315         bGroup.add(bURL);
316         bGroup.add(bDiscover);
317         bURL.addActionListener(this);
318         bDiscover.addActionListener(this);
319
320         JPanel discoverPanel = new JPanel();
321         discoverPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
322         discoverPanel.add(bDiscover);
323         // creates and fills the url panel.
324
urlPane = new JPanel();
325         urlPane.setLayout(new BoxLayout(urlPane, BoxLayout.X_AXIS));
326         urlPane.add(bURL);
327         urlPane.add(urlField);
328         urlPane.add(progressBar);
329         urlPane.setMaximumSize(new Dimension(Integer.MAX_VALUE, PANEL_HEIGHT));
330
331         JPanel bottomPanel = new JPanel();
332         bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS));
333         bottomPanel.add(discoverPanel);
334         bottomPanel.add(urlPane);
335
336         mainPanel.add(topPanel, BorderLayout.NORTH);
337         mainPanel.add(splitPane, BorderLayout.CENTER);
338         mainPanel.add(bottomPanel, BorderLayout.SOUTH);
339         mainPanel.setBackground(itemColor1);
340         frame.getContentPane().add(mainPanel);
341
342         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
343         frame.pack();
344         frame.setVisible(true);
345
346     }
347
348     /**
349      * Create a panel that gives the user instructions on how to use the client
350      * on startup.
351      */

352     private void addExplanationPanel() {
353
354         panel.setLayout(new BorderLayout());
355
356         JPanel explainPanel = new JPanel();
357         explainPanel.setPreferredSize(new Dimension(200, 100));
358         explainPanel.setLayout(new BoxLayout(explainPanel, BoxLayout.Y_AXIS));
359         explainPanel.setBackground(itemColor2);
360
361         JLabel label0 = new JLabel("Welcome to OLStore");
362         label0.setFont(new Font("sans-serif", Font.BOLD, 17));
363         explainPanel.add(label0);
364         explainPanel.add(Box.createVerticalStrut(SPACER));
365         explainPanel
366                 .add(new JLabel(
367                         "To view all the specials click the 'All Specials' button above."));
368
369         explainPanel.add(Box.createVerticalStrut(SPACER));
370         explainPanel
371                 .add(new JLabel(
372                         "To view the specials by type click the 'Specials By Type' button."));
373         explainPanel.add(Box.createVerticalStrut(SPACER));
374         explainPanel.add(new JLabel(
375                 "To add an item to the shopping cart, simply drag it to the "));
376         explainPanel.add(new JLabel("shopping cart panel on the right."));
377
378         panel.add(explainPanel, BorderLayout.CENTER);
379         panel.add(Box.createVerticalStrut(LARGE_SPACER),
380                 BorderLayout.PAGE_START);
381         panel.add(Box.createHorizontalStrut(LARGE_SPACER),
382                 BorderLayout.LINE_START);
383         panel.add(Box.createVerticalStrut(LARGE_SPACER), BorderLayout.PAGE_END);
384         panel.add(Box.createHorizontalStrut(LARGE_SPACER),
385                 BorderLayout.LINE_END);
386     }
387
388     /**
389      * Creates and displays a new olstore client.
390      * @param args The program's arguments.
391      */

392     public static void main(String[] args) {
393         OlstoreSwingClient client = new OlstoreSwingClient();
394     }
395
396     /**
397      * Creates a menu bar and adds an 'Exit' menu item.
398      */

399     public void createMenu() {
400         JMenuBar menuBar = new JMenuBar();
401
402         JMenu menu = new JMenu("File");
403         menu.setMnemonic(KeyEvent.VK_F);
404         menuBar.add(menu);
405
406         exitMenuItem = new JMenuItem("Exit", KeyEvent.VK_E);
407         exitMenuItem.addActionListener(this);
408
409         menu.add(exitMenuItem);
410
411         frame.setJMenuBar(menuBar);
412     }
413
414     /**
415      * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
416      */

417     public void actionPerformed(ActionEvent event) {
418         try {
419             if (event.getSource().equals(bSpecials)) {
420                 // Create a new thread to execute the call to the web service
421
// while allowing the GUI thread to update the progress bar
422
new Thread() {
423                     public void run() {
424                         try {
425                             displaySpecials("allSpecials", null);
426                         } catch (Exception ex) {
427                             reportError(ex);
428                         }
429                     }
430                 }.start();
431             }
432             if (event.getSource().equals(bSpecialsByType)) {
433                 if (types == null) {
434                     new Thread() {
435                         public void run() {
436                             try {
437                                 getSpecialTypes();
438                                 displayTypes();
439                             } catch (Exception ex) {
440                                 reportError(ex);
441                             }
442                         }
443                     }.start();
444                 } else {
445                     displayTypes();
446                 }
447
448             }
449             if (event.getSource().equals(bCheckout)) {
450                 doCheckout();
451
452             }
453             if (event.getSource().equals(bDiscover)) {
454                 urlField.setEnabled(false);
455             }
456             if (event.getSource().equals(bURL)) {
457                 urlField.setEnabled(true);
458             }
459
460             if (event.getSource().equals(bEmpty)) {
461                 cartMainPanel.removeAllItems();
462             }
463             if (event.getSource().equals(exitMenuItem)) {
464                 int n = JOptionPane.showConfirmDialog(frame,
465                         "Do you want to exit the client?", "Exit",
466                         JOptionPane.YES_NO_OPTION);
467
468                 if (n == 0) {
469                     System.exit(0);
470                 }
471             }
472
473         } catch (Exception e) {
474             reportError(e);
475         }
476
477     }
478
479     /**
480      * Contacts the web service via the base URL entered in the urlField, and
481      * the defined store endpoint, and stores the types in the String[]
482      * <code>types</code>.
483      */

484     private void getSpecialTypes() {
485         // start the progress bar
486
progressBar.setIndeterminate(true);
487         progressBar.setString("Loading types...");
488         bSpecialsByType.setEnabled(false);
489
490         try {
491             call = new Call(getStoreEndpoint());
492             types = (String[]) (call.invoke("getTypes", null));
493         } catch (Exception e) {
494             reportError(e);
495         }
496
497         bSpecialsByType.setEnabled(true);
498         // stop the progress bar
499
progressBar.setIndeterminate(false);
500         progressBar.setString("Done");
501
502     }
503
504     /**
505      * Prompts the user which type (via <code>types</code>) of special they
506      * would like to view, and displays the specials of that type.
507      */

508     private void displayTypes() {
509         if (types != null) {
510             final String s = (String) JOptionPane.showInputDialog(frame,
511                     "Select a type...", "Choose A Type",
512                     JOptionPane.PLAIN_MESSAGE, null, types, null);
513
514             if ((s != null) && (s.length() > 0)) {
515                 new Thread() {
516                     public void run() {
517                         try {
518                             displaySpecials("getSpecials", new Object[] { s });
519                         } catch (Exception ex) {
520                             reportError(ex);
521                         }
522                     }
523                 }.start();
524             }
525         }
526     }
527
528     /**
529      * Given a method name and array of parameters, invokes the web service
530      * through Call.invoke passing it the method name and parameters. The web
531      * service's response consists of a String[][] which contains the
532      * information for each item, as well as an image attachment for each item.
533      * The information and image are used to create new items which are
534      * displayed in the scroll pane.
535      * @param method The name of the method to invoke.
536      * @param params The parameters for the method.
537      * @throws Exception If the call fails.
538      */

539     private void displaySpecials(String method, Object[] params)
540             throws Exception {
541
542         // set the layout to BoxLayout, it might have been different to display
543
// the welcome screen
544
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
545
546         // start the progress bar
547
progressBar.setIndeterminate(true);
548         progressBar.setString("Loading specials...");
549
550         // disable the appropriate button while the webservice is called
551
if (params == null) {
552             bSpecials.setEnabled(false);
553         } else {
554             bSpecialsByType.setEnabled(false);
555         }
556
557         call = new Call(getStoreEndpoint());
558
559         String[][] result = (String[][]) (call.invoke(method, params));
560
561         SOAPMessage msg = call.getResponseMessage();
562         Iterator j = msg.getAttachments();
563         int counter = 0;
564         Color color;
565
566         // empty the current contents of this panel
567
panel.removeAll();
568
569         while (j.hasNext()) {
570             AttachmentPart ap = (AttachmentPart) j.next();
571
572             BufferedImage bi = ImageIO.read(ap.getDataHandler()
573                     .getInputStream());
574
575             if (counter % 2 == 0) {
576                 color = itemColor1;
577             } else {
578                 color = itemColor2;
579             }
580
581             ItemPanel itemPanel = new ItemPanel(result[counter][1],
582                     result[counter][2], result[counter][3], result[counter][0],
583                     result[counter][4], bi, color);
584
585             itemPanel.setBackground(color);
586             panel.add(itemPanel);
587
588             itemPanel.setTransferHandler(handler);
589
590             counter++;
591         }
592         // make sure the new components are drawn
593
scrollPane.validate();
594         scrollPane.repaint();
595
596         // turn the button back on
597
if (params == null) {
598             bSpecials.setEnabled(true);
599         } else {
600             bSpecialsByType.setEnabled(true);
601         }
602         // set the flag for the timer
603
progressBar.setIndeterminate(false);
604         progressBar.setString("Done");
605
606     }
607
608     /**
609      * Get the web services endpoint URL for OLStore. Returns the URL from UDDI
610      * registry if the bDiscover radio button is selected, uses the URL from the
611      * textfield otherwise.
612      *
613      * @return the URL of OLStore web services endpoint
614      * @throws Exception if it is unable to retrieve it from the UDDI registry
615      */

616     private String getStoreEndpoint() throws Exception {
617         // only connect to the UDDI registry if the 'Discover' radio button is on
618
if (bDiscover.isSelected()) {
619             try {
620                 registryConnector.retrieveWSDLLocations();
621             } catch (Exception e) {
622                 throw new Exception("Could not retrieve the WSDL URLs from the registry. " + e.getMessage());
623             }
624
625             List locations = registryConnector.getCartWSDLLocations();
626
627             if (locations.isEmpty()) {
628                 throw new Exception("No WSDL URL was returned.");
629             } else {
630                 // TODO provide the user with a list of available URLs?
631
return (String) registryConnector.getSpecialsWSDLLocations().get(0);
632             }
633         }
634
635         // return the endpoint by combining the value in the urlField with the
636
// constant for the endpoint
637
return urlField.getText() + storeEndpointPath;
638     }
639
640     /**
641      * Get the web services endpoint URL for OLStore shopping cart. Returns the
642      * URL from UDDI registry if the bDiscover radio button is selected, uses
643      * the URL from the textfield otherwise.
644      *
645      * @return the URL of OLStor shopping cart web services endpoint
646      * @throws Exception if it is unable to retrieve it from the UDDI registry
647      */

648     private String getShoppingCartEndpoint() throws Exception {
649         // only connect to the UDDI registry if the 'Discover' radio button is on
650
if (bDiscover.isSelected()) {
651             try {
652                 registryConnector.retrieveWSDLLocations();
653             } catch (Exception e) {
654                 throw new Exception("Could not retrieve the WSDL URLs from the registry. " + e.getMessage());
655             }
656
657             List locations = registryConnector.getCartWSDLLocations();
658
659             if (locations.isEmpty()) {
660                 throw new Exception("No WSDL URL was returned.");
661             } else {
662                 System.out.println("using registry URL: " + (String) registryConnector.getCartWSDLLocations().get(0));
663                 return (String) registryConnector.getCartWSDLLocations().get(0);
664             }
665         }
666
667         // return the endpoint by combining the value in the urlField with the
668
// constant for the endpoint
669
return urlField.getText() + cartEndpointPath;
670     }
671
672     /**
673      * Reports the given exception via a JOptionPane.
674      * @param e The exception to report.
675      */

676     private void reportError(Exception e) {
677         JOptionPane.showMessageDialog(frame,
678                 "Could not retrieve the required information from OLStore.\nError: "
679                         + e.getMessage(), "Client error",
680                 JOptionPane.ERROR_MESSAGE);
681
682         // turn off the progress bar
683
progressBar.setIndeterminate(false);
684         progressBar.setString("Error");
685
686         // turn on the buttons
687
bSpecialsByType.setEnabled(true);
688         bSpecials.setEnabled(true);
689     }
690
691     /**
692      * Updates the price value and price field by adding the given price to the
693      * current total.
694      * @param price The amount to add to the current total.
695      */

696     public void updatePrice(BigDecimal price) {
697         priceValue = priceValue.add(price);
698         setPrice(priceValue);
699     }
700
701     /**
702      * Sets the price label to the given price.
703      * @param priceValue The value to set the price label to.
704      */

705     public void setPrice(BigDecimal priceValue) {
706         this.priceValue = priceValue;
707         totalPrice.setText("Your total: $" + formatter.format(priceValue));
708     }
709
710     /**
711      * Prompts the user for a username and password, and sends the login
712      * information and cart contents (item IDs and the corresponding quantities)
713      * to the server via web services. If the login information is accepted the
714      * cart contents are added to a server side, user specific, shopping cart
715      * and the order is created and completed. If the login information is
716      * incorrect, then the user is prompted to try again.
717      * @throws Exception If the call fails.
718      */

719     public void doCheckout() throws Exception {
720
721         if (cartMainPanel.isEmpty()) {
722             JOptionPane.showMessageDialog(frame,
723                     "The shopping cart does not contain any items.",
724                     "Empty Cart", JOptionPane.INFORMATION_MESSAGE);
725         } else {
726             LoginDialog ld = new LoginDialog(frame);
727             ld.show();
728             if (ld.login()) {
729                 String[] info = ld.getLogin();
730
731                 Boolean result = new Boolean(false);
732
733                 Object[] orderItems = cartMainPanel.getCartContents();
734                 String[][] contents = new String[orderItems.length][2];
735                 for (int i = 0; i < orderItems.length; i++) {
736                     OrderItem item = (OrderItem) orderItems[i];
737                     contents[i][0] = item.getId();
738                     contents[i][1] = String.valueOf(item.getQuantity());
739                 }
740
741                 Object[] params = new Object[] { info[0], info[1],
742                         (String[][]) contents };
743
744                 call = new Call(getShoppingCartEndpoint());
745
746                 // Not the best way to handle sending the parameters, but in
747
// order to
748
// send the String[][] that contains the shopping cart item IDs
749
// and
750
// quantities, we have to use addParameter.
751
// For some strange reason this results in the 2-dimensional
752
// array being sent as a 4-dimensional array through the
753
// web service, though on the server side, it is still received
754
// as a 2-dimensional array.
755
call.addParameter("name", new QName("String"), String.class,
756                         ParameterMode.IN);
757                 call.addParameter("pwd", new QName("String"), String.class,
758                         ParameterMode.IN);
759                 call.addParameter("cartContents", new QName("String[][]"),
760                         String[][].class, ParameterMode.IN);
761                 call.setReturnType(new QName("Boolean"));
762                 result = (Boolean) (call.invoke("createAndCheckoutOrder",
763                         params));
764
765                 if (!result.booleanValue()) {
766                     JOptionPane
767                             .showMessageDialog(
768                                     frame,
769                                     "Cart checkout could not complete. \n"
770                                             + "Please check your username and password and try again.",
771                                     "Shopping cart error",
772                                     JOptionPane.ERROR_MESSAGE);
773                     return;
774                 }
775                 cartMainPanel.removeAllItems();
776                 JOptionPane.showMessageDialog(frame,
777                         "Thank you for your order!", "Order has been sent",
778                         JOptionPane.INFORMATION_MESSAGE);
779
780             }
781             ld.dispose();
782         }
783     }
784 }
785
Popular Tags