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