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