webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Games.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 29 Jul 2009 18:48:04 +0200
changeset 39 6b889f2717e9
parent 38 373f537e0153
child 46 71e4cf307c93
permissions -rw-r--r--
Ability to read stored games
     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.Arrays;
    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 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)
    79     public Game createGame(
    80         @QueryParam("white") String white,
    81         @QueryParam("black") String black
    82     ) {
    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         games.add(g);
    91         return g;
    92     }
    93 
    94     @GET
    95     @Path("{id}")
    96     @Produces(MediaType.TEXT_PLAIN)
    97     public String getBoard(@PathParam("id") String id) {
    98         Game g = findGame(id);
    99         if (g == null) {
   100             throw new IllegalArgumentException("Unknown game " + id);
   101         }
   102         return g.getBoard().toString();
   103     }
   104 
   105     @PUT
   106     @Path("{id}")
   107     @Produces(MediaType.APPLICATION_JSON)
   108     public Game applyMove(
   109         @PathParam("id") String id,
   110         @QueryParam("player") String player,
   111         @QueryParam("move") String move
   112     ) throws IllegalPositionException {
   113         Game g = findGame(id);
   114         if (g == null) {
   115             throw new IllegalArgumentException("Unknown game " + id);
   116         }
   117         Move m = Move.valueOf(move);
   118         g.apply(player, m);
   119         try {
   120             storeGame(g);
   121         } catch (IOException ex) {
   122             LOG.log(Level.WARNING, "Cannot store game " + id, ex);
   123         }
   124         return g;
   125     }
   126 
   127     @GET
   128     @Produces(MediaType.APPLICATION_JSON)
   129     public List<Game> getGames() {
   130         return games;
   131     }
   132 
   133     private Game findGame(String id) {
   134         for (Game g : games) {
   135             if (g.getId().equals(id)) {
   136                 return g;
   137             }
   138         }
   139         return null;
   140     }
   141 
   142     private Game readGame(File f) throws IOException {
   143         BufferedReader r = new BufferedReader(new FileReader(f));
   144         String white = null;
   145         String black = null;
   146         Game g = null;
   147         for (;;) {
   148             String line = r.readLine();
   149             if (line == null) {
   150                 break;
   151             }
   152             line = line.trim();
   153             if (line.length() == 0) {
   154                 continue;
   155             }
   156             if (line.startsWith("# white: ")) {
   157                 white = line.substring(9);
   158                 continue;
   159             }
   160             if (line.startsWith("# black: ")) {
   161                 black = line.substring(9);
   162                 continue;
   163             }
   164             if (line.startsWith("#")) {
   165                 continue;
   166             }
   167             if (white == null || black == null) {
   168                 throw new IOException("Missing white and black identification in " + f);
   169             }
   170             if (g == null) {
   171                 g = new Game(f.getName(), white, black);
   172             }
   173             String[] moves = line.split(" ");
   174             if (moves.length == 0) {
   175                 continue;
   176             }
   177             if (moves.length > 2) {
   178                 throw new IOException("Too much moves on line: " + line);
   179             }
   180             try {
   181                 g.apply(white, Move.valueOf(moves[0]));
   182                 if (moves.length == 2) {
   183                     g.apply(black, Move.valueOf(moves[1]));
   184                 }
   185             } catch (IllegalPositionException ex) {
   186                 throw new IOException("Wrong move: " + ex.getMessage());
   187             }
   188         }
   189         if (g == null) {
   190             throw new IOException("No moves in " + f);
   191         }
   192         return g;
   193     }
   194 
   195     private void storeGame(Game g) throws IOException {
   196         dir.mkdirs();
   197         File f = new File(dir, g.getId());
   198         PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
   199         pw.println("# white: " + g.getWhite());
   200         pw.println("# black: " + g.getBlack());
   201         int cnt = 0;
   202         for (Move m : g.getMoves()) {
   203             pw.print(m.toString());
   204             if (++cnt % 2 == 0) {
   205                 pw.println();
   206             } else {
   207                 pw.print(' ');
   208             }
   209         }
   210         pw.println();
   211         pw.println();
   212         pw.flush();
   213         pw.close();
   214     }
   215 }