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