webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Games.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 30 Aug 2009 14:37:47 +0200
changeset 48 69e897fe8140
parent 46 71e4cf307c93
child 77 d574ac6e44cc
permissions -rw-r--r--
Spliting Game into GameId and Game with full info about the state of the game
     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * The contents of this file are subject to the terms of either the GNU
     5  * General Public License Version 2 only ("GPL") or the Common
     6  * Development and Distribution License("CDDL") (collectively, the
     7  * "License"). You may not use this file except in compliance with the
     8  * License. You can obtain a copy of the License at
     9  * http://www.netbeans.org/cddl-gplv2.html
    10  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    11  * specific language governing permissions and limitations under the
    12  * License.  When distributing the software, include this License Header
    13  * Notice in each file and include the License file at
    14  * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
    15  * particular file as subject to the "Classpath" exception as provided
    16  * by Sun in the GPL Version 2 section of the License file that
    17  * accompanied this code. If applicable, add the following below the
    18  * License Header, with the fields enclosed by brackets [] replaced by
    19  * your own identifying information:
    20  * "Portions Copyrighted [year] [name of copyright owner]"
    21  *
    22  * Contributor(s):
    23  *
    24  * Portions Copyrighted 2009 Jaroslav Tulach
    25  */
    26 
    27 package cz.xelfi.quoridor.webidor.resources;
    28 
    29 import cz.xelfi.quoridor.IllegalPositionException;
    30 import cz.xelfi.quoridor.webidor.*;
    31 import cz.xelfi.quoridor.Move;
    32 import java.io.BufferedReader;
    33 import java.io.BufferedWriter;
    34 import java.io.File;
    35 import java.io.FileReader;
    36 import java.io.FileWriter;
    37 import java.io.IOException;
    38 import java.io.PrintWriter;
    39 import java.util.ArrayList;
    40 import java.util.Date;
    41 import java.util.List;
    42 import java.util.logging.Level;
    43 import java.util.logging.Logger;
    44 import javax.ws.rs.GET;
    45 import javax.ws.rs.POST;
    46 import javax.ws.rs.PUT;
    47 import javax.ws.rs.Path;
    48 import javax.ws.rs.PathParam;
    49 import javax.ws.rs.Produces;
    50 import javax.ws.rs.QueryParam;
    51 import javax.ws.rs.core.MediaType;
    52 
    53 /**
    54  *
    55  * @author Jaroslav Tulach <jtulach@netbeans.org>
    56  */
    57 public final class Games {
    58     private final List<Game> games = new ArrayList<Game>();
    59     private final File dir;
    60     private static final Logger LOG = Logger.getLogger(Games.class.getName());
    61 
    62     public Games(File dir) {
    63         this.dir = dir;
    64         File[] arr = dir.listFiles();
    65         if (arr != null) {
    66             for (File f : arr) {
    67                 try {
    68                     Game g = readGame(f);
    69                     games.add(g);
    70                 } catch (IOException ex) {
    71                     LOG.log(Level.WARNING, "Wrong game in " + f, ex);
    72                 }
    73             }
    74         }
    75     }
    76 
    77     @POST
    78     @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
    79     public GameId createGame(
    80         @QueryParam("white") String white,
    81         @QueryParam("black") String black
    82     ) throws IOException {
    83         if (white == null) {
    84             throw new IllegalArgumentException("Must specify white");
    85         }
    86         if (black == null) {
    87             throw new IllegalArgumentException("Must specify black");
    88         }
    89         Game g = new Game(white, black);
    90         storeGame(g);
    91         games.add(g);
    92         return g.getId();
    93     }
    94 
    95     @GET
    96     @Path("{id}")
    97     @Produces(MediaType.TEXT_PLAIN)
    98     public String getBoard(@PathParam("id") String id) {
    99         Game g = findGame(id);
   100         if (g == null) {
   101             throw new IllegalArgumentException("Unknown game " + id);
   102         }
   103         return g.getBoard().toString();
   104     }
   105 
   106     @GET
   107     @Path("{id}")
   108     @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
   109     public Game getBoardInfo(@PathParam("id") String id) {
   110         Game g = findGame(id);
   111         if (g == null) {
   112             throw new IllegalArgumentException("Unknown game " + id);
   113         }
   114         return g;
   115     }
   116 
   117     @PUT
   118     @Path("{id}")
   119     @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
   120     public GameId applyMove(
   121         @PathParam("id") String id,
   122         @QueryParam("player") String player,
   123         @QueryParam("move") String move
   124     ) throws IllegalPositionException {
   125         Game g = findGame(id);
   126         if (g == null) {
   127             throw new IllegalArgumentException("Unknown game " + id);
   128         }
   129         Move m = Move.valueOf(move);
   130         g.apply(player, m);
   131         try {
   132             storeGame(g);
   133         } catch (IOException ex) {
   134             LOG.log(Level.WARNING, "Cannot store game " + id, ex);
   135         }
   136         return g.getId();
   137     }
   138 
   139     @GET
   140     @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
   141     public List<GameId> listGames() {
   142         List<GameId> arr = new ArrayList<GameId>(games.size());
   143         for (Game g : games) {
   144             arr.add(g.getId());
   145         }
   146         return arr;
   147     }
   148 
   149     public List<Game> getGames() {
   150         return games;
   151     }
   152 
   153     private Game findGame(String id) {
   154         for (Game g : games) {
   155             if (g.getId().getId().equals(id)) {
   156                 return g;
   157             }
   158         }
   159         return null;
   160     }
   161 
   162     private Game readGame(File f) throws IOException {
   163         BufferedReader r = new BufferedReader(new FileReader(f));
   164         String white = null;
   165         String black = null;
   166         Game g = null;
   167         for (;;) {
   168             String line = r.readLine();
   169             if (line == null) {
   170                 line = "finish";
   171             }
   172             line = line.trim();
   173             if (line.length() == 0) {
   174                 continue;
   175             }
   176             if (line.startsWith("# white: ")) {
   177                 white = line.substring(9);
   178                 continue;
   179             }
   180             if (line.startsWith("# black: ")) {
   181                 black = line.substring(9);
   182                 continue;
   183             }
   184             if (line.startsWith("#")) {
   185                 continue;
   186             }
   187             if (white == null || black == null) {
   188                 throw new IOException("Missing white and black identification in " + f);
   189             }
   190             if (g == null) {
   191                 GameId id = new GameId(f.getName(), white, black, new Date(f.lastModified()), GameResult.IN_PROGRESS);
   192                 g = new Game(id);
   193             }
   194             if (line.equals("finish")) {
   195                 break;
   196             }
   197             String[] moves = line.split(" ");
   198             if (moves.length == 0) {
   199                 continue;
   200             }
   201             if (moves.length > 2) {
   202                 throw new IOException("Too much moves on line: " + line);
   203             }
   204             try {
   205                 g.apply(white, Move.valueOf(moves[0]));
   206                 if (moves.length == 2) {
   207                     g.apply(black, Move.valueOf(moves[1]));
   208                 }
   209             } catch (IllegalPositionException ex) {
   210                 throw new IOException("Wrong move: " + ex.getMessage());
   211             }
   212         }
   213         if (g == null) {
   214             throw new IOException("No moves in " + f);
   215         }
   216         return g;
   217     }
   218 
   219     private void storeGame(Game g) throws IOException {
   220         dir.mkdirs();
   221         File f = new File(dir, g.getId().getId());
   222         PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
   223         pw.println("# white: " + g.getId().getWhite());
   224         pw.println("# black: " + g.getId().getBlack());
   225         pw.println("# status: " + g.getId().getResult());
   226         int cnt = 0;
   227         for (Move m : g.getMoves()) {
   228             pw.print(m.toString());
   229             if (++cnt % 2 == 0) {
   230                 pw.println();
   231             } else {
   232                 pw.print(' ');
   233             }
   234         }
   235         pw.println();
   236         pw.println();
   237         pw.flush();
   238         pw.close();
   239     }
   240 }