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