webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Games.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 28 Sep 2009 14:42:19 +0200
changeset 115 6a80463a74c0
parent 114 ed560bfe37f0
child 117 c1057591a344
permissions -rw-r--r--
Support for comments among the moves
jtulach@36
     1
/*
jtulach@36
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jtulach@36
     3
 *
jtulach@36
     4
 * The contents of this file are subject to the terms of either the GNU
jtulach@36
     5
 * General Public License Version 2 only ("GPL") or the Common
jtulach@36
     6
 * Development and Distribution License("CDDL") (collectively, the
jtulach@36
     7
 * "License"). You may not use this file except in compliance with the
jtulach@36
     8
 * License. You can obtain a copy of the License at
jtulach@36
     9
 * http://www.netbeans.org/cddl-gplv2.html
jtulach@36
    10
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jtulach@36
    11
 * specific language governing permissions and limitations under the
jtulach@36
    12
 * License.  When distributing the software, include this License Header
jtulach@36
    13
 * Notice in each file and include the License file at
jtulach@36
    14
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
jtulach@36
    15
 * particular file as subject to the "Classpath" exception as provided
jtulach@36
    16
 * by Sun in the GPL Version 2 section of the License file that
jtulach@36
    17
 * accompanied this code. If applicable, add the following below the
jtulach@36
    18
 * License Header, with the fields enclosed by brackets [] replaced by
jtulach@36
    19
 * your own identifying information:
jtulach@36
    20
 * "Portions Copyrighted [year] [name of copyright owner]"
jtulach@36
    21
 *
jtulach@36
    22
 * Contributor(s):
jtulach@36
    23
 *
jtulach@36
    24
 * Portions Copyrighted 2009 Jaroslav Tulach
jtulach@36
    25
 */
jtulach@36
    26
jtulach@36
    27
package cz.xelfi.quoridor.webidor.resources;
jtulach@36
    28
jtulach@36
    29
import cz.xelfi.quoridor.IllegalPositionException;
jtulach@36
    30
import cz.xelfi.quoridor.webidor.*;
jtulach@36
    31
import cz.xelfi.quoridor.Move;
jtulach@37
    32
import java.io.BufferedReader;
jtulach@37
    33
import java.io.BufferedWriter;
jtulach@37
    34
import java.io.File;
jtulach@37
    35
import java.io.FileReader;
jtulach@37
    36
import java.io.FileWriter;
jtulach@36
    37
import java.io.IOException;
jtulach@37
    38
import java.io.PrintWriter;
jtulach@36
    39
import java.util.ArrayList;
jaroslav@96
    40
import java.util.Collections;
jaroslav@48
    41
import java.util.Date;
jtulach@36
    42
import java.util.List;
jtulach@37
    43
import java.util.logging.Level;
jtulach@37
    44
import java.util.logging.Logger;
jaroslav@115
    45
import java.util.regex.Matcher;
jaroslav@115
    46
import java.util.regex.Pattern;
jaroslav@100
    47
import javax.ws.rs.DefaultValue;
jtulach@36
    48
import javax.ws.rs.GET;
jtulach@36
    49
import javax.ws.rs.POST;
jtulach@36
    50
import javax.ws.rs.PUT;
jtulach@36
    51
import javax.ws.rs.Path;
jtulach@36
    52
import javax.ws.rs.PathParam;
jtulach@36
    53
import javax.ws.rs.Produces;
jtulach@36
    54
import javax.ws.rs.QueryParam;
jtulach@82
    55
import javax.ws.rs.WebApplicationException;
jtulach@36
    56
import javax.ws.rs.core.MediaType;
jtulach@82
    57
import javax.ws.rs.core.Response.Status;
jtulach@36
    58
jtulach@36
    59
/**
jtulach@36
    60
 *
jtulach@36
    61
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@36
    62
 */
jtulach@36
    63
