-
Notifications
You must be signed in to change notification settings - Fork 222
Expand file tree
/
Copy pathGameModel.java
More file actions
76 lines (66 loc) · 2.57 KB
/
GameModel.java
File metadata and controls
76 lines (66 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package scorekeep;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class GameModel {
/** AWS SDK credentials. */
private AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
.build();
private DynamoDBMapper mapper = new DynamoDBMapper(client);
private final SessionModel sessionModel = new SessionModel();
public void saveGame(Game game) throws SessionNotFoundException {
// check session
String sessionId = game.getSession();
if (sessionModel.loadSession(sessionId) == null ) {
throw new SessionNotFoundException(sessionId);
}
mapper.save(game);
}
public Game loadGame(String gameId) throws GameNotFoundException {
Game game = mapper.load(Game.class, gameId);
if ( game == null ) {
throw new GameNotFoundException(gameId);
}
return game;
}
public List<Game> loadGames(String sessionId) throws SessionNotFoundException {
if ( sessionModel.loadSession(sessionId) == null ) {
throw new SessionNotFoundException(sessionId);
}
Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":val1", new AttributeValue().withS(sessionId));
Map<String, String> ean = new HashMap<String, String>();
ean.put("#key1", "session");
DynamoDBQueryExpression<Game> queryExpression = new DynamoDBQueryExpression<Game>()
.withIndexName("session-index")
.withExpressionAttributeValues(eav)
.withExpressionAttributeNames(ean)
.withKeyConditionExpression("#key1 = :val1")
.withConsistentRead(false);
List<Game> sessionGames = mapper.query(Game.class, queryExpression);
return sessionGames;
}
public void deleteGame(String sessionId, String gameId) throws GameNotFoundException {
Game game = mapper.load(Game.class, gameId);
if ( game == null ) {
throw new GameNotFoundException(gameId);
}
mapper.delete(game);
//delete game from session
Session session = mapper.load(Session.class, sessionId);
Set<String> sessionGames = session.getGames();
sessionGames.remove(gameId);
if (sessionGames.size() == 0) {
session.clearGames();
} else {
session.setGames(sessionGames);
}
mapper.save(session);
}
}