webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Games.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 16 Sep 2009 22:28:11 +0200
branchdisplay-image
changeset 91 786df32c496b
parent 82 9ac7acee7d9f
permissions -rw-r--r--
First attempt to show 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;
jtulach@91
    32
import cz.xelfi.quoridor.visidor.Visidor;
jtulach@91
    33
import java.awt.Image;
jtulach@37
    34
import java.io.BufferedReader;
jtulach@37
    35
import java.io.BufferedWriter;
jtulach@37
    36
import java.io.File;
jtulach@37
    37
import java.io.FileReader;
jtulach@37
    38
import java.io.FileWriter;
jtulach@36
    39
import java.io.IOException;
jtulach@37
    40
import java.io.PrintWriter;
jtulach@36
    41
import java.util.ArrayList;
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}")
jtulach@91
   123
    @Produces("image/png")
jtulach@91
   124
    public Image getBoardImage(@PathParam("id") String id) {
jtulach@91
   125
        Game g = findGame(id);
jtulach@91
   126
        if (g == null) {
jtulach@91
   127
            throw new IllegalArgumentException("Unknown game " + id);
jtulach@91
   128
        }
jtulach@91
   129
        return Visidor.draw(g.getBoard());
jtulach@91
   130
    }
jtulach@91
   131
jtulach@91
   132
    @GET
jtulach@91
   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@48
   181
        return arr;
jaroslav@48
   182
    }
jaroslav@48
   183
jtulach@36
   184
    public List<Game> getGames() {
jtulach@36
   185
        return games;
jtulach@36
   186
    }
jtulach@36
   187
jtulach@36
   188
    private Game findGame(String id) {
jtulach@36
   189
        for (Game g : games) {
jaroslav@48
   190
            if (g.getId().getId().equals(id)) {
jtulach@36
   191
                return g;
jtulach@36
   192
            }
jtulach@36
   193
        }
jtulach@36
   194
        return null;
jtulach@36
   195
    }
jtulach@36
   196
jtulach@37
   197
    private Game readGame(File f) throws IOException {
jtulach@37
   198
        BufferedReader r = new BufferedReader(new FileReader(f));
jtulach@37
   199
        String white = null;
jtulach@37
   200
        String black = null;
jtulach@37
   201
        Game g = null;
jtulach@37
   202
        for (;;) {
jtulach@37
   203
            String line = r.readLine();
jtulach@37
   204
            if (line == null) {
jaroslav@48
   205
                line = "finish";
jtulach@37
   206
            }
jtulach@39
   207
            line = line.trim();
jtulach@39
   208
            if (line.length() == 0) {
jtulach@39
   209
                continue;
jtulach@39
   210
            }
jtulach@37
   211
            if (line.startsWith("# white: ")) {
jtulach@37
   212
                white = line.substring(9);
jtulach@37
   213
                continue;
jtulach@37
   214
            }
jtulach@37
   215
            if (line.startsWith("# black: ")) {
jtulach@37
   216
                black = line.substring(9);
jtulach@37
   217
                continue;
jtulach@37
   218
            }
jtulach@37
   219
            if (line.startsWith("#")) {
jtulach@37
   220
                continue;
jtulach@37
   221
            }
jtulach@37
   222
            if (white == null || black == null) {
jtulach@37
   223
                throw new IOException("Missing white and black identification in " + f);
jtulach@37
   224
            }
jtulach@37
   225
            if (g == null) {
jtulach@78
   226
                GameId id = new GameId(f.getName(), white, black, new Date(f.lastModified()), new Date(f.lastModified()), GameStatus.whiteMove);
jaroslav@48
   227
                g = new Game(id);
jaroslav@48
   228
            }
jaroslav@48
   229
            if (line.equals("finish")) {
jaroslav@48
   230
                break;
jtulach@37
   231
            }
jtulach@37
   232
            String[] moves = line.split(" ");
jtulach@37
   233
            if (moves.length == 0) {
jtulach@37
   234
                continue;
jtulach@37
   235
            }
jtulach@37
   236
            if (moves.length > 2) {
jtulach@37
   237
                throw new IOException("Too much moves on line: " + line);
jtulach@37
   238
            }
jtulach@37
   239
            try {
jtulach@79
   240
                g.apply(white, Move.valueOf(moves[0]), null);
jtulach@37
   241
                if (moves.length == 2) {
jtulach@79
   242
                    g.apply(black, Move.valueOf(moves[1]), null);
jtulach@37
   243
                }
jtulach@37
   244
            } catch (IllegalPositionException ex) {
jtulach@37
   245
                throw new IOException("Wrong move: " + ex.getMessage());
jtulach@37
   246
            }
jtulach@37
   247
        }
jtulach@37
   248
        if (g == null) {
jtulach@37
   249
            throw new IOException("No moves in " + f);
jtulach@37
   250
        }
jtulach@37
   251
        return g;
jtulach@36
   252
    }
jtulach@36
   253
jtulach@37
   254
    private void storeGame(Game g) throws IOException {
jtulach@37
   255
        dir.mkdirs();
jaroslav@48
   256
        File f = new File(dir, g.getId().getId());
jtulach@37
   257
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
jaroslav@48
   258
        pw.println("# white: " + g.getId().getWhite());
jaroslav@48
   259
        pw.println("# black: " + g.getId().getBlack());
jtulach@77
   260
        pw.println("# status: " + g.getId().getStatus());
jtulach@37
   261
        int cnt = 0;
jtulach@37
   262
        for (Move m : g.getMoves()) {
jtulach@37
   263
            pw.print(m.toString());
jtulach@37
   264
            if (++cnt % 2 == 0) {
jtulach@37
   265
                pw.println();
jtulach@37
   266
            } else {
jtulach@37
   267
                pw.print(' ');
jtulach@37
   268
            }
jtulach@37
   269
        }
jtulach@37
   270
        pw.println();
jtulach@37
   271
        pw.println();
jtulach@37
   272
        pw.flush();
jtulach@37
   273
        pw.close();
jtulach@37
   274
    }
jtulach@36
   275
}