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