webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Games.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 29 Jul 2009 17:24:20 +0200
changeset 38 373f537e0153
parent 37 782d925cb5a1
child 39 6b889f2717e9
permissions -rw-r--r--
It is possible to play the game from command line with curl
     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.List;
    41 import java.util.logging.Level;
    42 import java.util.logging.Logger;
    43 import javax.ws.rs.GET;
    44 import javax.ws.rs.POST;
    45 import javax.ws.rs.PUT;
    46 import javax.ws.rs.Path;
    47 import javax.ws.rs.PathParam;
    48 import javax.ws.rs.Produces;
    49 import javax.ws.rs.QueryParam;
    50 import javax.ws.rs.core.MediaType;
    51 
    52 /**
    53  *
    54  * @author Jaroslav Tulach <jtulach@netbeans.org>
    55  */
    56 public final class Games {
    57     private List<Game> games = new ArrayList<Game>();
    58     private final File dir;
    59     private static final Logger LOG = Logger.getLogger(Games.class.getName());
    60 
    61     public Games(File dir) {
    62         this.dir = dir;
    63         File[] arr = dir.listFiles();
    64         if (arr != null) {
    65             for (File f : arr) {
    66                 try {
    67                     Game g = readGame(f);
    68                     games.add(g);
    69                 } catch (IOException ex) {
    70                     LOG.log(Level.WARNING, "Wrong game in " + f, ex);
    71                 }
    72             }
    73         }
    74     }
    75 
    76     @POST
    77     @Produces(MediaType.APPLICATION_JSON)
    78     public Game createGame(
    79         @QueryParam("white") String white,
    80         @QueryParam("black") String black
    81     ) {
    82         if (white == null) {
    83             throw new IllegalArgumentException("Must specify white");
    84         }
    85         if (black == null) {
    86             throw new IllegalArgumentException("Must specify black");
    87         }
    88         Game g = new Game(white, black);
    89         games.add(g);
    90         return g;
    91     }
    92 
    93     @GET
    94     @Path("{id}")
    95     @Produces(MediaType.TEXT_PLAIN)
    96     public String getBoard(@PathParam("id") String id) {
    97         Game g = findGame(id);
    98         if (g == null) {
    99             throw new IllegalArgumentException("Unknown game " + id);
   100         }
   101         return g.getBoard().toString();
   102     }
   103 
   104     @PUT
   105     @Path("{id}")
   106     @Produces(MediaType.APPLICATION_JSON)
   107     public Game applyMove(
   108         @PathParam("id") String id,
   109         @QueryParam("player") String player,
   110         @QueryParam("move") String move
   111     ) throws IllegalPositionException {
   112         Game g = findGame(id);
   113         if (g == null) {
   114             throw new IllegalArgumentException("Unknown game " + id);
   115         }
   116         Move m = Move.valueOf(move);
   117         g.apply(player, m);
   118         try {
   119             storeGame(g);
   120         } catch (IOException ex) {
   121             LOG.log(Level.WARNING, "Cannot store game " + id, ex);
   122         }
   123         return g;
   124     }
   125 
   126     @GET
   127     @Produces(MediaType.APPLICATION_JSON)
   128     public List<Game> getGames() {
   129         return games;
   130     }
   131 
   132     private Game findGame(String id) {
   133         for (Game g : games) {
   134             if (g.getId().equals(id)) {
   135                 return g;
   136             }
   137         }
   138         return null;
   139     }
   140 
   141     private Game readGame(File f) throws IOException {
   142         BufferedReader r = new BufferedReader(new FileReader(f));
   143         String white = null;
   144         String black = null;
   145         Game g = null;
   146         for (;;) {
   147             String line = r.readLine();
   148             if (line == null) {
   149                 break;
   150             }
   151             if (line.startsWith("# white: ")) {
   152                 white = line.substring(9);
   153                 continue;
   154             }
   155             if (line.startsWith("# black: ")) {
   156                 black = line.substring(9);
   157                 continue;
   158             }
   159             if (line.startsWith("#")) {
   160                 continue;
   161             }
   162             if (white == null || black == null) {
   163                 throw new IOException("Missing white and black identification in " + f);
   164             }
   165             if (g == null) {
   166                 g = new Game(f.getName(), white, black);
   167             }
   168             String[] moves = line.split(" ");
   169             if (moves.length == 0) {
   170                 continue;
   171             }
   172             if (moves.length > 2) {
   173                 throw new IOException("Too much moves on line: " + line);
   174             }
   175             try {
   176                 g.apply(white, Move.valueOf(moves[0]));
   177                 if (moves.length == 2) {
   178                     g.apply(black, Move.valueOf(moves[1]));
   179                 }
   180             } catch (IllegalPositionException ex) {
   181                 throw new IOException("Wrong move: " + ex.getMessage());
   182             }
   183         }
   184         if (g == null) {
   185             throw new IOException("No moves in " + f);
   186         }
   187         return g;
   188     }
   189 
   190     private void storeGame(Game g) throws IOException {
   191         dir.mkdirs();
   192         File f = new File(dir, g.getId());
   193         PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
   194         pw.println("# white: " + g.getWhite());
   195         pw.println("# black: " + g.getBlack());
   196         int cnt = 0;
   197         for (Move m : g.getMoves()) {
   198             pw.print(m.toString());
   199             if (++cnt % 2 == 0) {
   200                 pw.println();
   201             } else {
   202                 pw.print(' ');
   203             }
   204         }
   205         pw.println();
   206         pw.println();
   207         pw.flush();
   208         pw.close();
   209     }
   210 }