webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Games.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Sep 2009 07:58:56 +0200
changeset 96 2eeaa41236c3
parent 95 36ace6ba1dc1
child 100 8b899ed24f9f
permissions -rw-r--r--
Sorting games by their newestness
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;
jaroslav@95
    32
import java.awt.Image;
jtulach@37
    33
import java.io.BufferedReader;
jtulach@37
    34
import java.io.BufferedWriter;
jtulach@37
    35
import java.io.File;
jtulach@37
    36
import java.io.FileReader;
jtulach@37
    37
import java.io.FileWriter;
jtulach@36
    38
import java.io.IOException;
jtulach@37
    39
import java.io.PrintWriter;
jtulach@36
    40
import java.util.ArrayList;
jaroslav@96
    41
import java.util.Collections;
jaroslav@48
    42
import java.util.Date;
jtulach@36
    43
import java.util.List;
jtulach@37
    44
import java.util.logging.Level;
jtulach@37
    45
import java.util.logging.Logger;
jtulach@36
    46
import javax.ws.rs.GET;
jtulach@36
    47
import javax.ws.rs.POST;
jtulach@36
    48
import javax.ws.rs.PUT;
jtulach@36
    49
import javax.ws.rs.Path;
jtulach@36
    50
import javax.ws.rs.PathParam;
jtulach@36
    51
import javax.ws.rs.Produces;
jtulach@36
    52
import javax.ws.rs.QueryParam;
jtulach@82
    53
import javax.ws.rs.WebApplicationException;
jtulach@36
    54
import javax.ws.rs.core.MediaType;
jtulach@82
    55
import javax.ws.rs.core.Response.Status;
jtulach@36
    56
jtulach@36
    57
/**
jtulach@36
    58
 *
jtulach@36
    59
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@36
    60
 */
jtulach@36
    61
