freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 18 Oct 2009 20:29:49 +0200
changeset 126 e905cd9b1e4a
parent 124 90371f3eb106
child 129 fd95f7873b96
permissions -rw-r--r--
Removing compile time dependency on webidor, its functionality is accessed only via REST
     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.awt.Image;
    40 import java.io.IOException;
    41 import java.io.InputStream;
    42 import java.net.URI;
    43 import java.util.HashMap;
    44 import java.util.Locale;
    45 import java.util.Map;
    46 import java.util.MissingResourceException;
    47 import java.util.Properties;
    48 import java.util.ResourceBundle;
    49 import java.util.concurrent.Callable;
    50 import javax.ws.rs.DefaultValue;
    51 import javax.ws.rs.FormParam;
    52 import javax.ws.rs.GET;
    53 import javax.ws.rs.POST;
    54 import javax.ws.rs.Path;
    55 import javax.ws.rs.PathParam;
    56 import javax.ws.rs.Produces;
    57 import javax.ws.rs.QueryParam;
    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 Viewable welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
   139         Viewable v = checkLogin();
   140         if (v != null) {
   141             return v;
   142         }
   143         return welcomeImpl("maxItems", maxItems);
   144     }
   145 
   146     @GET
   147     @Path("games/{id}.png")
   148     @Produces("image/png")
   149     public Image getBoardImage(
   150         @PathParam("id") String id,
   151         @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
   152         @QueryParam("move") @DefaultValue("-1") int move
   153     ) throws IllegalPositionException {
   154         WebResource wr = base.path("games").path(id);
   155         if (move != -1) {
   156             wr = wr.queryParam("move", "" + move);
   157         }
   158         String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
   159         Board b = Board.valueOf(txt);
   160         return BoardImage.draw(b, fieldSize);
   161     }
   162 
   163 
   164     private Response board(String id) {
   165         return board(id, "", null);
   166     }
   167     @GET
   168     @Path("games/{id}/")
   169     @Produces(MediaType.TEXT_HTML)
   170     public Response board(
   171         @PathParam("id") String id,
   172         @QueryParam("format") @DefaultValue("") String format,
   173         @QueryParam("move") @DefaultValue("-1") String move
   174     ) {
   175         return board(id, null, format, move);
   176     }
   177     private Response board(@PathParam("id") String id, String msg, String format, String m) {
   178         Viewable v = checkLogin();
   179         if (v != null) {
   180             return Response.ok().entity(v).build();
   181         }
   182         int move;
   183         try {
   184             move = Integer.parseInt(m);
   185         } catch (NumberFormatException ex) {
   186             move = -1;
   187         }
   188         WebResource url = base.path("games").path(id);
   189         if (move >= 0) {
   190             url = url.queryParam("move", "" + move);
   191         }
   192         ResponseBuilder resp = Response.ok();
   193         Cookie cFormat = headers.getCookies().get("format");
   194         if (format.length() == 0) {
   195             if (cFormat != null) {
   196                 format = cFormat.getValue();
   197             }
   198         } else {
   199             if (cFormat == null || !format.equals(cFormat.getValue())) {
   200                 resp.cookie(new NewCookie("format", format));
   201             }
   202         }
   203 
   204         Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
   205         Board b;
   206         try {
   207             b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
   208         } catch (IllegalPositionException ex) {
   209             Exceptions.printStackTrace(ex);
   210             b = Board.empty();
   211         }
   212         v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
   213         return resp.entity(v).build();
   214     }
   215 
   216     @GET
   217     @Path("games/{id}/move")
   218     @Produces(MediaType.TEXT_HTML)
   219     public Response move(
   220         @PathParam("id") String id,
   221         @QueryParam("type") String type,
   222         @QueryParam("direction") String direction,
   223         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   224         @QueryParam("column") @DefaultValue("") String column,
   225         @QueryParam("row") @DefaultValue("") String row
   226     ) {
   227         Viewable v = checkLogin();
   228         if (v != null) {
   229             return Response.ok().entity(v).build();
   230         }
   231         WebResource wr = base.path("games").path(id).
   232             queryParam("loginID", uuid).
   233             queryParam("player", user);
   234         try {
   235             if (type.equals("resign")) {
   236                 wr.queryParam("move", "RESIGN").put();
   237                 return board(id);
   238             }
   239             if (type.equals("fence")) {
   240                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   241                 return board(id);
   242             }
   243             if (type.equals("move")) {
   244                 wr.queryParam("move", direction + directionNext).put();
   245                 return board(id);
   246             }
   247         } catch (UniformInterfaceException ex) {
   248             return board(id, "WRONG_MOVE", "-1");
   249         }
   250         return board(id);
   251     }
   252 
   253     @GET
   254     @Path("games/{id}/comment")
   255     @Produces(MediaType.TEXT_HTML)
   256     public Response comment(
   257         @PathParam("id") String id,
   258         @QueryParam("comment") String comment
   259     ) {
   260         Viewable v = checkLogin();
   261         if (v != null) {
   262             return Response.ok().entity(v).build();
   263         }
   264         WebResource wr = base.path("games").path(id).
   265             queryParam("loginID", uuid).
   266             queryParam("player", user).
   267             queryParam("comment", comment);
   268         wr.put();
   269         
   270         return board(id);
   271     }
   272 
   273     @GET
   274     @Path("games/create")
   275     @Produces(MediaType.TEXT_HTML)
   276     public Response create(
   277         @QueryParam("white") String white,
   278         @QueryParam("black") String black
   279     ) {
   280         Viewable v = checkLogin();
   281         if (v != null) {
   282             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   283         }
   284 
   285         if (user.equals(white) || user.equals(black)) {
   286             Object obj =
   287                 base.path("games").
   288                 queryParam("loginID", uuid).
   289                 queryParam("white", white).
   290                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   291             return Response.ok(welcomeImpl()).build();
   292         } else {
   293             return Response.status(Response.Status.NOT_FOUND).
   294                 entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
   295         }
   296     }
   297 
   298     private Viewable welcomeImpl(Object... args) {
   299         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   300         return viewable("index.fmt", got, args);
   301     }
   302 
   303     //
   304     // start the server
   305     //
   306 
   307     public static void main(String[] args) throws Exception {
   308         int port = 9333;
   309         if (args.length > 1) {
   310             port = Integer.parseInt(args[0]);
   311         }
   312         String remoteAPI = args.length > 2 ? args[1] : null;
   313 
   314 
   315         Callable<Void> r = startServers(port, remoteAPI);
   316 
   317         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   318             System.out.println("Hit enter to stop it...");
   319             System.in.read();
   320         } else {
   321             synchronized (UI.class) {
   322                 UI.class.wait();
   323             }
   324         }
   325         r.call();
   326         System.exit(0);
   327     }
   328 
   329     static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
   330         Client client = new Client();
   331 
   332         final HttpServer apiServer;
   333         if (remoteAPI == null) {
   334             throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
   335         } else {
   336             base = client.resource(new URI(remoteAPI));
   337             apiServer = null;
   338         }
   339 
   340         ResourceConfig rc = new PackagesResourceConfig(
   341             "cz.xelfi.quoridor.freemarkerdor"
   342         );
   343 
   344         final String baseUri = "http://localhost:" + port + "/";
   345         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   346         server.start();
   347         System.out.println("Quoridor started at port " + port);
   348 
   349         return new Callable<Void>() {
   350             public Void call() throws Exception {
   351                 if (apiServer != null) {
   352                     apiServer.stop(0);
   353                 }
   354                 server.stop(0);
   355                 return null;
   356             }
   357         };
   358     }
   359 
   360     private Viewable viewable(String page, Document doc, Object... more) {
   361         ResourceBundle rb = null;
   362         for (Locale l : headers.getAcceptableLanguages()) {
   363             try {
   364                 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   365             } catch (MissingResourceException e) {
   366                 // OK
   367             }
   368         }
   369         if (rb == null) {
   370             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   371         }
   372 
   373         Map<String,Object> map = new HashMap<String,Object>();
   374         map.put("doc", doc);
   375         map.put("user", user);
   376         map.put("bundle", rb);
   377         map.put("now", System.currentTimeMillis());
   378         map.put("version", version);
   379         for (int i = 0; i < more.length; i += 2) {
   380             map.put((String)more[i],more[i + 1]);
   381         }
   382         return new Viewable(page, map);
   383     }
   384 
   385 }