2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * The contents of this file are subject to the terms of either the GNU
5 * General Public License Version 2 only ("GPL") or the Common
6 * Development and Distribution License("CDDL") (collectively, the
7 * "License"). You may not use this file except in compliance with the
8 * License. You can obtain a copy of the License at
9 * http://www.netbeans.org/cddl-gplv2.html
10 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
11 * specific language governing permissions and limitations under the
12 * License. When distributing the software, include this License Header
13 * Notice in each file and include the License file at
14 * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
15 * particular file as subject to the "Classpath" exception as provided
16 * by Sun in the GPL Version 2 section of the License file that
17 * accompanied this code. If applicable, add the following below the
18 * License Header, with the fields enclosed by brackets [] replaced by
19 * your own identifying information:
20 * "Portions Copyrighted [year] [name of copyright owner]"
24 * Portions Copyrighted 2009 Jaroslav Tulach
27 package cz.xelfi.quoridor.webidor.resources;
29 import cz.xelfi.quoridor.IllegalPositionException;
30 import cz.xelfi.quoridor.webidor.*;
31 import cz.xelfi.quoridor.Move;
32 import java.io.BufferedReader;
33 import java.io.BufferedWriter;
35 import java.io.FileInputStream;
36 import java.io.FileOutputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.io.OutputStreamWriter;
41 import java.io.PrintWriter;
42 import java.io.Writer;
43 import java.util.ArrayList;
44 import java.util.Collections;
45 import java.util.Date;
46 import java.util.List;
47 import java.util.logging.Level;
48 import java.util.logging.Logger;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
51 import javax.ws.rs.DefaultValue;
52 import javax.ws.rs.GET;
53 import javax.ws.rs.POST;
54 import javax.ws.rs.PUT;
55 import javax.ws.rs.Path;
56 import javax.ws.rs.PathParam;
57 import javax.ws.rs.Produces;
58 import javax.ws.rs.QueryParam;
59 import javax.ws.rs.WebApplicationException;
60 import javax.ws.rs.core.MediaType;
61 import javax.ws.rs.core.Response.Status;
65 * @author Jaroslav Tulach <jtulach@netbeans.org>
67 public final class Games {
68 private final Quoridor quoridor;
69 private final List<Game> games = new ArrayList<Game>();
70 private final File dir;
71 private static final Logger LOG = Logger.getLogger(Games.class.getName());
73 public Games(File dir, Quoridor quoridor) {
75 this.quoridor = quoridor;
76 File[] arr = dir.listFiles();
82 } catch (IOException ex) {
83 LOG.log(Level.WARNING, "Wrong game in " + f, ex);
90 @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
91 public GameId createGame(
92 @QueryParam("loginID") String id,
93 @QueryParam("white") String white,
94 @QueryParam("black") String black
95 ) throws IOException {
96 String logUser = quoridor.isLoggedIn(id);
97 if (logUser == null) {
98 throw new WebApplicationException(Status.UNAUTHORIZED);
101 throw new WebApplicationException(Status.PRECONDITION_FAILED);
104 throw new WebApplicationException(Status.PRECONDITION_FAILED);
106 if (!logUser.equals(white) && !logUser.equals(black)) {
107 throw new WebApplicationException(Status.PRECONDITION_FAILED);
110 Game g = new Game(white, black);
118 @Produces(MediaType.TEXT_PLAIN)
119 public String getBoard(
120 @PathParam("id") String id,
121 @QueryParam("move") @DefaultValue("-1") int move
123 Game g = findGame(id, move);
125 throw new IllegalArgumentException("Unknown game " + id);
127 return g.getBoard().toString();
132 @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
133 public Game getBoardInfo(
134 @QueryParam("loginID") @DefaultValue("") String loginId,
135 @PathParam("id") String id,
136 @QueryParam("move") @DefaultValue("-1") int move
138 Game g = findGame(id, move);
139 if (canSee(g.getId(), loginId)) {
142 throw new WebApplicationException(Status.UNAUTHORIZED);
145 private boolean canSee(GameId id, String loginId) {
146 if (!id.isFinished()) {
149 String logUser = quoridor.isLoggedIn(loginId);
150 if (logUser == null) {
153 if (logUser.equals(id.getWhite())) {
156 if (logUser.equals(id.getBlack())) {
164 @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
165 public GameId applyMove(
166 @QueryParam("loginID") String loginId,
167 @PathParam("id") String id,
168 @QueryParam("player") String player,
169 @QueryParam("move") String move,
170 @QueryParam("comment") String comment
171 ) throws IllegalPositionException {
172 String logUser = quoridor.isLoggedIn(loginId);
173 if (logUser == null) {
174 throw new WebApplicationException(Status.UNAUTHORIZED);
176 if (!logUser.equals(player)) {
177 throw new WebApplicationException(Status.UNAUTHORIZED);
179 if (comment == null && move == null) {
180 throw new WebApplicationException(Status.BAD_REQUEST);
183 Game g = findGame(id);
185 throw new IllegalArgumentException("Unknown game " + id);
188 Move m = Move.valueOf(move);
189 g.apply(player, m, new Date());
191 if (comment != null) {
192 g.comment(player, comment, new Date());
196 } catch (IOException ex) {
197 LOG.log(Level.WARNING, "Cannot store game " + id, ex);
203 @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
204 public List<GameId> listGames(
205 @DefaultValue("") @QueryParam("loginID") String loginId,
206 @DefaultValue("") @QueryParam("status") String status
208 List<GameId> arr = new ArrayList<GameId>(games.size());
209 for (Game g : games) {
210 if (!canSee(g.getId(), loginId)) {
213 if (status.length() == 0 || g.getId().getStatus().toString().equals(status)) {
217 Collections.sort(arr, GameId.NEWEST_FIRST);
221 public List<Game> getGames() {
225 private Game findGame(String id) {
226 for (Game g : games) {
227 if (g.getId().getId().equals(id)) {
233 private Game findGame(String id, int move) {
234 Game g = findGame(id);
236 throw new IllegalArgumentException("Unknown game " + id);
239 return move == -1 ? g : g.snapshot(move);
240 } catch (IllegalPositionException ex) {
241 Logger.getLogger(Games.class.getName()).log(Level.SEVERE, null, ex);
246 private static final Pattern saidWho = Pattern.compile("# *([^ ]*) *@(.*):$");
248 private Game readGame(File f) throws IOException {
249 InputStream is = new FileInputStream(f);
250 BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
257 String line = r.readLine();
262 if (line.length() == 0) {
265 if (line.startsWith("# white: ")) {
266 white = line.substring(9);
269 if (line.startsWith("# black: ")) {
270 black = line.substring(9);
273 if (line.startsWith("#")) {
274 Matcher m =saidWho.matcher(line);
283 if (line.startsWith("# ")) {
284 line = line.substring(2);
286 line = line.substring(1);
291 d = new Date(Date.parse(when));
293 } catch (IllegalArgumentException ex) {
294 LOG.warning("Unparseable date " + when + " in " + f);
296 g.comment(who, line, d);
301 if (white == null || black == null) {
302 throw new IOException("Missing white and black identification in " + f);
305 GameId id = new GameId(f.getName(), white, black, new Date(f.lastModified()), new Date(f.lastModified()), GameStatus.whiteMove, 0, false);
308 int hash = line.indexOf('#');
310 line = line.substring(0, hash);
312 if (line.equals("finish")) {
315 String[] moves = line.split(" ");
316 if (moves.length == 0) {
319 if (moves.length > 2) {
320 throw new IOException("Too much moves on line: " + line);
323 if (!"...".equals(moves[0])) {
324 g.apply(white, Move.valueOf(moves[0]), null);
326 if (moves.length == 2) {
327 g.apply(black, Move.valueOf(moves[1]), null);
329 } catch (IllegalPositionException ex) {
330 throw new IOException("Wrong move: " + ex.getMessage());
334 throw new IOException("No moves in " + f);
339 private void storeGame(Game g) throws IOException {
341 File f = new File(dir, g.getId().getId());
345 final void storeGame(Game g, File f) throws IOException {
346 FileOutputStream os = new FileOutputStream(f);
347 Writer w = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
348 PrintWriter pw = new PrintWriter(w);
349 pw.println("# white: " + g.getId().getWhite());
350 pw.println("# black: " + g.getId().getBlack());
351 pw.println("# status: " + g.getId().getStatus());
353 boolean separate = true;
354 for (CommentedMove m : g.getMoves()) {
355 if (!separate && cnt % 2 == 1) {
359 pw.print(m.getMove().toString());
360 List<Note> notes = m.getComments();
364 for (Note n : notes) {
366 pw.print(n.getWho());
368 pw.print(n.getWhen());
370 for (String l : n.getComment().split("\n")) {