01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: Contest.java 3732 2007-05-02 20:45:59Z gbevin $
07: */
08: package tutorial.numberguess.backend;
09:
10: import com.uwyn.rife.tools.UniqueID;
11: import com.uwyn.rife.tools.UniqueIDGenerator;
12: import java.util.HashMap;
13: import java.util.Map;
14:
15: /**
16: * This class is meant to never be instantiated. It keeps track of all active
17: * games.
18: * <p>
19: * Ideally this functionality should be implemented through the storage in a
20: * database or other persistant data storage medium. For simplicity's sake,
21: * a simple in-memory structure is used and accessed in a thread-safe manner.
22: *
23: * @author Geert Bevin (gbevin[remove] at uwyn dot com)
24: * @version $Revision: 3732 $
25: */
26: public abstract class Contest {
27: private static final Map activeGames = new HashMap();
28:
29: /**
30: * Starts a new game and registers it in the collection of active game.
31: * A unique identifier is also generated that can be used to retrieve the
32: * game afterwards.
33: *
34: * @return a <code>String</code> containing the unique id that corresponds
35: * to the newly started game.
36: */
37: public static String startGame() {
38: UniqueID gameid = UniqueIDGenerator.generate();
39: Game game = new Game();
40:
41: synchronized (Contest.activeGames) {
42: Contest.activeGames.put(gameid.toString(), game);
43: }
44:
45: return gameid.toString();
46: }
47:
48: /**
49: * Stops an active game.
50: *
51: * @param gameid The unique identifier that corresponds to the game that
52: * has to be stopped.
53: *
54: * @return the <code>Game</code> instance that has been stopped; or
55: * <p>
56: *<code>null</code> if no game could be found with the provided id.
57: */
58: public static Game stopGame(String gameid) {
59: synchronized (Contest.activeGames) {
60: return (Game) Contest.activeGames.remove(gameid);
61: }
62: }
63:
64: /**
65: * Retrieves an active game.
66: *
67: * @param gameid The unique identifier that corresponds to the game that
68: * has to be retrieved.
69: *
70: * @return the <code>Game</code> instance that corresponds to the provided
71: * id; or
72: * <p>
73: * <code>null</code> if no game could be found with the provided id
74: *
75: */
76: public static Game getGame(String gameid) {
77: return (Game) Contest.activeGames.get(gameid);
78: }
79: }
|