KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > poker > business > GameList


1 package poker.business;
2
3 import java.util.Vector JavaDoc;
4 import java.sql.SQLException JavaDoc;
5 import poker.data.DODS_GameData.*;
6 import poker.data.DODS_Fortune.*;
7 import com.lutris.appserver.server.sql.*;
8 import com.lutris.appserver.server.Enhydra;
9 import com.lutris.logging.Logger;
10 import com.lutris.util.*;
11 //import dods.builder.sourceGenerators.Query.*;
12
import com.lutris.dods.builder.generator.query.*;
13 import poker.spec.*;
14 /**
15  *
16  * EnhyDraw!, beta 4, 5/21/99
17  *
18  * Copyright 1999, Larry Wolcot & Daryl Tempesta
19  * ALL rights reserved. Not for commercial use
20  * without written permission from both authors.
21  *
22  * This is the GameList object that does all of the database dirtywork.
23  * The GameManager class started off just using a Vector to keep a list
24  * of all active PokerGame classes. It's not the most direct way of doing
25  * things, but by far the easiest way to illustrate how the DODS Objects
26  * can easily be used within a standard application.
27  *
28  * In the GameManager, I just changed the gameList to extend this object
29  * instead of a Vector. Now, we can simply divert some of the Vector's
30  * methods and use it more like a standard database adapter. Otherwise,
31  * if the useDB flag is set to false, we can just do a pass-through to
32  * the Super Object (Vector).
33  */

