freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 04 Sep 2009 20:26:48 +0200
changeset 56 7c3794f5baa1
parent 55 830e0ba29c04
child 57 fa12b02023a0
permissions -rw-r--r--
Reload of the game page, warning messages, listing just game in progress
     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.freemarkerdor;
    28 
    29 import com.sun.jersey.api.client.Client;
    30 import com.sun.jersey.api.client.UniformInterfaceException;
    31 import com.sun.jersey.api.client.WebResource;
    32 import com.sun.jersey.api.container.httpserver.HttpServerFactory;
    33 import com.sun.jersey.api.core.PackagesResourceConfig;
    34 import com.sun.jersey.api.core.ResourceConfig;
    35 import com.sun.jersey.api.view.Viewable;
    36 import com.sun.net.httpserver.HttpServer;
    37 import cz.xelfi.quoridor.webidor.resources.Quoridor;
    38 import java.io.File;
    39 import java.io.FileInputStream;
    40 import java.io.IOException;
    41 import java.net.URI;
    42 import java.util.HashMap;
    43 import java.util.Map;
    44 import java.util.Properties;
    45 import java.util.concurrent.Callable;
    46 import javax.ws.rs.DefaultValue;
    47 import javax.ws.rs.FormParam;
    48 import javax.ws.rs.GET;
    49 import javax.ws.rs.POST;
    50 import javax.ws.rs.Path;
    51 import javax.ws.rs.PathParam;
    52 import javax.ws.rs.Produces;
    53 import javax.ws.rs.QueryParam;
    54 import javax.ws.rs.core.Context;
    55 import javax.ws.rs.core.HttpHeaders;
    56 import javax.ws.rs.core.MediaType;
    57 import javax.ws.rs.core.NewCookie;
    58 import javax.ws.rs.core.Response;
    59 import org.w3c.dom.Document;
    60 
    61 /**
    62  *
    63  * @author Jaroslav Tulach <jtulach@netbeans.org>
    64  */
    65 @Path("/")
    66 public final class UI {
    67     private static WebResource base;
    68 
    69     @Context
    70     private HttpHeaders headers;
    71     private String user;
    72 
    73     public UI() {
    74     }
    75 
    76     private Viewable checkLogin() {
    77         if (headers.getCookies().containsKey("login")) {
    78             user = headers.getCookies().get("login").getValue();
    79             return null;
    80         }
    81         return viewable("login.fmt", null);
    82     }
    83 
    84     @POST
    85     @Path("login")
    86     @Produces(MediaType.TEXT_HTML)
    87     public Response login(
    88         @FormParam("name") String name, @FormParam("password") String password
    89     ) throws Exception {
    90         File f = new File(new File(new File(System.getProperty("user.home")), ".quoridor"), "passwd");
    91         Properties p = new Properties();
    92         try {
    93             p.load(new FileInputStream(f));
    94         } catch (IOException ex) {
    95             ex.printStackTrace();
    96         }
    97         if (name != null && password.equals(p.getProperty(name))) {
    98             return Response.seeOther(new URI("/")).cookie(new NewCookie("login", name)).entity(welcomeImpl()).build();
    99         } else {
   100             Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
   101             return Response.status(1).entity(v).build();
   102         }
   103     }
   104 
   105     @GET
   106     @Produces(MediaType.TEXT_HTML)
   107     public Viewable welcome() {
   108         Viewable v = checkLogin();
   109         if (v != null) {
   110             return v;
   111         }
   112         return welcomeImpl();
   113     }
   114 
   115     @GET
   116     @Path("games/{id}/")
   117     @Produces(MediaType.TEXT_HTML)
   118     public Viewable board(@PathParam("id") String id) {
   119         return board(id, null);
   120     }
   121     private Viewable board(@PathParam("id") String id, String msg) {
   122         Viewable v = checkLogin();
   123         if (v != null) {
   124             return v;
   125         }
   126         Document doc = base.path("games").path(id).accept(MediaType.TEXT_XML).get(Document.class);
   127         return viewable("game.fmt", doc, "message", msg);
   128     }
   129 
   130     @GET
   131     @Path("games/{id}/move")
   132     @Produces(MediaType.TEXT_HTML)
   133     public Viewable move(
   134         @PathParam("id") String id,
   135         @QueryParam("type") String type,
   136         @QueryParam("direction") String direction,
   137         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   138         @QueryParam("column") @DefaultValue("") String column,
   139         @QueryParam("row") @DefaultValue("") String row
   140     ) {
   141         Viewable v = checkLogin();
   142         if (v != null) {
   143             return v;
   144         }
   145         WebResource wr = base.path("games").path(id).queryParam("player", user);
   146         try {
   147             if (type.equals("fence")) {
   148                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   149                 return board(id);
   150             }
   151             if (type.equals("move")) {
   152                 wr.queryParam("move", direction + directionNext).put();
   153                 return board(id);
   154             }
   155         } catch (UniformInterfaceException ex) {
   156             return board(id, "WRONG_MOVE");
   157         }
   158         return board(id);
   159     }
   160 
   161     @GET
   162     @Path("games/create")
   163     @Produces(MediaType.TEXT_HTML)
   164     public Viewable create(
   165         @QueryParam("white") String white,
   166         @QueryParam("black") String black
   167     ) {
   168         Viewable v = checkLogin();
   169         if (v != null) {
   170             return v;
   171         }
   172         Object obj =
   173             base.path("games").queryParam("white", white).
   174             queryParam("black", black).post(Document.class);
   175         return welcome();
   176     }
   177 
   178     private Viewable welcomeImpl() {
   179         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   180         return viewable("index.fmt", got);
   181     }
   182 
   183     //
   184     // start the server
   185     //
   186 
   187     public static void main(String[] args) throws Exception {
   188         Callable<Void> r = startServers();
   189 
   190         System.in.read();
   191         r.call();
   192         System.exit(0);
   193     }
   194 
   195     static Callable<Void> startServers() throws Exception {
   196         final HttpServer api = Quoridor.start(9998);
   197         Client client = new Client();
   198         base = client.resource(new URI("http://localhost:9998/api/"));
   199 
   200         final HttpServer s = start(9997);
   201         System.out.println(
   202             "Quoridor started at port 9997\n" + "Hit enter to stop it..."
   203         );
   204 
   205         return new Callable<Void>() {
   206             public Void call() throws Exception {
   207                 s.stop(0);
   208                 api.stop(0);
   209                 return null;
   210             }
   211         };
   212     }
   213 
   214     static HttpServer start(int port) throws IOException {
   215         final String baseUri = "http://localhost:" + port + "/";
   216         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
   217         HttpServer server = HttpServerFactory.create(baseUri, rc);
   218         server.start();
   219         return server;
   220     }
   221 
   222     private Viewable viewable(String page, Document doc, Object... more) {
   223         Map<String,Object> map = new HashMap<String,Object>();
   224         map.put("doc", doc);
   225         map.put("user", user);
   226         for (int i = 0; i < more.length; i += 2) {
   227             map.put((String)more[i],more[i + 1]);
   228         }
   229         return new Viewable(page, map);
   230     }
   231 
   232 }