public final class Games {
jtulach@82
    62
    private final Quoridor quoridor;
jaroslav@48
    63
    private final List<Game> games = new ArrayList<Game>();
jtulach@37
    64
    private final File dir;
jtulach@37
    65
    private static final Logger LOG = Logger.getLogger(Games.class.getName());
jtulach@37
    66
jtulach@82
    67
    public Games(File dir, Quoridor quoridor) {
jtulach@37
    68
        this.dir = dir;
jtulach@82
    69
        this.quoridor = quoridor;
jtulach@37
    70
        File[] arr = dir.listFiles();
jtulach@37
    71
        if (arr != null) {
jtulach@37
    72
            for (File f : arr) {
jtulach@37
    73
                try {
jtulach@37
    74
                    Game g = readGame(f);
jtulach@37
    75
                    games.add(g);
jtulach@37
    76
                } catch (IOException ex) {
jtulach@37
    77
                    LOG.log(Level.WARNING, "Wrong game in " + f, ex);
jtulach@37
    78
                }
jtulach@37
    79
            }
jtulach@37
    80
        }
jtulach@37
    81
    }
jtulach@36
    82
jtulach@36
    83
    @POST
jaroslav@48
    84
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
    85
    public GameId createGame(
jtulach@82
    86
        @QueryParam("loginID") String id,
jtulach@38
    87
        @QueryParam("white") String white,
jtulach@38
    88
        @QueryParam("black") String black
jaroslav@48
    89
    ) throws IOException {
jtulach@82
    90
        String logUser = quoridor.isLoggedIn(id);
jtulach@82
    91
        if (logUser == null) {
jtulach@82
    92
            throw new WebApplicationException(Status.UNAUTHORIZED);
jtulach@82
    93
        }
jtulach@38
    94
        if (white == null) {
jtulach@82
    95
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
jtulach@38
    96
        }
jtulach@38
    97
        if (black == null) {
jtulach@82
    98
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
jtulach@38
    99
        }
jtulach@82
   100
        if (!logUser.equals(white) && !logUser.equals(black)) {
jtulach@82
   101
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
jtulach@82
   102
        }
jtulach@82
   103
jtulach@38
   104
        Game g = new Game(white, black);
jaroslav@48
   105
        storeGame(g);
jtulach@36
   106
        games.add(g);
jaroslav@48
   107
        return g.getId();
jtulach@36
   108
    }
jtulach@36
   109
jtulach@38
   110
    @GET
jtulach@38
   111
    @Path("{id}")
jtulach@38
   112
    @Produces(MediaType.TEXT_PLAIN)
jtulach@38
   113
    public String getBoard(@PathParam("id") String id) {
jtulach@38
   114
        Game g = findGame(id);
jtulach@38
   115
        if (g == null) {
jtulach@38
   116
            throw new IllegalArgumentException("Unknown game " + id);
jtulach@38
   117
        }
jtulach@38
   118
        return g.getBoard().toString();
jtulach@38
   119
    }
jtulach@38
   120
jaroslav@46
   121
    @GET
jaroslav@46
   122
    @Path("{id}")
jaroslav@95
   123
    @Produces("image/png")
jaroslav@95
   124
    public Image getBoardImage(@PathParam("id") String id) {
jaroslav@95
   125
        Game g = findGame(id);
jaroslav@95
   126
        if (g == null) {
jaroslav@95
   127
            throw new IllegalArgumentException("Unknown game " + id);
jaroslav@95
   128
        }
jaroslav@95
   129
        return BoardImage.draw(g.getBoard());
jaroslav@95
   130
    }
jaroslav@95
   131
jaroslav@95
   132
    @GET
jaroslav@95
   133
    @Path("{id}")
jaroslav@48
   134
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
   135
    public Game getBoardInfo(@PathParam("id") String id) {
jaroslav@46
   136
        Game g = findGame(id);
jaroslav@46
   137
        if (g == null) {
jaroslav@46
   138
            throw new IllegalArgumentException("Unknown game " + id);
jaroslav@46
   139
        }
jaroslav@48
   140
        return g;
jaroslav@46
   141
    }
jaroslav@46
   142
jtulach@36
   143
    @PUT
jtulach@36
   144
    @Path("{id}")
jaroslav@48
   145
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
   146
    public GameId applyMove(
jtulach@82
   147
        @QueryParam("loginID") String loginId,
jtulach@38
   148
        @PathParam("id") String id,
jtulach@38
   149
        @QueryParam("player") String player,
jtulach@38
   150
        @QueryParam("move") String move
jtulach@38
   151
    ) throws IllegalPositionException {
jtulach@82
   152
        String logUser = quoridor.isLoggedIn(loginId);
jtulach@82
   153
        if (logUser == null) {
jtulach@82
   154
            throw new WebApplicationException(Status.UNAUTHORIZED);
jtulach@82
   155
        }
jtulach@82
   156
        if (!logUser.equals(player)) {
jtulach@82
   157
            throw new WebApplicationException(Status.UNAUTHORIZED);
jtulach@82
   158
        }
jtulach@82
   159
jtulach@36
   160
        Game g = findGame(id);
jtulach@36
   161
        if (g == null) {
jtulach@36
   162
            throw new IllegalArgumentException("Unknown game " + id);
jtulach@36
   163
        }
jtulach@36
   164
        Move m = Move.valueOf(move);
jtulach@79
   165
        g.apply(player, m, new Date());
jtulach@37
   166
        try {
jtulach@37
   167
            storeGame(g);
jtulach@37
   168
        } catch (IOException ex) {
jtulach@37
   169
            LOG.log(Level.WARNING, "Cannot store game " + id, ex);
jtulach@37
   170
        }
jaroslav@48
   171
        return g.getId();
jtulach@36
   172
    }
jtulach@36
   173
jtulach@36
   174
    @GET
jaroslav@48
   175
    @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
jaroslav@48
   176
    public List<GameId> listGames() {
jaroslav@48
   177
        List<GameId> arr = new ArrayList<GameId>(games.size());
jaroslav@48
   178
        for (Game g : games) {
jaroslav@48
   179
            arr.add(g.getId());
jaroslav@48
   180
        }
jaroslav@96
   181
        Collections.sort(arr, GameId.NEWEST_FIRST);
jaroslav@48
   182
        return arr;
jaroslav@48
   183
    }
jaroslav@48
   184
jtulach@36
   185
    public List<Game> getGames() {
jtulach@36
   186
        return games;
jtulach@36
   187
    }
jtulach@36
   188
jtulach@36
   189
    private Game findGame(String id) {
jtulach@36
   190
        for (Game g : games) {
jaroslav@48
   191
            if (g.getId().getId().equals(id)) {
jtulach@36
   192
                return g;
jtulach@36
   193
            }
jtulach@36
   194
        }
jtulach@36
   195
        return null;
jtulach@36
   196
    }
jtulach@36
   197
jtulach@37
   198
    private Game readGame(File f) throws IOException {
jtulach@37
   199
        BufferedReader r = new BufferedReader(new FileReader(f));
jtulach@37
   200
        String white = null;
jtulach@37
   201
        String black = null;
jtulach@37
   202
        Game g = null;
jtulach@37
   203
        for (;;) {
jtulach@37
   204
            String line = r.readLine();
jtulach@37
   205
            if (line == null) {
jaroslav@48
   206
                line = "finish";
jtulach@37
   207
            }
jtulach@39
   208
            line = line.trim();
jtulach@39
   209
            if (line.length() == 0) {
jtulach@39
   210
                continue;
jtulach@39
   211
            }
jtulach@37
   212
            if (line.startsWith("# white: ")) {
jtulach@37
   213
                white = line.substring(9);
jtulach@37
   214
                continue;
jtulach@37
   215
            }
jtulach@37
   216
            if (line.startsWith("# black: ")) {
jtulach@37
   217
                black = line.substring(9);
jtulach@37
   218
                continue;
jtulach@37
   219
            }
jtulach@37
   220
            if (line.startsWith("#")) {
jtulach@37
   221
                continue;
jtulach@37
   222
            }
jtulach@37
   223
            if (white == null || black == null) {
jtulach@37
   224
                throw new IOException("Missing white and black identification in " + f);
jtulach@37
   225
            }
jtulach@37
   226
            if (g == null) {
jtulach@78
   227
                GameId id = new GameId(f.getName(), white, black, new Date(f.lastModified()), new Date(f.lastModified()), GameStatus.whiteMove);
jaroslav@48
   228
                g = new Game(id);
jaroslav@48
   229
            }
jaroslav@48
   230
            if (line.equals("finish")) {
jaroslav@48
   231
                break;
jtulach@37
   232
            }
jtulach@37
   233
            String[] moves = line.split(" ");
jtulach@37
   234
            if (moves.length == 0) {
jtulach@37
   235
                continue;
jtulach@37
   236
            }
jtulach@37
   237
            if (moves.length > 2) {
jtulach@37
   238
                throw new IOException("Too much moves on line: " + line);
jtulach@37
   239
            }
jtulach@37
   240
            try {
jtulach@79
   241
                g.apply(white, Move.valueOf(moves[0]), null);
jtulach@37
   242
                if (moves.length == 2) {
jtulach@79
   243
                    g.apply(black, Move.valueOf(moves[1]), null);
jtulach@37
   244
                }
jtulach@37
   245
            } catch (IllegalPositionException ex) {
jtulach@37
   246
                throw new IOException("Wrong move: " + ex.getMessage());
jtulach@37
   247
            }
jtulach@37
   248
        }
jtulach@37
   249
        if (g == null) {
jtulach@37
   250
            throw new IOException("No moves in " + f);
jtulach@37
   251
        }
jtulach@37
   252
        return g;
jtulach@36
   253
    }
jtulach@36
   254
jtulach@37
   255
    private void storeGame(Game g) throws IOException {
jtulach@37
   256
        dir.mkdirs();
jaroslav@48
   257
        File f = new File(dir, g.getId().getId());
jtulach@37
   258
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
jaroslav@48
   259
        pw.println("# white: " + g.getId().getWhite());
jaroslav@48
   260
        pw.println("# black: " + g.getId().getBlack());
jtulach@77
   261
        pw.println("# status: " + g.getId().getStatus());
jtulach@37
   262
        int cnt = 0;
jtulach@37
   263
        for (Move m : g.getMoves()) {
jtulach@37
   264
            pw.print(m.toString());
jtulach@37
   265
            if (++cnt % 2 == 0) {
jtulach@37
   266
                pw.println();
jtulach@37
   267
            } else {
jtulach@37
   268
                pw.print(' ');
jtulach@37
   269
            }
jtulach@37
   270
        }
jtulach@37
   271
        pw.println();
jtulach@37
   272
        pw.println();
jtulach@37
   273
        pw.flush();
jtulach@37
   274
        pw.close();
jtulach@37
   275
    }
jtulach@36
   276
}