Skip to content

Commit

Permalink
AppEngine Channel Example with Tic Tac Toe + Java (#191)
Browse files Browse the repository at this point in the history
* Moving https://code.google.com/archive/p/java-channel-tic-tac-toe/ to GitHub
* Applied Style
* fixed checkstyle
  • Loading branch information
saturnism authored and lesv committed Apr 26, 2016
1 parent a14bd02 commit e9043ca
Show file tree
Hide file tree
Showing 12 changed files with 948 additions and 0 deletions.
111 changes: 111 additions & 0 deletions appengine/channel/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<!--
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.appengine</groupId>
<artifactId>appengine-channel</artifactId>
<parent>
<groupId>com.google.cloud</groupId>
<artifactId>doc-samples</artifactId>
<version>1.0.0</version>
<relativePath>../..</relativePath>
</parent>
<properties>
<objectify.version>5.1.5</objectify.version>
</properties>
<!-- [START set_versions] -->
<prerequisites>
<maven>3.3.9</maven>
</prerequisites>
<!-- [END set_versions] -->
<dependencies>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.sdk.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
<dependency>
<groupId>com.googlecode.objectify</groupId>
<artifactId>objectify</artifactId>
<version>${objectify.version}</version>
</dependency>

<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-tools-sdk</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.28</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
</outputDirectory>
<plugins>
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.sdk.version}</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.channel;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

@Entity
public class Game {
static final Pattern[] XWins =
{Pattern.compile("XXX......"), Pattern.compile("...XXX..."), Pattern.compile("......XXX"),
Pattern.compile("X..X..X.."), Pattern.compile(".X..X..X."),
Pattern.compile("..X..X..X"), Pattern.compile("X...X...X"),
Pattern.compile("..X.X.X..")};
static final Pattern[] OWins =
{Pattern.compile("OOO......"), Pattern.compile("...OOO..."), Pattern.compile("......OOO"),
Pattern.compile("O..O..O.."), Pattern.compile(".O..O..O."),
Pattern.compile("..O..O..O"), Pattern.compile("O...O...O"),
Pattern.compile("..O.O.O..")};

@Id
public String id;
private String userX;
private String userO;
private String board;
private Boolean moveX;
private String winner;
private String winningBoard;

Game() {
}

Game(String userX, String userO, String board, boolean moveX) {
this.id = UUID.randomUUID().toString();
this.userX = userX;
this.userO = userO;
this.board = board;
this.moveX = moveX;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getUserX() {
return userX;
}

public String getUserO() {
return userO;
}

public void setUserO(String userO) {
this.userO = userO;
}

public String getBoard() {
return board;
}

public void setBoard(String board) {
this.board = board;
}

public boolean getMoveX() {
return moveX;
}

public void setMoveX(boolean moveX) {
this.moveX = moveX;
}

public String getMessageString() {
Map<String, String> state = new HashMap<String, String>();
state.put("userX", userX);
if (userO == null) {
state.put("userO", "");
} else {
state.put("userO", userO);
}
state.put("board", board);
state.put("moveX", moveX.toString());
state.put("winner", winner);
if (winner != null && winner != "") {
state.put("winningBoard", winningBoard);
}
JSONObject message = new JSONObject(state);
return message.toString();
}

public String getChannelKey(String user) {
return user + id;
}

private void sendUpdateToUser(String user) {
if (user != null) {
ChannelService channelService = ChannelServiceFactory.getChannelService();
String channelKey = getChannelKey(user);
channelService.sendMessage(new ChannelMessage(channelKey, getMessageString()));
}
}

public void sendUpdateToClients() {
sendUpdateToUser(userX);
sendUpdateToUser(userO);
}

public void checkWin() {
final Pattern[] wins;
if (moveX) {
wins = XWins;
} else {
wins = OWins;
}

for (Pattern winPattern : wins) {
if (winPattern.matcher(board).matches()) {
if (moveX) {
winner = userX;
} else {
winner = userO;
}
winningBoard = winPattern.toString();
}
}
}

public boolean makeMove(int position, String user) {
String currentMovePlayer;
char value;
if (getMoveX()) {
value = 'X';
currentMovePlayer = getUserX();
} else {
value = 'O';
currentMovePlayer = getUserO();
}

if (currentMovePlayer.equals(user)) {
char[] boardBytes = getBoard().toCharArray();
boardBytes[position] = value;
setBoard(new String(boardBytes));
checkWin();
setMoveX(!getMoveX());
sendUpdateToClients();
return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.channel;

import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetTokenServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
String gameId = req.getParameter("gamekey");
Objectify ofy = ObjectifyService.ofy();
Game game = ofy.load().type(Game.class).id(gameId).safe();

String currentUserId = userService.getCurrentUser().getUserId();
if (currentUserId.equals(game.getUserX()) || currentUserId.equals(game.getUserO())) {
String channelKey = game.getChannelKey(currentUserId);
ChannelService channelService = ChannelServiceFactory.getChannelService();
resp.setContentType("text/plain");
resp.getWriter().println(channelService.createChannel(channelKey));
return;
}
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.channel;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MoveServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
String gameId = req.getParameter("gamekey");
int piece = new Integer(req.getParameter("i"));
Objectify ofy = ObjectifyService.ofy();
Game game = ofy.load().type(Game.class).id(gameId).safe();

String currentUserId = userService.getCurrentUser().getUserId();
if (!game.makeMove(piece, currentUserId)) {
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
ofy.save().entity(game).now();
}
}
}
Loading

0 comments on commit e9043ca

Please sign in to comment.