Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Consuming the Blackjack Web Service

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - Web Services

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Consuming the Blackjack Web Service

The blackjack application in Fig. 28.14 keeps track of the player’s and dealer’s cards, and the web service tracks the cards that have been dealt.

Consuming the Blackjack Web Service

 

The blackjack application in Fig. 28.14 keeps track of the player’s and dealer’s cards, and the web service tracks the cards that have been dealt. The constructor (lines 34–83) sets up the GUI (line 36), changes the window’s background color (line 40) and creates the Blackjack web service’s proxy object (lines 46–47). In the GUI, each player has 11 JLa-bels—the maximum number of cards that can be dealt without automatically exceeding 21 (i.e., four aces, four twos and three threes). These JLabels are placed in an ArrayList of JLabels, (lines 59–82), so we can index the ArrayList during the game to determine the JLabel that will display a particular card image.

With JAX-WS 2.0, the client application must indicate whether it wants to allow the web service to maintain session information. Lines 50–51 in the constructor perform this

task. We first cast the proxy object to interface type BindingProvider. A BindingProvider enables the client to manipulate the request information that will be sent to the server. This information is stored in an object that implements interface RequestContext.

 

The BindingProvider and RequestContext are part of the framework that is created by the IDE when you add a web service client to the application. Next, lines 50–51 invoke the BindingProvider’s getRequestContext method to obtain the RequestContext object. Then the RequestContext’s put method is called to set the property BindingPro-vider.SESSION_MAINTAIN_PROPERTY to true, which enables session tracking from the client side so that the web service knows which client is invoking the service’s web methods.

 

9     // Fig. 28.14: BlackjackGameJFrame.java

 

10  // Blackjack game that uses the Blackjack Web Service

 

11  package com.deitel.iw3htp4.ch28.blackjackclient;

4

1     import java.awt.Color;

 

2     import java.util.ArrayList;

 

3     import javax.swing.ImageIcon;

 

4     import javax.swing.JLabel;

 

5     import javax.swing.JOptionPane;

 

6       import javax.xml.ws.BindingProvider;

 

7       import com.deitel.iw3htp4.ch28.blackjackclient.Blackjack;

 

8       import com.deitel.iw3htp4.ch28.blackjackclient.BlackjackService;

9              

6       public class BlackjackGameJFrame extends javax.swing.JFrame

