freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sun, 13 Sep 2009 20:07:32 +0200
changeset 83 8dd8b041a3e1
parent 82 9ac7acee7d9f
child 85 3574b08dc3c3
permissions -rw-r--r--
Necessary fixes to make the system work at least a bit
     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 java.io.File;
    38 import java.net.URI;
    39 import java.util.HashMap;
    40 import java.util.Locale;
    41 import java.util.Map;
    42 import java.util.MissingResourceException;
    43 import java.util.ResourceBundle;
    44 import java.util.concurrent.Callable;
    45 import javax.ws.rs.DefaultValue;
    46 import javax.ws.rs.FormParam;
    47 import javax.ws.rs.GET;
    48 import javax.ws.rs.POST;
    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.core.Context;
    54 import javax.ws.rs.core.HttpHeaders;
    55 import javax.ws.rs.core.MediaType;
    56 import javax.ws.rs.core.NewCookie;
    57 import javax.ws.rs.core.Response;
    58 import org.w3c.dom.Document;
    59 
    60 /**
    61  *
    62  * @author Jaroslav Tulach <jtulach@netbeans.org>
    63  */
    64 @Path("/")
    65 public final class UI {
    66     private static WebResource base;
    67 
    68     @Context
    69     private HttpHeaders headers;
    70     private String user;
    71     private String uuid;
    72 
    73     public UI() {
    74     }
    75 
    76     private Viewable checkLogin() {
    77         if (headers.getCookies().containsKey("login")) {
    78             String id = headers.getCookies().get("login").getValue();
    79             String us = base.path("login").queryParam("id", id).
    80                 accept(MediaType.TEXT_PLAIN).get(String.class);
    81             if (us.length() > 0) {
    82                 user = us;
    83                 uuid = id;
    84                 return null;
    85             }
    86         }
    87         return viewable("login.fmt", null);
    88     }
    89 
    90     @POST
    91     @Path("login")
    92     @Produces(MediaType.TEXT_HTML)
    93     public Response login(
    94         @FormParam("name") String name, @FormParam("password") String password
    95     ) throws Exception {
    96         uuid = base.path("login").queryParam("name", name).queryParam("password", password).
    97             accept(MediaType.TEXT_PLAIN).put(String.class);
    98         if (uuid != null) {
    99             user = name;
   100             return Response.ok().cookie(new NewCookie("login", uuid)).entity(viewable("login.fmt", null)).build();
   101         } else {
   102             Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
   103             return Response.status(1).entity(v).build();
   104         }
   105     }
   106 
   107     @GET
   108     @Produces(MediaType.TEXT_HTML)
   109     public Viewable welcome() {
   110         Viewable v = checkLogin();
   111         if (v != null) {
   112             return v;
   113         }
   114         return welcomeImpl();
   115     }
   116 
   117     @GET
   118     @Path("games/{id}/")
   119     @Produces(MediaType.TEXT_HTML)
   120     public Viewable board(@PathParam("id") String id) {
   121         return board(id, null);
   122     }
   123     private Viewable board(@PathParam("id") String id, String msg) {
   124         Viewable v = checkLogin();
   125         if (v != null) {
   126             return v;
   127         }
   128         Document doc = base.path("games").path(id).accept(MediaType.TEXT_XML).get(Document.class);
   129         return viewable("game.fmt", doc, "message", msg);
   130     }
   131 
   132     @GET
   133     @Path("games/{id}/move")
   134     @Produces(MediaType.TEXT_HTML)
   135     public Viewable move(
   136         @PathParam("id") String id,
   137         @QueryParam("type") String type,
   138         @QueryParam("direction") String direction,
   139         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   140         @QueryParam("column") @DefaultValue("") String column,
   141         @QueryParam("row") @DefaultValue("") String row
   142     ) {
   143         Viewable v = checkLogin();
   144         if (v != null) {
   145             return v;
   146         }
   147         WebResource wr = base.path("games").path(id).
   148             queryParam("loginID", uuid).
   149             queryParam("player", user);
   150         try {
   151             if (type.equals("resign")) {
   152                 wr.queryParam("move", "RESIGN").put();
   153                 return board(id);
   154             }
   155             if (type.equals("fence")) {
   156                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   157                 return board(id);
   158             }
   159             if (type.equals("move")) {
   160                 wr.queryParam("move", direction + directionNext).put();
   161                 return board(id);
   162             }
   163         } catch (UniformInterfaceException ex) {
   164             return board(id, "WRONG_MOVE");
   165         }
   166         return board(id);
   167     }
   168 
   169     @GET
   170     @Path("games/create")
   171     @Produces(MediaType.TEXT_HTML)
   172     public Response create(
   173         @QueryParam("white") String white,
   174         @QueryParam("black") String black
   175     ) {
   176         Viewable v = checkLogin();
   177         if (v != null) {
   178             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   179         }
   180 
   181         if (user.equals(white) || user.equals(black)) {
   182             Object obj =
   183                 base.path("games").
   184                 queryParam("loginID", uuid).
   185                 queryParam("white", white).
   186                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   187             return Response.ok(welcomeImpl()).build();
   188         } else {
   189             return Response.status(Response.Status.NOT_FOUND).
   190                 entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
   191         }
   192     }
   193 
   194     private Viewable welcomeImpl(Object... args) {
   195         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   196         return viewable("index.fmt", got, args);
   197     }
   198 
   199     //
   200     // start the server
   201     //
   202 
   203     public static void main(String[] args) throws Exception {
   204         int port = 9998;
   205         if (args.length > 1) {
   206             port = Integer.parseInt(args[0]);
   207         }
   208 
   209 
   210         Callable<Void> r = startServers(port);
   211 
   212         if (args.length > 2 && args[1].equals("--kill")) {
   213             System.out.println("Hit enter to stop it...");
   214             System.in.read();
   215         } else {
   216             synchronized (UI.class) {
   217                 UI.class.wait();
   218             }
   219         }
   220         r.call();
   221         System.exit(0);
   222     }
   223 
   224     static Callable<Void> startServers(int port) throws Exception {
   225 
   226         if (System.getProperty("quoridor.dir") == null) {
   227             File home = new File(System.getProperty("user.home"));
   228             File quoridor = new File(home, ".quoridor");
   229             System.setProperty("quoridor.dir", quoridor.getPath());
   230         }
   231 
   232         ResourceConfig rc = new PackagesResourceConfig(
   233             "cz.xelfi.quoridor.webidor",
   234             "cz.xelfi.quoridor.freemarkerdor"
   235         );
   236 
   237         Client client = new Client();
   238         base = client.resource(new URI("http://localhost:" + port + "/api/"));
   239 
   240         final String baseUri = "http://localhost:" + port + "/";
   241         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   242         server.start();
   243         System.out.println("Quoridor started at port " + port);
   244 
   245         return new Callable<Void>() {
   246             public Void call() throws Exception {
   247                 server.stop(0);
   248                 return null;
   249             }
   250         };
   251     }
   252 
   253     private Viewable viewable(String page, Document doc, Object... more) {
   254         ResourceBundle rb = null;
   255         for (Locale l : headers.getAcceptableLanguages()) {
   256             try {
   257                 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   258             } catch (MissingResourceException e) {
   259                 // OK
   260             }
   261         }
   262         if (rb == null) {
   263             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   264         }
   265 
   266         Map<String,Object> map = new HashMap<String,Object>();
   267         map.put("doc", doc);
   268         map.put("user", user);
   269         map.put("bundle", rb);
   270         map.put("now", System.currentTimeMillis());
   271         for (int i = 0; i < more.length; i += 2) {
   272             map.put((String)more[i],more[i + 1]);
   273         }
   274         return new Viewable(page, map);
   275     }
   276 
   277 }