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