7       {

 

8             private String playerCards;

 

9             private String dealerCards;

 

10          private ArrayList< JLabel > cardboxes; // list of card image JLabels

 

11          private int currentPlayerCard; // player's current card number

 

12          private int currentDealerCard; // blackjackProxy's current card number

 

13          private BlackjackService blackjackService; // used to obtain proxy

 

14          private Blackjack blackjackProxy; // used to access the web service

15           

12          // enumeration of game states

 

13          private enum GameStatus

14          {

 

15                 PUSH, // game ends in a tie

 

16                 LOSE, // player loses

 

17                 WIN, // player wins

 

18                 BLACKJACK // player has blackjack

 

19          } // end enum GameStatus

32

17          // no-argument constructor

 

18          public BlackjackGameJFrame()

19          {

 

20                 initComponents();

37

 

25                 // due to a bug in Netbeans, we must change the JFrame's background

 

26                 // color here rather than in the designer

 

27                 getContentPane().setBackground( new Color( 0, 180, 0 ) );

41

1                    // initialize the blackjack proxy

2                    try

3                    {

 

4                          // create the objects for accessing the Blackjack web service

 

5                          blackjackService = new BlackjackService();

 

6                          blackjackProxy = blackjackService.getBlackjackPort();

48

7                          // enable session tracking

 

8                          ( ( BindingProvider ) blackjackProxy ).getRequestContext().put(

10                              BindingProvider.SESSION_MAINTAIN_PROPERTY, true );

 

11                 } // end try

 

12                 catch ( Exception e )

13                 {

 

14                       e.printStackTrace();

 

15                 } // end catch

57

49                 // add JLabels to cardBoxes ArrayList for programmatic manipulation

 

50                 cardboxes = new ArrayList< JLabel >();

60

1                    cardboxes.add( 0, dealerCard1JLabel );

 

2                    cardboxes.add( dealerCard2JLabel );

 

3                    cardboxes.add( dealerCard3JLabel );

 

4                    cardboxes.add( dealerCard4JLabel );

 

5                    cardboxes.add( dealerCard5JLabel );

 

6                    cardboxes.add( dealerCard6JLabel );

 

7                    cardboxes.add( dealerCard7JLabel );

 

8                    cardboxes.add( dealerCard8JLabel );

 

9                    cardboxes.add( dealerCard9JLabel );

 

10                 cardboxes.add( dealerCard10JLabel );

 

11                 cardboxes.add( dealerCard11JLabel );

 

12                 cardboxes.add( playerCard1JLabel );

 

13                 cardboxes.add( playerCard2JLabel );

 

14                 cardboxes.add( playerCard3JLabel );

 

15                 cardboxes.add( playerCard4JLabel );

 

16                 cardboxes.add( playerCard5JLabel );

 

17                 cardboxes.add( playerCard6JLabel );

 

18                 cardboxes.add( playerCard7JLabel );

 

19                 cardboxes.add( playerCard8JLabel );

 

20                 cardboxes.add( playerCard9JLabel );

 

21                 cardboxes.add( playerCard10JLabel );

 

22                 cardboxes.add( playerCard11JLabel );

 

23          } // end no-argument constructor

84

9             // play the dealer’s hand

 

10          private void dealerPlay()

11          {

12                 try

{

90        // while the value of the dealer's hand is below 17

 

91        // the dealer must continue to take cards

 

92        String[] cards = dealerCards.split( "\t" );

93

94        // display dealer's cards

 

95        for ( int i = 0; i < cards.length; i++ )

 

 

96        displayCard( i, cards[ i ]);

97       

98        while ( blackjackProxy.getHandValue( dealerCards ) < 17 )

99        {

100      String newCard = blackjackProxy.dealCard();

 

101      dealerCards += "\t" + newCard; // deal new card

 

102      displayCard( currentDealerCard, newCard );

 

103      ++currentDealerCard;

 

104      JOptionPane.showMessageDialog( this, "Dealer takes a card",

105

"Dealer's turn", JOptionPane.PLAIN_MESSAGE );

           

106      } // end while

107     

108      int dealersTotal = blackjackProxy.getHandValue( dealerCards );

 

109      int playersTotal = blackjackProxy.getHandValue( playerCards );

110     

111      // if dealer busted, player wins

112      if ( dealersTotal > 21 )

113      {

 

114      gameOver( GameStatus.WIN );

115      return;

116      } // end if

117

118      // if dealer and player are below 21

 

119      // higher score wins, equal scores is a push

 

120      if ( dealersTotal > playersTotal )

 

121      gameOver( GameStatus.LOSE );

 

122      else if ( dealersTotal < playersTotal )

 

123      gameOver( GameStatus.WIN );

124      else

 

125      gameOver( GameStatus.PUSH );

126      } // end try

 

127      catch ( Exception e )

128      {

 

129      e.printStackTrace();

 

130      } // end catch

 

131      } // end method dealerPlay

132

133      // displays the card represented by cardValue in specified JLabel

 

134      public void displayCard( int card, String cardValue )

135      {

136      try

137      {

 

138      // retrieve correct JLabel from cardBoxes

 

139      JLabel displayLabel = cardboxes.get( card );

140

141      // if string representing card is empty, display back of card

142      if ( cardValue.equals( "" ) )

143      {

 

                       

144      displayLabel.setIcon( new ImageIcon(          getClass().getResource(

145      "/com/deitel/iw3htp4/ch28/blackjackclient/" +

146      "blackjack_images/cardback.png" )    ) ) ;

147      return;

148      } // end if

149     

150      // retrieve the face value of the card

 

151      String face = cardValue.substring( 0, cardValue.indexOf( " " ) );

152     

153      // retrieve the suit of the card

 

154      String suit =

 

155      cardValue.substring( cardValue. indexOf( " " ) + 1 );

156     

157      char suitLetter; // suit letter used to form image file

 

158

159      switch ( Integer.parseInt( suit ) )

160      {

 

161      case 0: // hearts

 

 

162      suitLetter = 'h';

163      break;

164      case 1: // diamonds

165      suitLetter = 'd';

166      break;

167      case 2: // clubs

168      suitLetter = 'c';

169      break;

170      default: // spades

171      suitLetter = 's';

172      break;

173      } // end switch

174     

175      // set image for displayLabel

 

176      displayLabel.setIcon( new ImageIcon( getClass().getResource(

 

177      "/com/deitel/iw3htp4/ch28/blackjackclient/blackjack_images/" +

 

178      face + suitLetter + ".png" ) ) );

179      } // end try

 

180      catch ( Exception e )

181      {

 

182      e.printStackTrace();

 

183      } // end catch

 

184      } // end method displayCard

185

186      // displays all player cards and shows appropriate message

 

187      public void gameOver( GameStatus winner )

188      {

 

189      String[] cards = dealerCards.split( "\t" );

190

191      // display blackjackProxy's cards

 

192      for ( int i = 0; i < cards.length; i++ )

 

193      displayCard( i, cards[ i ]);

195              // display appropriate status image

 

196              if ( winner == GameStatus.WIN )

 

197                     statusJLabel.setText( "You win!" );

 

198              else if ( winner == GameStatus.LOSE )

 

199                     statusJLabel.setText( "You lose." );

 

200              else if ( winner == GameStatus.PUSH )

 

201                     statusJLabel.setText( "It's a push." );

 

202              else // blackjack

 

203                     statusJLabel.setText( "Blackjack!" );

204        

205              // display final scores

 

206              int dealersTotal = blackjackProxy.getHandValue( dealerCards );

 

207              int playersTotal = blackjackProxy.getHandValue( playerCards );

 

208              dealerTotalJLabel.setText( "Dealer: " +  dealersTotal );

 

209              playerTotalJLabel.setText( "Player: " + playersTotal );

210

211              // reset for new game

 

212              standJButton.setEnabled( false );

 

213              hitJButton.setEnabled( false );

 

214              dealJButton.setEnabled( true );

 

215       } // end method gameOver

216

 

217       // The initComponents method is autogenerated by Netbeans and is called

 

218       // from the constructor to initialize the GUI. This method is not shown

 

219       // here to save space. Open BlackjackGameJFrame.java in this

 

220       // example's folder to view the complete generated code (lines 221-531)

221        

532       // handles standJButton click

 

533      private void standJButtonActionPerformed(

 

534              java.awt.event.ActionEvent evt )

535       {

 

536              standJButton.setEnabled( false );

 

537              hitJButton.setEnabled( false );

 

538              dealJButton.setEnabled( true );

 

539              dealerPlay();

 

540       } // end method standJButtonActionPerformed

541        

542       // handles hitJButton click

 

543      private void hitJButtonActionPerformed(

 

544              java.awt.event.ActionEvent evt )

545       {

 

546              // get player another card

 

547              String card = blackjackProxy.dealCard(); // deal new card

 

548              playerCards += "\t" + card; // add card to hand

549

550              // update GUI to display new card

 

551              displayCard( currentPlayerCard, card );

 

552              ++currentPlayerCard;

553

554              // determine new value of player's hand

 

555              int total = blackjackProxy.getHandValue( playerCards );

556        

557              if ( total > 21 ) // player busts

 

558                     gameOver( GameStatus.LOSE );

 

559              if ( total == 21 ) // player cannot take any more cards

560              {

 

561                     hitJButton.setEnabled( false );

 

562                     dealerPlay();

563              } // end if

 

564       } // end method hitJButtonActionPerformed

565

566       // handles dealJButton click

 

567      private void dealJButtonActionPerformed(

 

568              java.awt.event.ActionEvent evt )

569       {

 

570              String card; // stores a card temporarily until it's added to a hand

571        

572              // clear card images

 

573              for ( int i = 0; i < cardboxes.size(); i++ )

 

574                     cardboxes.get( i ).setIcon( null );

575

576              statusJLabel.setText( "" );

 

577              dealerTotalJLabel.setText( "" );

 

578              playerTotalJLabel.setText( "" );

579        

580              // create a new, shuffled deck on remote machine

 

581              blackjackProxy.shuffle();

582

583              // deal two cards to player

 

584              playerCards = blackjackProxy.dealCard(); // add first card to hand

 

585              displayCard( 11, playerCards ); // display first card

 

586              card = blackjackProxy.dealCard(); // deal second card

 

587              displayCard( 12, card ); // display second card

 

588              playerCards += "\t" + card; // add second card to hand

589

590              // deal two cards to blackjackProxy, but only show first

 

591              dealerCards = blackjackProxy.dealCard(); // add first card to hand

 

592              displayCard( 0, dealerCards ); // display first card

 

593              card = blackjackProxy.dealCard(); // deal second card

 

594              displayCard( 1, "" ); // display back of card

 

595              dealerCards += "\t" + card; // add second card to hand

596

597              standJButton.setEnabled( true );

 

598              hitJButton.setEnabled( true );

 

599              dealJButton.setEnabled( false );

600        

601              // determine the value of the two hands

 

602              int dealersTotal = blackjackProxy.getHandValue( dealerCards );

 

603              int playersTotal = blackjackProxy.getHandValue( playerCards );

604        

605              // if hands both equal 21, it is a push

 

606              if ( playersTotal == dealersTotal && playersTotal == 21 )

 

607                     gameOver( GameStatus.PUSH );

 

608              else if ( dealersTotal == 21 ) // blackjackProxy has blackjack

 

gameOver( GameStatus.LOSE );

610               else if ( playersTotal == 21 ) // blackjack

 

611                     gameOver( GameStatus.BLACKJACK );

612

613               // next card for blackjackProxy has index 2

 

614               currentDealerCard = 2;

615

616               // next card for player has index 13

 

617               currentPlayerCard = 13;

 

618        } // end method dealJButtonActionPerformed

619        

620        // begins application execution

 

621        public static void main( String args[] )

622        {

 

623               java.awt.EventQueue.invokeLater(

 

624                     new Runnable()

625                     {

 

626                           public void run()

627                           {

628                         new BlackjackGameJFrame().setVisible(true);

 

629                           }

630                     }

 

631               ); // end call to java.awt.EventQueue.invokeLater

 

632        } // end method main

633

634        // Variables declaration - do not modify

 

635        private javax.swing.JButton dealJButton;

 

636        private javax.swing.JLabel dealerCard10JLabel;

 

637        private javax.swing.JLabel dealerCard11JLabel;

 

638        private javax.swing.JLabel dealerCard1JLabel;

 

639        private javax.swing.JLabel dealerCard2JLabel;

 

640        private javax.swing.JLabel dealerCard3JLabel;

 

641        private javax.swing.JLabel dealerCard4JLabel;

 

642        private javax.swing.JLabel dealerCard5JLabel;

 

643        private javax.swing.JLabel dealerCard6JLabel;

 

644        private javax.swing.JLabel dealerCard7JLabel;

 

645        private javax.swing.JLabel dealerCard8JLabel;

 

646        private javax.swing.JLabel dealerCard9JLabel;

 

647        private javax.swing.JLabel dealerJLabel;

 

648        private javax.swing.JLabel dealerTotalJLabel;

 

649        private javax.swing.JButton hitJButton;

 

650        private javax.swing.JLabel playerCard10JLabel;

 

651        private javax.swing.JLabel playerCard11JLabel;

 

652        private javax.swing.JLabel playerCard1JLabel;

 

653        private javax.swing.JLabel playerCard2JLabel;

 

654        private javax.swing.JLabel playerCard3JLabel;

 

655        private javax.swing.JLabel playerCard4JLabel;

 

656        private javax.swing.JLabel playerCard5JLabel;

 

657        private javax.swing.JLabel playerCard6JLabel;

 

658        private javax.swing.JLabel playerCard7JLabel;

 

659        private javax.swing.JLabel playerCard8JLabel;

 

660        private javax.swing.JLabel playerCard9JLabel;

 

661        private javax.swing.JLabel playerJLabel;

 

private javax.swing.JLabel playerTotalJLabel;

663       private javax.swing.JButton standJButton;

 

664       private javax.swing.JLabel statusJLabel;

 

665       // End of variables declaration

 

} // end class BlackjackGameJFrame






 

