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