freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 25 Oct 2009 14:42:33 +0100
changeset 132 23055e2d6539
parent 129 fd95f7873b96
child 146 0b889d9e4ee1
permissions -rw-r--r--
Two parameters are enough to specify port and URL of API
     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.Board;
    38 import cz.xelfi.quoridor.IllegalPositionException;
    39 import java.io.IOException;
    40 import java.io.InputStream;
    41 import java.net.URI;
    42 import java.util.HashMap;
    43 import java.util.Locale;
    44 import java.util.Map;
    45 import java.util.MissingResourceException;
    46 import java.util.Properties;
    47 import java.util.ResourceBundle;
    48 import java.util.concurrent.Callable;
    49 import javax.ws.rs.DefaultValue;
    50 import javax.ws.rs.FormParam;
    51 import javax.ws.rs.GET;
    52 import javax.ws.rs.POST;
    53 import javax.ws.rs.Path;
    54 import javax.ws.rs.PathParam;
    55 import javax.ws.rs.Produces;
    56 import javax.ws.rs.QueryParam;
    57 import javax.ws.rs.core.CacheControl;
    58 import javax.ws.rs.core.Context;
    59 import javax.ws.rs.core.Cookie;
    60 import javax.ws.rs.core.HttpHeaders;
    61 import javax.ws.rs.core.MediaType;
    62 import javax.ws.rs.core.NewCookie;
    63 import javax.ws.rs.core.Response;
    64 import javax.ws.rs.core.Response.ResponseBuilder;
    65 import org.openide.util.Exceptions;
    66 import org.w3c.dom.Document;
    67 
    68 /**
    69  *
    70  * @author Jaroslav Tulach <jtulach@netbeans.org>
    71  */
    72 @Path("/")
    73 public final class UI {
    74     private static final String version;
    75     static {
    76         Properties p = new Properties();
    77         try {
    78             InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/org.apidesign/freemarkerdor/pom.properties"); // NOI18N
    79             if (is != null) {
    80                 p.load(is);
    81             }
    82         } catch (IOException ex) {
    83             ex.printStackTrace();
    84         }
    85         version = p.getProperty("version", "unknown"); // NOI18N
    86     }
    87     private static WebResource base;
    88 
    89     @Context
    90     private HttpHeaders headers;
    91     private String user;
    92     private String uuid;
    93 
    94     public UI() {
    95     }
    96 
    97     private Viewable checkLogin() {
    98         Cookie cookie = headers.getCookies().get("login");
    99         if (cookie != null) {
   100             String id = cookie.getValue();
   101             String us;
   102             try {
   103                 us = base.path("login").queryParam("id", id).
   104                     accept(MediaType.TEXT_PLAIN).get(String.class);
   105             } catch (UniformInterfaceException ex) {
   106                 ex.printStackTrace();
   107                 us = "";
   108             }
   109             if (us.length() > 0) {
   110                 user = us;
   111                 uuid = id;
   112                 return null;
   113             }
   114         }
   115         return viewable("login.fmt", null);
   116     }
   117 
   118     @POST
   119     @Path("login")
   120     @Produces(MediaType.TEXT_HTML)
   121     public Response login(
   122         @FormParam("name") String name, @FormParam("password") String password
   123     ) throws Exception {
   124         uuid = base.path("login").queryParam("name", name).queryParam("password", password).
   125             accept(MediaType.TEXT_PLAIN).put(String.class);
   126         if (uuid != null) {
   127             user = name;
   128             NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
   129             return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
   130         } else {
   131             Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
   132             return Response.status(1).entity(v).build();
   133         }
   134     }
   135 
   136     @GET
   137     @Produces(MediaType.TEXT_HTML)
   138     public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
   139         Viewable v = checkLogin();
   140         ResponseBuilder resp = Response.ok();
   141         if (v == null) {
   142             v = welcomeImpl("maxItems", maxItems);
   143         }
   144         CacheControl cc = new CacheControl();
   145         cc.setNoCache(true);
   146         resp.cacheControl(cc);
   147         return resp.entity(v).build();
   148     }
   149 
   150     @GET
   151     @Path("games/{id}.png")
   152     @Produces("image/png")
   153     public Response getBoardImage(
   154         @PathParam("id") String id,
   155         @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
   156         @QueryParam("move") @DefaultValue("-1") int move
   157     ) throws IllegalPositionException {
   158         WebResource wr = base.path("games").path(id);
   159         if (move != -1) {
   160             wr = wr.queryParam("move", "" + move);
   161         }
   162         String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
   163         Board b = Board.valueOf(txt);
   164         ResponseBuilder resp = Response.ok();
   165         CacheControl cc = new CacheControl();
   166         cc.setNoCache(true);
   167         resp.cacheControl(cc);
   168         return resp.entity(BoardImage.draw(b, fieldSize)).build();
   169     }
   170 
   171 
   172     private Response board(String id) {
   173         return board(id, "", null);
   174     }
   175     @GET
   176     @Path("games/{id}/")
   177     @Produces(MediaType.TEXT_HTML)
   178     public Response board(
   179         @PathParam("id") String id,
   180         @QueryParam("format") @DefaultValue("") String format,
   181         @QueryParam("move") @DefaultValue("-1") String move
   182     ) {
   183         return board(id, null, format, move);
   184     }
   185     private Response board(@PathParam("id") String id, String msg, String format, String m) {
   186         Viewable v = checkLogin();
   187         if (v != null) {
   188             return Response.ok().entity(v).build();
   189         }
   190         int move;
   191         try {
   192             move = Integer.parseInt(m);
   193         } catch (NumberFormatException ex) {
   194             move = -1;
   195         }
   196         WebResource url = base.path("games").path(id);
   197         if (move >= 0) {
   198             url = url.queryParam("move", "" + move);
   199         }
   200         ResponseBuilder resp = Response.ok();
   201         CacheControl cc = new CacheControl();
   202         cc.setNoCache(true);
   203         resp.cacheControl(cc);
   204         Cookie cFormat = headers.getCookies().get("format");
   205         if (format.length() == 0) {
   206             if (cFormat != null) {
   207                 format = cFormat.getValue();
   208             }
   209         } else {
   210             if (cFormat == null || !format.equals(cFormat.getValue())) {
   211                 resp.cookie(new NewCookie("format", format));
   212             }
   213         }
   214 
   215         Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
   216         Board b;
   217         try {
   218             b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
   219         } catch (IllegalPositionException ex) {
   220             Exceptions.printStackTrace(ex);
   221             b = Board.empty();
   222         }
   223         v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
   224         return resp.entity(v).build();
   225     }
   226 
   227     @GET
   228     @Path("games/{id}/move")
   229     @Produces(MediaType.TEXT_HTML)
   230     public Response move(
   231         @PathParam("id") String id,
   232         @QueryParam("type") String type,
   233         @QueryParam("direction") String direction,
   234         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   235         @QueryParam("column") @DefaultValue("") String column,
   236         @QueryParam("row") @DefaultValue("") String row
   237     ) {
   238         Viewable v = checkLogin();
   239         if (v != null) {
   240             return Response.ok().entity(v).build();
   241         }
   242         WebResource wr = base.path("games").path(id).
   243             queryParam("loginID", uuid).
   244             queryParam("player", user);
   245         try {
   246             if (type.equals("resign")) {
   247                 wr.queryParam("move", "RESIGN").put();
   248                 return board(id);
   249             }
   250             if (type.equals("fence")) {
   251                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   252                 return board(id);
   253             }
   254             if (type.equals("move")) {
   255                 wr.queryParam("move", direction + directionNext).put();
   256                 return board(id);
   257             }
   258         } catch (UniformInterfaceException ex) {
   259             return board(id, "WRONG_MOVE", "-1");
   260         }
   261         return board(id);
   262     }
   263 
   264     @GET
   265     @Path("games/{id}/comment")
   266     @Produces(MediaType.TEXT_HTML)
   267     public Response comment(
   268         @PathParam("id") String id,
   269         @QueryParam("comment") String comment
   270     ) {
   271         Viewable v = checkLogin();
   272         if (v != null) {
   273             return Response.ok().entity(v).build();
   274         }
   275         WebResource wr = base.path("games").path(id).
   276             queryParam("loginID", uuid).
   277             queryParam("player", user).
   278             queryParam("comment", comment);
   279         wr.put();
   280         
   281         return board(id);
   282     }
   283 
   284     @GET
   285     @Path("games/create")
   286     @Produces(MediaType.TEXT_HTML)
   287     public Response create(
   288         @QueryParam("white") String white,
   289         @QueryParam("black") String black
   290     ) {
   291         Viewable v = checkLogin();
   292         if (v != null) {
   293             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   294         }
   295 
   296         if (user.equals(white) || user.equals(black)) {
   297             Object obj =
   298                 base.path("games").
   299                 queryParam("loginID", uuid).
   300                 queryParam("white", white).
   301                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   302             return Response.ok(welcomeImpl()).build();
   303         } else {
   304             return Response.status(Response.Status.NOT_FOUND).
   305                 entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
   306         }
   307     }
   308 
   309     private Viewable welcomeImpl(Object... args) {
   310         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   311         return viewable("index.fmt", got, args);
   312     }
   313 
   314     //
   315     // start the server
   316     //
   317 
   318     public static void main(String[] args) throws Exception {
   319         int port = 9333;
   320         if (args.length > 1) {
   321             port = Integer.parseInt(args[0]);
   322         }
   323         String remoteAPI = args.length >= 2 ? args[1] : null;
   324 
   325 
   326         Callable<Void> r = startServers(port, remoteAPI);
   327 
   328         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   329             System.out.println("Hit enter to stop it...");
   330             System.in.read();
   331         } else {
   332             synchronized (UI.class) {
   333                 UI.class.wait();
   334             }
   335         }
   336         r.call();
   337         System.exit(0);
   338     }
   339 
   340     static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
   341         Client client = new Client();
   342 
   343         final HttpServer apiServer;
   344         if (remoteAPI == null) {
   345             throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
   346         } else {
   347             base = client.resource(new URI(remoteAPI));
   348             apiServer = null;
   349         }
   350 
   351         ResourceConfig rc = new PackagesResourceConfig(
   352             "cz.xelfi.quoridor.freemarkerdor"
   353         );
   354 
   355         final String baseUri = "http://localhost:" + port + "/";
   356         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   357         server.start();
   358         System.out.println("Quoridor started at port " + port);
   359 
   360         return new Callable<Void>() {
   361             public Void call() throws Exception {
   362                 if (apiServer != null) {
   363                     apiServer.stop(0);
   364                 }
   365                 server.stop(0);
   366                 return null;
   367             }
   368         };
   369     }
   370 
   371     private Viewable viewable(String page, Document doc, Object... more) {
   372         ResourceBundle rb = null;
   373         for (Locale l : headers.getAcceptableLanguages()) {
   374             try {
   375                 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   376             } catch (MissingResourceException e) {
   377                 // OK
   378             }
   379         }
   380         if (rb == null) {
   381             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   382         }
   383 
   384         Map<String,Object> map = new HashMap<String,Object>();
   385         map.put("doc", doc);
   386         map.put("user", user);
   387         map.put("bundle", rb);
   388         map.put("now", System.currentTimeMillis());
   389         map.put("version", version);
   390         for (int i = 0; i < more.length; i += 2) {
   391             map.put((String)more[i],more[i + 1]);
   392         }
   393         return new Viewable(page, map);
   394     }
   395 
   396 }