34 public class GameList extends Vector JavaDoc implements java.io.Serializable JavaDoc {
35
36     private boolean useDB = false;
37
38    /**
39     * Public Constructor
40     */

41     public GameList(int n){
42         super(n);
43     }
44
45     /**
46      * Private Constructor used by getCopy() method
47      */

48     private GameList(){
49         super(0);
50     }
51
52     /**
53      * This method returns a copy of the gameList object.
54      */

55     protected GameList getCopy(){
56       GameList newCopy = new GameList();
57       newCopy = this;
58       return newCopy;
59     }
60
61
62     /**
63      * Here is where we determine how to store our data.. db or memory.
64      */

65     public void setUseDB(boolean useDB) throws Exception JavaDoc{
66       try {
67       this.useDB = useDB;
68       } catch(Exception JavaDoc e) {
69           throw e;
70       }
71     }
72
73    /**
74     * Send to the Vector() or the DB depending on the useDB flag
75     * This is where we hook into the DODS_GameData Object
76     */

77     public synchronized void addGame(PokerGame thisGame){
78       if (useDB == false) {
79           super.addElement(thisGame);
80       } else {
81           try {
82               addGameToDB(thisGame);
83           } catch (Exception JavaDoc e) {
84         //There was a problem adding the game! bummer..
85
}
86       }
87     }
88
89    /**
90     * This is a private method that maps the PokerGame to
91     * a GameDataDO Object so it can be inserted into the database.
92     */

93     public synchronized void addGameToDB(PokerGame newGame) throws Exception JavaDoc {
94     //remap the PokerGame Object into a GameDataDO built by DODS.
95
GameDataDO nullDO = null;
96     GameDataDO newGameDataDO = mapToDO(nullDO, newGame);
97
98     try {
99         DBTransaction db =Enhydra.getDatabaseManager().createTransaction();
100
101         try {
102
103         //Insert the newly mapped object into the DB
104
db.insert(newGameDataDO);
105         db.commit();
106         } catch (SQLException JavaDoc se) {
107
108         //Something went wrong, so roll it back and pass it on!
109
db.rollback();
110             throw se;
111         } finally {
112
113         //This releases all resources allocated in last trans
114
db.release();
115         }
116     } catch (Exception JavaDoc e) {
117         throw e;
118         }
119     }
120
121     /**
122      * This private method takes a PokerGame object and maps it
123      * into a DODS GameDataDO object. Ideally, they would be the same
124      * but this is used to illustrate adding a DODS objects to
125      * a completed application.
126      * Hopefully, Jay will finish the "fake persistance" sooner
127      * or later, then this will look archaic.
128      */

129     private synchronized GameDataDO mapToDO(
130             GameDataDO newGameDataDO, PokerGame newGame){
131     try {
132         newGameDataDO = GameDataDO.createVirgin();
133         newGameDataDO.setName(newGame.getName());
134         newGameDataDO.setPassword(newGame.getPassword());
135             newGameDataDO.setEmail(newGame.getEmail());
136             newGameDataDO.setCash(newGame.getCash());
137             newGameDataDO.setLargestBet(newGame.getLargestBet());
138             newGameDataDO.setSmallestBet(newGame.getSmallestBet());
139             newGameDataDO.setTotalPlayed(newGame.getTotalPlayed());
140             newGameDataDO.setTotalWon(newGame.getTotalWon());
141             newGameDataDO.setDeck(newGame.getDeck());
142     } catch (Exception JavaDoc e){
143           System.out.print(e.getMessage());
144           e.printStackTrace();
145        //This is a DODS sourceGenetaror exception
146
}
147     return newGameDataDO;
148     }
149
150     /**
151      * This private method takes a GameDataDO object and maps it
152      * into a PokerGame object. Ideally, they would be the same
153      * but this is used to illustrate adding a DODS objects to
154      * a completed application. Ditto from the method above
155      */

156     private synchronized PokerGame mapNewPokerGame(GameDataDO thisGame){
157     PokerGameImpl newPokerGame = new PokerGameImpl("", "", "",0);
158
159         try {
160             newPokerGame.setName(thisGame.getName());
161             newPokerGame.setPassword(thisGame.getPassword());
162             newPokerGame.setEmail(thisGame.getEmail());
163             newPokerGame.setCash(thisGame.getCash());
164             newPokerGame.setLargestBet(thisGame.getLargestBet());
165             newPokerGame.setSmallestBet(thisGame.getSmallestBet());
166             newPokerGame.setTotalPlayed(thisGame.getTotalPlayed());
167             newPokerGame.setTotalWon(thisGame.getTotalWon());
168             newPokerGame.setDeck(thisGame.getDeck());
169         newPokerGame.setID(thisGame.getOId().toString());
170         } catch (Exception JavaDoc e){
171            //There really shouldn't be an exception
172
}
173         return newPokerGame;
174     }
175
176     /**
177      * This method detremines the storage medium, then dishes
178      * the removeGame call out to the proper method
179      */

180     public synchronized void removeGame(String JavaDoc thisName){
181     if (this.useDB) {
182         try {
183         removeDBGame(thisName);
184         } catch (Exception JavaDoc e) {
185         //FIX: nothing done!
186
}
187     } else {
188         removeMemoryGame(thisName);
189     }
190     }
191
192     /**
193      * This method removes thisGame's record from the DB
194      */

195     public synchronized void removeDBGame(String JavaDoc name) throws Exception JavaDoc{
196         GameDataDO gameDataDO = getGameDataByName(name);
197         try {
198             DBTransaction db =
199         Enhydra.getDatabaseManager().createTransaction();
200             try {
201                 // Multiple data objects could be update, deleted,inserted
202
// here as a single transaction.....
203
//Thread.currentThread().dumpStack();
204
db.delete(gameDataDO);
205                 db.commit();
206             } catch (SQLException JavaDoc sqle) {
207                 db.rollback();
208                 throw sqle;
209             } finally {
210                 // You must call this to free any resources (such as
211
// connections) that were allocated by the transaction.
212
db.release();
213             }
214         } catch (Exception JavaDoc e) {
215             // You should deal with any exceptions here....
216
throw e;
217         }
218     }
219
220     /**
221      * This method removes the thisGame object from the Vector
222      */

223     public void removeMemoryGame(String JavaDoc name){
224         int marker = 0;
225         PokerGame thatGame;
226
227         //Lock gamelist before opps, for thread paranoia!
228
synchronized (this){
229         //get the index equal to thisGame, then remove it
230
for (int i = 0; i < super.size(); i++){
231                 thatGame = (PokerGame)super.elementAt(i);
232             //if(thatGame.getName().equalsIgnoreCase(name)){
233
if(thatGame.getName().equals(name)){
234            marker = i;
235             }
236             }
237         super.removeElementAt(marker);
238     }
239     }
240
241     /**
242      * This is a provate method that returns the GameDataDO
243      * from the database where oId = id
244      */

245     private GameDataDO getGameDataByName(String JavaDoc name)
246                         throws Exception JavaDoc{
247     GameDataDO gotGameDataDO = null;
248     GameDataQuery dq = new GameDataQuery();
249     dq.setQueryName(name);
250         try {
251             gotGameDataDO = (GameDataDO) dq.getNextDO();
252         }
253         finally {
254             // Free up any resources
255
// dq.reset();
256
}
257         return gotGameDataDO;
258     }
259
260     /**
261      * This method ddtermines which storage medium is ised, then
262      * doles the getGameByName request to the right place.
263      */

264     public PokerGame getGame(String JavaDoc name){
265         PokerGame thisGame = null;
266
267     if (useDB){
268         try {
269            GameDataDO thisDO = null;
270            thisDO = getGameDataByName(name);
271            thisGame = mapNewPokerGame(thisDO);
272
273         } catch (Exception JavaDoc e) {
274         Enhydra.getLogChannel().write(Logger.DEBUG, "ERROR! " +
275             e.toString());
276            //FIX: Still need to take care of some exceptions :)
277
}
278     } else {
279         thisGame = getGameInMemory(name);
280     }
281
282     return thisGame;
283
284     }
285
286     /**
287      * This method ddtermines which storage medium is ised, then
288      * doles the getIsNameUsed request to the right place.
289      */

290     public boolean getIsNameUsed(String JavaDoc name){
291     boolean isUsed = true;
292
293     if (this.useDB) {
294         isUsed = getIsNameUsedInDB(name);
295     } else {
296         isUsed = getIsNameUsedInMemory(name);
297     }
298
299     return isUsed;
300     }
301
302     /**
303      * This method ddtermines which storage medium is ised, then
304      * doles the getTopTen method to the right place.
305      */

306     public Vector JavaDoc getTopTen(){
307         Vector JavaDoc topTen = new Vector JavaDoc(0);
308         if (this.useDB) {
309             topTen = getTopTenInDB();
310         } else {
311             topTen = getTopTenInMemory();
312         }
313
314         return topTen;
315     }
316
317     /**
318      * This method ddtermines which storage medium is ised, then
319      * doles the authenticate request to the right place.
320      */

321     public boolean authenticate(String JavaDoc name, String JavaDoc pw){
322       boolean auth = false;
323
324       if (useDB) {
325         auth = authenticateInDB(name, pw);
326       }
327       else {
328         auth = authenticateInMemory(name, pw);
329       }
330
331       return auth;
332     }
333
334     /**
335      * Check to see if this name has been used in the DB
336      */

337     public synchronized boolean getIsNameUsedInDB(String JavaDoc name){
338         boolean isUsed = false;
339 // GameDataDO thisGameDataDO = null;
340
try {
341             if (getGameDataByName(name) == null) {
342             isUsed = false;
343         }
344             else {
345             isUsed = true;
346         }
347     } catch (Exception JavaDoc e) { isUsed = false; }
348         return isUsed;
349     }
350
351     /**
352      * Check to see if this name has been used in Memory
353      */

354     public synchronized boolean getIsNameUsedInMemory(String JavaDoc name){
355         boolean isUsed = false;
356         PokerGame thisGame;
357
358         //Get copy of gameList object so we dont have to
359
// worry about locking the object for threadsafe opps
360
GameList gameListCopy = this.getCopy();
361
362         // I used the for-next so that I could use equalsIgnorecase
363
// instead of Vector.contains()
364
for (int i = 0; i < gameListCopy.size(); i++){
365             thisGame = (PokerGame)gameListCopy.elementAt(i);
366             //if (thisGame.getName().equalsIgnoreCase(name)){
367
if (thisGame.getName().equals(name)){
368                 isUsed = true;
369             }
370         }
371         return isUsed;
372     }
373
374     /**
375      * Authenticate user in DB
376      */

377     public synchronized boolean authenticateInDB
378         (String JavaDoc name, String JavaDoc pw) {
379       boolean isAuth = false;
380       try {
381         GameDataDO thisGameDataDO = getGameDataByName(name);
382         if (thisGameDataDO != null) {
383           if (thisGameDataDO.getPassword().equalsIgnoreCase(pw)) {
384             isAuth = true;
385           }
386         }
387         else {
388           isAuth = false;
389         }
390       }
391       catch (Exception JavaDoc e) {
392         e.printStackTrace(); // VR
393
//Ooops! Not much excaption handeling in the app yet!
394
}
395       return isAuth;
396     }
397
398     /**
399      * Authenticate user in memory
400      */

401     public synchronized boolean authenticateInMemory (String JavaDoc name, String JavaDoc pw){
402         boolean isAuth = false;
403         PokerGame thisGame;
404
405         //Get copy of the gameList object so we dont have to
406
//worry about locking it for threadsave opps
407
GameList gameListCopy = this.getCopy();
408
409         // I used the for-next so that I could use equalsIgnorecase
410
// instead of Vector.contains()
411
for (int i = 0; i < gameListCopy.size(); i++) {
412             thisGame = (PokerGame)gameListCopy.elementAt(i);
413             //if ((thisGame.getName().equalsIgnoreCase(name)) &
414
// (thisGame.getPassword().equalsIgnoreCase(pw))) {
415
if ((thisGame.getName().equals(name)) &
416                (thisGame.getPassword().equals(pw))) {
417
418                   isAuth = true;
419             }
420         }
421         return isAuth;
422     }
423
424     /**
425      * Return the game that belongs to user name
426      * from the Vector in memory
427      */

428     public synchronized PokerGame getGameInMemory(String JavaDoc name){
429         PokerGameImpl thisGame = new PokerGameImpl(name , "", "",0);
430
431         //Get copy of the gameList object so we dont have to
432
//worry about locking it for threadsafe opps
433
GameList gameListCopy = this.getCopy();
434         synchronized(thisGame){
435            //Yeah, I could have done this another way, but I didn't
436
for (int i = 0; i < gameListCopy.size(); i++){
437                thisGame = (PokerGameImpl)gameListCopy.elementAt(i);
438                //if (thisGame.getName().equalsIgnoreCase(name)){
439
if (thisGame.getName().equals(name)){
440                    return thisGame;
441                }
442            }
443         }
444         return thisGame;
445     }
446
447    /**
448     * return the top ten players ranked by cash won
449     */

450     public synchronized Vector JavaDoc getTopTenInMemory(){
451         Vector JavaDoc topTen = new Vector JavaDoc(0);
452         PokerGameImpl blankGame;
453         for (int i = 0; i < 10; i++){
454             blankGame = new PokerGameImpl("", "", "",0);
455             topTen.addElement(blankGame);
456         }
457         PokerGame game;
458         int rank[] = new int[10]; int Cash = 0;
459
460         //get copy of gameList so we don't have to
461
//worry about locking the object for threadsafe opps
462
GameList gameListCopy = this.getCopy();
463
464         //Really scary sort routine I came up with.
465
for (int x = 0; x < 10; x++){
466             for (int i = 0; i < gameListCopy.size(); i++){
467                  game = (PokerGame)gameListCopy.elementAt(i);
468                  if (x < 1){
469                      if (game.getCash() > rank[x]){
470                          rank[x] = game.getCash();
471                          topTen.setElementAt(game, x);
472                      }
473                  } else {
474                      if ((rank[x-1] >= game.getCash()) &
475                         (!topTen.contains(game)) &
476                         (rank[x] <= game.getCash())){
477                           rank[x] = game.getCash();
478                           topTen.setElementAt(game, x);
479                      }
480                  }
481             }
482         }
483         return topTen;
484     }
485
486     /**
487      * Check to see if the DO changes need to be updated to the DB
488      */

489     public synchronized void updateGame(PokerGame thisGame){
490     if ( (this.useDB) & (thisGame.getIsDirty()) ) {
491         try {
492            GameDataDO gameDataDO =
493                    getGameDataByName(thisGame.getName());
494            gameDataDO.setDeck(thisGame.getDeck());
495                gameDataDO.setLargestBet(thisGame.getLargestBet());
496                gameDataDO.setSmallestBet(thisGame.getSmallestBet());
497                gameDataDO.setTotalPlayed(thisGame.getTotalPlayed());
498                gameDataDO.setTotalWon(thisGame.getTotalWon());
499                gameDataDO.setCash(thisGame.getCash());
500
501 //vr DBTransaction db = Enhydra.getDatabaseManager().createTransaction();
502
try {
503 //vr db.update(gameDataDO);
504
//vr db.commit();
505
gameDataDO.save(); //vr
506
}
507                catch (SQLException JavaDoc sqle) {
508            Enhydra.getLogChannel().write(Logger.INFO, "ERROR! " +
509                         sqle.toString());
510 //vr db.rollback();
511
//vr throw sqle;
512
}
513                finally {
514 //vr db.release();
515
}
516         } catch (Exception JavaDoc e) {
517                 Enhydra.getLogChannel().write(Logger.DEBUG, "ERROR! " +
518                         e.toString());
519                 //FIX: Still need to take care of some exceptions :)
520
}
521     }
522     }
523
524     /**
525      * This method returns the total players registered in the
526      * DB or Vector
527      */

528     public int getCount(){
529     int n = 0;
530     if (!useDB){
531         n = this.size();
532     } else {
533            GameDataQuery dq = new GameDataQuery();
534            dq.getQueryBuilder().addEndClause( " order by Cash" );
535            PokerGame tempGame = null;
536            try {
537                GameDataDO[] allGames = dq.getDOArray();
538            n = allGames.length;
539            } catch (Exception JavaDoc e) {
540                Enhydra.getLogChannel().write(Logger.INFO, "ERROR: " +
541                                                           e.toString());
542        }
543
544     }
545
546     return n;
547     }
548
549     /**
550      * This method queries the database for all games sorted
551      * by score, then returns a vector with the top 10
552      */

553     public Vector JavaDoc getTopTenInDB(){
554         GameDataQuery dq = new GameDataQuery();
555         dq.getQueryBuilder().addEndClause( " order by Cash" );
556     Vector JavaDoc topTen = new Vector JavaDoc(0);
557     for (int i = 0; i < 10; i++){
558          topTen.addElement(new PokerGameImpl("","","",0));
559         }
560
561     PokerGame tempGame = null;
562     try {
563             GameDataDO[] allGames = dq.getDOArray();
564
565         int x = 0;
566             for (int i = allGames.length -1; i > -1; i--){
567         tempGame = mapNewPokerGame(allGames[i]);
568         topTen.setElementAt(tempGame,x);
569         x++;
570         if (x == 10) { i = -1; }
571             }
572
573     } catch (Exception JavaDoc e) {
574             Enhydra.getLogChannel().write(Logger.INFO, "ERROR: " +
575                             e.toString());
576         //FIX: Oops! I really should handle this
577
}
578
579         return topTen;
580     }
581
582     /**
583      * get rank of current dollars compared to the gameList
584      */

585     public synchronized int getRank(int cash){
586         PokerGame game;
587     GameList gameListCopy = this.getCopy();
588         int rank = 0;
589     if (!useDB){
590            //opps to be done on copy, eliminates need for object lock
591
for (int i = 0; i < gameListCopy.size(); i++){
592                 game = (PokerGame)gameListCopy.elementAt(i);
593                 if (game.getCash() > cash) { rank++; }
594            }
595     } else {
596            GameDataQuery dq = new GameDataQuery();
597            dq.getQueryBuilder().addEndClause( " order by Cash" );
598            try {
599                GameDataDO[] allGames = dq.getDOArray();
600                for (int i = 0; i < allGames.length; i++){
601                     if (allGames[i].getCash() > cash) { rank++; }
602                }
603            } catch (Exception JavaDoc e) {
604                Enhydra.getLogChannel().write(Logger.INFO, "ERROR: " +
605                                                           e.toString());
606            }
607     }
608
609         return rank + 1;
610     }
611
612
613 }
614
Popular Tags