Method gameOver (lines 187–215) displays all the dealer’s cards, shows the appro-priate message in statusJLabel and displays the final point totals of both the dealer and the player. Method gameOver receives as an argument a member of the GameStatus enu-meration (defined in lines 25–31). The enumeration represents whether the player tied, lost or won the game; its four members are PUSH, LOSE, WIN and BLACKJACK.

 

When the player clicks the Deal JButton, method dealJButtonActionPerformed (lines 567–618) clears all of the JLabels that display cards or game status information. Next, the deck is shuffled (line 581), and the player and dealer receive two cards each (lines 584–595). Lines 602–603 then total each hand. If the player and the dealer both obtain scores of 21, the program calls method gameOver, passing GameStatus.PUSH (line 607). If only the dealer has 21, the program passes GameStatus.LOSE to method gameOver (line 609). If only the player has 21 after the first two cards are dealt, the program passes GameStatus.BLACKJACK to method gameOver (line 611).

 

If dealJButtonActionPerformed does not call gameOver, the player can take more cards by clicking the Hit JButton, which calls hitJButtonActionPerformed in lines 543– 564. Each time a player clicks Hit, the program deals the player one more card and displays it in the GUI. If the player exceeds 21, the game is over and the player loses. If the player has exactly 21, the player is not allowed to take any more cards, and method dealerPlay (lines 86–131) is called, causing the dealer to take cards until the dealer’s hand has a value of 17 or more (lines 98–106). If the dealer exceeds 21, the player wins (line 114); other-wise, the values of the hands are compared, and gameOver is called with the appropriate argument (lines 120–125).

 

Clicking the Stand JButton indicates that a player does not want to be dealt another card. Method standJButtonActionPerformed (lines 533–540) disables the Hit and Stand buttons, enables the Deal button, then calls method dealerPlay.

Method displayCard (lines 134–184) updates the GUI to display a newly dealt card. The method takes as arguments an integer index for the JLabel in the ArrayList that must have its image set and a String representing the card. An empty String indicates that we wish to display the card face down. If method displayCard receives a String that’s not empty, the program extracts the face and suit from the String and uses this informa-tion to display the correct image. The switch statement (lines 159–173) converts the number representing the suit to an integer and assigns the appropriate character to suit-Letter (h for hearts, d for diamonds, c for clubs and s for spades). The character in suit-Letter is used to complete the image’s filename (lines 176–178).

 

In this example, you learned how to set up a web service to support session handling so that you could keep track of each client’s session state. You also learned how to indicate from a desktop client application that it wishes to take part in session tracking. You’ll now learn how to access a database from a web service and how to consume a web service from a client web application.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.