public final class Games {
jtulach@82
    64
    private final Quoridor quoridor;
jaroslav@48
    65
    private final List<Game> games = new ArrayList<Game>();
jtulach@37
    66
    private final File dir;
jtulach@37
    67
    private static final Logger LOG = Logger.getLogger(Games.class.getName());
jtulach@37
    68
jtulach@82
    69
    public Games(File dir, Quoridor quoridor) {
jtulach@37
    70
        this.dir = dir;
jtulach@82
    71
        this.quoridor = quoridor;
jtulach@37
    72
        File[] arr = dir.listFiles();
jtulach@37
    73
        if (arr != null) {
jtulach@37
    74
            for (File f : arr) {
jtulach@37
    75
                try {
jtulach@37
    76
                    Game g = readGame(f);
jtulach@37
    77
                    games.add(g);
jtulach@37
    78
                } catch (IOException ex) {
jtulach@37
    79
                    LOG.log(Level.WARNING, "Wrong game in " + f, ex);
jtulach@37
    80
                }
jtulach@37
    81
            }
jtulach@37
    82
        }
jtulach@37
    83
    }
jtulach@36
    84
jtulach@36
    85
    @POST
jaroslav@48
    86
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
    87
    public GameId createGame(
jtulach@82
    88
        @QueryParam("loginID") String id,
jtulach@38
    89
        @QueryParam("white") String white,
jtulach@38
    90
        @QueryParam("black") String black
jaroslav@48
    91
    ) throws IOException {
jtulach@82
    92
        String logUser = quoridor.isLoggedIn(id);
jtulach@82
    93
        if (logUser == null) {
jtulach@82
    94
            throw new WebApplicationException(Status.UNAUTHORIZED);
jtulach@82
    95
        }
jtulach@38
    96
        if (white == null) {
jtulach@82
    97
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
jtulach@38
    98
        }
jtulach@38
    99
        if (black == null) {
jtulach@82
   100
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
jtulach@38
   101
        }
jtulach@82
   102
        if (!logUser.equals(white) && !logUser.equals(black)) {
jtulach@82
   103
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
jtulach@82
   104
        }
jtulach@82
   105
jtulach@38
   106
        Game g = new Game(white, black);
jaroslav@48
   107
        storeGame(g);
jtulach@36
   108
        games.add(g);
jaroslav@48
   109
        return g.getId();
jtulach@36
   110
    }
jtulach@36
   111
jtulach@38
   112
    @GET
jtulach@38
   113
    @Path("{id}")
jtulach@38
   114
    @Produces(MediaType.TEXT_PLAIN)
jaroslav@106
   115
    public String getBoard(
jaroslav@106
   116
        @PathParam("id") String id,
jaroslav@106
   117
        @QueryParam("move") @DefaultValue("-1") int move
jaroslav@106
   118
    ) {
jaroslav@106
   119
        Game g = findGame(id, move);
jtulach@38
   120
        if (g == null) {
jtulach@38
   121
            throw new IllegalArgumentException("Unknown game " + id);
jtulach@38
   122
        }
jtulach@38
   123
        return g.getBoard().toString();
jtulach@38
   124
    }
jtulach@38
   125
jaroslav@46
   126
    @GET
jaroslav@46
   127
    @Path("{id}")
jaroslav@48
   128
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@100
   129
    public Game getBoardInfo(
jaroslav@100
   130
        @PathParam("id") String id,
jaroslav@100
   131
        @QueryParam("move") @DefaultValue("-1") int move
jaroslav@100
   132
    ) {
jaroslav@100
   133
        return findGame(id, move);
jaroslav@46
   134
    }
jaroslav@46
   135
jtulach@36
   136
    @PUT
jtulach@36
   137
    @Path("{id}")
jaroslav@48
   138
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
   139
    public GameId applyMove(
jtulach@82
   140
        @QueryParam("loginID") String loginId,
jtulach@38
   141
        @PathParam("id") String id,
jtulach@38
   142
        @QueryParam("player") String player,
jaroslav@115
   143
        @QueryParam("move") String move,
jaroslav@115
   144
        @QueryParam("comment") String comment
jtulach@38
   145
    ) throws IllegalPositionException {
jtulach@82
   146
        String logUser = quoridor.isLoggedIn(loginId);
jtulach@82
   147
        if (logUser == null) {
jtulach@82
   148
            throw new WebApplicationException(Status.UNAUTHORIZED);
jtulach@82
   149
        }
jtulach@82
   150
        if (!logUser.equals(player)) {
jtulach@82
   151
            throw new WebApplicationException(Status.UNAUTHORIZED);
jtulach@82
   152
        }
jaroslav@115
   153
        if (comment == null && move == null) {
jaroslav@115
   154
            throw new WebApplicationException(Status.BAD_REQUEST);
jaroslav@115
   155
        }
jtulach@82
   156
jtulach@36
   157
        Game g = findGame(id);
jtulach@36
   158
        if (g == null) {
jtulach@36
   159
            throw new IllegalArgumentException("Unknown game " + id);
jtulach@36
   160
        }
jaroslav@115
   161
        if (move != null) {
jaroslav@115
   162
            Move m = Move.valueOf(move);
jaroslav@115
   163
            g.apply(player, m, new Date());
jaroslav@115
   164
        }
jaroslav@115
   165
        if (comment != null) {
jaroslav@115
   166
            g.comment(player, comment, new Date());
jaroslav@115
   167
        }
jtulach@37
   168
        try {
jtulach@37
   169
            storeGame(g);
jtulach@37
   170
        } catch (IOException ex) {
jtulach@37
   171
            LOG.log(Level.WARNING, "Cannot store game " + id, ex);
jtulach@37
   172
        }
jaroslav@48
   173
        return g.getId();
jtulach@36
   174
    }
jtulach@36
   175
jtulach@36
   176
    @GET
jaroslav@48
   177
    @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
   178
    public List<GameId> listGames() {
jaroslav@48
   179
        List<GameId> arr = new ArrayList<GameId>(games.size());
jaroslav@48
   180
        for (Game g : games) {
jaroslav@48
   181
            arr.add(g.getId());
jaroslav@48
   182
        }
jaroslav@96
   183
        Collections.sort(arr, GameId.NEWEST_FIRST);
jaroslav@48
   184
        return arr;
jaroslav@48
   185
    }
jaroslav@48
   186
jtulach@36
   187
    public List<Game> getGames() {
jtulach@36
   188
        return games;
jtulach@36
   189
    }
jtulach@36
   190
jtulach@36
   191
    private Game findGame(String id) {
jtulach@36
   192
        for (Game g : games) {
jaroslav@48
   193
            if (g.getId().getId().equals(id)) {
jtulach@36
   194
                return g;
jtulach@36
   195
            }
jtulach@36
   196
        }
jtulach@36
   197
        return null;
jtulach@36
   198
    }
jaroslav@100
   199
    private Game findGame(String id, int move) {
jaroslav@100
   200
        Game g = findGame(id);
jaroslav@100
   201
        if (g == null) {
jaroslav@100
   202
            throw new IllegalArgumentException("Unknown game " + id);
jaroslav@100
   203
        }
jaroslav@100
   204
        try {
jaroslav@100
   205
            return move == -1 ? g : g.snapshot(move);
jaroslav@100
   206
        } catch (IllegalPositionException ex) {
jaroslav@100
   207
            Logger.getLogger(Games.class.getName()).log(Level.SEVERE, null, ex);
jaroslav@100
   208
            return null;
jaroslav@100
   209
        }
jaroslav@100
   210
    }
jtulach@36
   211
jaroslav@115
   212
    private static final Pattern saidWho = Pattern.compile("# *([^ ]*) *@(.*):$");
jaroslav@115
   213
jtulach@37
   214
    private Game readGame(File f) throws IOException {
jtulach@37
   215
        BufferedReader r = new BufferedReader(new FileReader(f));
jtulach@37
   216
        String white = null;
jtulach@37
   217
        String black = null;
jtulach@37
   218
        Game g = null;
jaroslav@115
   219
        String who = null;
jaroslav@115
   220
        String when = null;
jtulach@37
   221
        for (;;) {
jtulach@37
   222
            String line = r.readLine();
jtulach@37
   223
            if (line == null) {
jaroslav@48
   224
                line = "finish";
jtulach@37
   225
            }
jtulach@39
   226
            line = line.trim();
jtulach@39
   227
            if (line.length() == 0) {
jtulach@39
   228
                continue;
jtulach@39
   229
            }
jtulach@37
   230
            if (line.startsWith("# white: ")) {
jtulach@37
   231
                white = line.substring(9);
jtulach@37
   232
                continue;
jtulach@37
   233
            }
jtulach@37
   234
            if (line.startsWith("# black: ")) {
jtulach@37
   235
                black = line.substring(9);
jtulach@37
   236
                continue;
jtulach@37
   237
            }
jtulach@37
   238
            if (line.startsWith("#")) {
jaroslav@115
   239
                Matcher m =saidWho.matcher(line);
jaroslav@115
   240
                if (m.matches()) {
jaroslav@115
   241
                    who = m.group(1);
jaroslav@115
   242
                    when = m.group(2);
jaroslav@115
   243
                    continue;
jaroslav@115
   244
                }
jaroslav@115
   245
                if (g == null) {
jaroslav@115
   246
                    continue;
jaroslav@115
   247
                }
jaroslav@115
   248
                if (line.startsWith("# ")) {
jaroslav@115
   249
                    line = line.substring(2);
jaroslav@115
   250
                } else {
jaroslav@115
   251
                    line = line.substring(1);
jaroslav@115
   252
                }
jaroslav@115
   253
                Date d = new Date();
jaroslav@115
   254
                try {
jaroslav@115
   255
                    if (when != null) {
jaroslav@115
   256
                        d = new Date(Date.parse(when));
jaroslav@115
   257
                    }
jaroslav@115
   258
                } catch (IllegalArgumentException ex) {
jaroslav@115
   259
                    LOG.warning("Unparseable date " + when + " in " + f);
jaroslav@115
   260
                }
jaroslav@115
   261
                g.comment(who, line, d);
jaroslav@115
   262
                who = null;
jaroslav@115
   263
                when = null;
jtulach@37
   264
                continue;
jtulach@37
   265
            }
jtulach@37
   266
            if (white == null || black == null) {
jtulach@37
   267
                throw new IOException("Missing white and black identification in " + f);
jtulach@37
   268
            }
jtulach@37
   269
            if (g == null) {
jtulach@78
   270
                GameId id = new GameId(f.getName(), white, black, new Date(f.lastModified()), new Date(f.lastModified()), GameStatus.whiteMove);
jaroslav@48
   271
                g = new Game(id);
jaroslav@48
   272
            }
jaroslav@114
   273
            int hash = line.indexOf('#');
jaroslav@114
   274
            if (hash >= 0) {
jaroslav@114
   275
                line = line.substring(0, hash);
jaroslav@114
   276
            }
jaroslav@48
   277
            if (line.equals("finish")) {
jaroslav@48
   278
                break;
jtulach@37
   279
            }
jtulach@37
   280
            String[] moves = line.split(" ");
jtulach@37
   281
            if (moves.length == 0) {
jtulach@37
   282
                continue;
jtulach@37
   283
            }
jtulach@37
   284
            if (moves.length > 2) {
jtulach@37
   285
                throw new IOException("Too much moves on line: " + line);
jtulach@37
   286
            }
jtulach@37
   287
            try {
jaroslav@114
   288
                if (!"...".equals(moves[0])) {
jaroslav@114
   289
                    g.apply(white, Move.valueOf(moves[0]), null);
jaroslav@114
   290
                }
jtulach@37
   291
                if (moves.length == 2) {
jtulach@79
   292
                    g.apply(black, Move.valueOf(moves[1]), null);
jtulach@37
   293
                }
jtulach@37
   294
            } catch (IllegalPositionException ex) {
jtulach@37
   295
                throw new IOException("Wrong move: " + ex.getMessage());
jtulach@37
   296
            }
jtulach@37
   297
        }
jtulach@37
   298
        if (g == null) {
jtulach@37
   299
            throw new IOException("No moves in " + f);
jtulach@37
   300
        }
jtulach@37
   301
        return g;
jtulach@36
   302
    }
jtulach@36
   303
jtulach@37
   304
    private void storeGame(Game g) throws IOException {
jtulach@37
   305
        dir.mkdirs();
jaroslav@48
   306
        File f = new File(dir, g.getId().getId());
jaroslav@115
   307
        storeGame(g, f);
jaroslav@115
   308
    }
jaroslav@115
   309
jaroslav@115
   310
    final void storeGame(Game g, File f) throws IOException {
jtulach@37
   311
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
jaroslav@48
   312
        pw.println("# white: " + g.getId().getWhite());
jaroslav@48
   313
        pw.println("# black: " + g.getId().getBlack());
jtulach@77
   314
        pw.println("# status: " + g.getId().getStatus());
jtulach@37
   315
        int cnt = 0;
jaroslav@115
   316
        boolean separate = true;
jaroslav@115
   317
        for (CommentedMove m : g.getMoves()) {
jaroslav@115
   318
            if (!separate && cnt % 2 == 1) {
jaroslav@115
   319
                pw.print("... ");
jaroslav@115
   320
            }
jaroslav@115
   321
            separate = true;
jaroslav@115
   322
            pw.print(m.getMove().toString());
jaroslav@115
   323
            List<Note> notes = m.getComments();
jaroslav@115
   324
            if (notes != null) {
jaroslav@115
   325
                separate = false;
jtulach@37
   326
                pw.println();
jaroslav@115
   327
                for (Note n : notes) {
jaroslav@115
   328
                    pw.print ("# ");
jaroslav@115
   329
                    pw.print(n.getWho());
jaroslav@115
   330
                    pw.print("@");
jaroslav@115
   331
                    pw.print(n.getWhen());
jaroslav@115
   332
                    pw.println(":");
jaroslav@115
   333
                    for (String l : n.getComment().split("\n")) {
jaroslav@115
   334
                        pw.print("# ");
jaroslav@115
   335
                        pw.println(l);
jaroslav@115
   336
                    }
jaroslav@115
   337
                }
jaroslav@115
   338
            }
jaroslav@115
   339
jaroslav@115
   340
            cnt++;
jaroslav@115
   341
jaroslav@115
   342
            if (separate) {
jaroslav@115
   343
                if (cnt % 2 == 0) {
jaroslav@115
   344
                    pw.println();
jaroslav@115
   345
                } else {
jaroslav@115
   346
                    pw.print(' ');
jaroslav@115
   347
                }
jtulach@37
   348
            }
jtulach@37
   349
        }
jtulach@37
   350
        pw.println();
jtulach@37
   351
        pw.println();
jtulach@37
   352
        pw.flush();
jtulach@37
   353
        pw.close();
jtulach@37
   354
    }
jtulach@36
   355
}