freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 07 Jan 2010 22:34:17 +0100
branchstatistics-and-elo
changeset 178 4b78d4f028b3
parent 172 3de0568f7ee8
child 179 c5fbddc4c590
permissions -rw-r--r--
Initial version of statistics and ELO rating. Donated by Martin Rexa
     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.Date;
    43 import java.util.HashMap;
    44 import java.util.List;
    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.CacheControl;
    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     private static WebResource stat;
    91 
    92     @Context
    93     private HttpHeaders headers;
    94     private UserInfo user;
    95     private String uuid;
    96 
    97     public UI() {
    98     }
    99 
   100     private Viewable checkLogin() {
   101         Cookie cookie = headers.getCookies().get("login");
   102         if (cookie != null) {
   103             String id = cookie.getValue();
   104             UserInfo us;
   105             try {
   106                 us = base.path("users").queryParam("loginID", id).
   107                     accept(MediaType.TEXT_XML).get(UserInfo.class);
   108             } catch (Exception ex) {
   109                 ex.printStackTrace();
   110                 us = null;
   111             }
   112             if (us != null && us.getId().length() > 0) {
   113                 user = us;
   114                 uuid = id;
   115                 return null;
   116             }
   117         }
   118         return viewable("login.fmt", null);
   119     }
   120 
   121     @POST
   122     @Path("login")
   123     @Produces(MediaType.TEXT_HTML)
   124     public Response login(
   125         @FormParam("name") String name, @FormParam("password") String password
   126     ) throws Exception {
   127         uuid = base.path("login").queryParam("name", name).queryParam("password", password).
   128             accept(MediaType.TEXT_PLAIN).put(String.class);
   129         if (uuid != null) {
   130             user = new UserInfo(name);
   131             NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
   132             return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
   133         } else {
   134             Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
   135             return Response.status(1).entity(v).build();
   136         }
   137     }
   138 
   139     @GET
   140     @Produces(MediaType.TEXT_HTML)
   141     public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
   142         Viewable v = checkLogin();
   143         ResponseBuilder resp = Response.ok();
   144         if (v == null) {
   145             v = welcomeImpl("maxItems", maxItems);
   146         }
   147         CacheControl cc = new CacheControl();
   148         cc.setNoCache(true);
   149         resp.cacheControl(cc);
   150         return resp.entity(v).build();
   151     }
   152 
   153     @GET
   154     @Path("games/{id}.png")
   155     @Produces("image/png")
   156     public Response getBoardImage(
   157         @PathParam("id") String id,
   158         @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
   159         @QueryParam("move") @DefaultValue("-1") int move
   160     ) throws IllegalPositionException {
   161         WebResource wr = base.path("games").path(id);
   162         if (move != -1) {
   163             wr = wr.queryParam("move", "" + move);
   164         }
   165         String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
   166         Board b = Board.valueOf(txt);
   167 //        Board b = new Board(txt);
   168         ResponseBuilder resp = Response.ok();
   169         CacheControl cc = new CacheControl();
   170         cc.setNoCache(true);
   171         resp.cacheControl(cc);
   172         return resp.entity(BoardImage.draw(b, fieldSize)).build();
   173     }
   174 
   175 
   176     private Response board(String id) {
   177         return board(id, "", null);
   178     }
   179     @GET
   180     @Path("games/{id}/")
   181     @Produces(MediaType.TEXT_HTML)
   182     public Response board(
   183         @PathParam("id") String id,
   184         @QueryParam("format") @DefaultValue("") String format,
   185         @QueryParam("move") @DefaultValue("-1") String move
   186     ) {
   187         return board(id, null, format, move);
   188     }
   189     private Response board(@PathParam("id") String id, String msg, String format, String m) {
   190         Viewable v = checkLogin();
   191         if (v != null) {
   192             return Response.ok().entity(v).build();
   193         }
   194         int move;
   195         try {
   196             move = Integer.parseInt(m);
   197         } catch (NumberFormatException ex) {
   198             move = -1;
   199         }
   200         WebResource url = base.path("games").queryParam("loginID", uuid).path(id);
   201         if (move >= 0) {
   202             url = url.queryParam("move", "" + move);
   203         }
   204         ResponseBuilder resp = Response.ok();
   205         CacheControl cc = new CacheControl();
   206         cc.setNoCache(true);
   207         resp.cacheControl(cc);
   208         Cookie cFormat = headers.getCookies().get("format");
   209         if (format.length() == 0) {
   210             if (cFormat != null) {
   211                 format = cFormat.getValue();
   212             } else {
   213                 if (isMobile(headers)) {
   214                     format = "small";
   215                 }
   216             }
   217         } else {
   218             if (cFormat == null || !format.equals(cFormat.getValue())) {
   219                 resp.cookie(new NewCookie("format", format));
   220             }
   221         }
   222 
   223         Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
   224         Board b;
   225         String t = doc.getElementsByTagName("board").item(0).getTextContent();
   226         try {
   227             b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
   228         } catch (Exception ex) {
   229 //            b = new Board(t);
   230 //        } catch (IllegalStateException ex) {
   231             Exceptions.printStackTrace(ex);
   232             b = Board.empty();
   233         }
   234         String bCode = null;
   235         try{
   236             bCode = stat.path("openings").path(Board.board2HashCode(b)+".check").queryParam("loginID", user.getId()).accept(MediaType.TEXT_PLAIN).get(String.class);
   237         }catch(Exception e){
   238             bCode = null;
   239         }
   240         if(bCode == null || "".equals(bCode))
   241             v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture",b.boardToPicture());
   242         else
   243             v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture",b.boardToPicture(),"bCode", bCode);
   244         return resp.entity(v).build();
   245     }
   246 
   247     @GET
   248     @Path("games/{id}/move")
   249     @Produces(MediaType.TEXT_HTML)
   250     public Response move(
   251         @PathParam("id") String id,
   252         @QueryParam("type") String type,
   253         @QueryParam("direction") String direction,
   254         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   255         @QueryParam("column") @DefaultValue("") String column,
   256         @QueryParam("row") @DefaultValue("") String row
   257     ) {
   258         Viewable v = checkLogin();
   259         if (v != null) {
   260             return Response.ok().entity(v).build();
   261         }
   262         WebResource wr = base.path("games").path(id).
   263             queryParam("loginID", uuid).
   264             queryParam("player", user.getId());
   265         try {
   266             if (type.equals("resign")) {
   267                 wr.queryParam("move", "RESIGN").put();
   268                 return board(id);
   269             }
   270             if (type.equals("fence")) {
   271                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   272                 return board(id);
   273             }
   274             if (type.equals("move")) {
   275                 wr.queryParam("move", direction + directionNext).put();
   276                 return board(id);
   277             }
   278         } catch (UniformInterfaceException ex) {
   279             return board(id, "WRONG_MOVE", "-1");
   280         }
   281         return board(id);
   282     }
   283 
   284     @GET
   285     @Path("games/{id}/comment")
   286     @Produces(MediaType.TEXT_HTML)
   287     public Response comment(
   288         @PathParam("id") String id,
   289         @QueryParam("comment") String comment
   290     ) {
   291         Viewable v = checkLogin();
   292         if (v != null) {
   293             return Response.ok().entity(v).build();
   294         }
   295         WebResource wr = base.path("games").path(id).
   296             queryParam("loginID", uuid).
   297             queryParam("player", user.getId()).
   298             queryParam("comment", comment);
   299         wr.put();
   300         
   301         return board(id);
   302     }
   303 
   304     @GET
   305     @Path("games/create")
   306     @Produces(MediaType.TEXT_HTML)
   307     public Response create(
   308         @QueryParam("white") String white,
   309         @QueryParam("black") String black
   310     ) {
   311         Viewable v = checkLogin();
   312         if (v != null) {
   313             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   314         }
   315 
   316         if (user.getId().equals(white) || user.getId().equals(black)) {
   317             Object obj =
   318                 base.path("games").
   319                 queryParam("loginID", uuid).
   320                 queryParam("white", white).
   321                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   322             return Response.ok(welcomeImpl()).build();
   323         } else {
   324             return Response.status(Response.Status.NOT_FOUND).
   325                 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
   326         }
   327     }
   328 
   329     private Viewable welcomeImpl(Object... args) {
   330         final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
   331         return viewable("index.fmt", got, args);
   332     }
   333 
   334 
   335     @GET
   336     @Path("options")
   337     public Response changeOptions(
   338         @QueryParam("email") String email,
   339         @QueryParam("language") String language
   340     ) {
   341         Viewable v = checkLogin();
   342         if (v != null) {
   343             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   344         }
   345 
   346         if (email != null) {
   347             UserInfo ui = base.path("users/" + user.getId()).
   348                 queryParam("loginID", uuid).
   349                 queryParam("name", "email").
   350                 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
   351         }
   352 
   353         if (language != null) {
   354             UserInfo ui = base.path("users/" + user.getId()).
   355                 queryParam("loginID", uuid).
   356                 queryParam("name", "language").
   357                 queryParam("value", language).
   358                 accept(MediaType.TEXT_XML).post(UserInfo.class);
   359         }
   360 
   361         return welcome(10);
   362     }
   363 
   364     @GET
   365     @Path("elo")
   366     @Produces(MediaType.TEXT_HTML)
   367     public Response getEloList(){
   368         Viewable v = checkLogin();
   369         if (v != null) {
   370             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   371         }
   372         final Document got = stat.path("elo").path("list").accept(MediaType.TEXT_XML).get(Document.class);
   373         return Response.ok(viewable("elo.fmt", got)).build();
   374     }
   375     
   376     @GET
   377     @Path("openings")
   378     @Produces(MediaType.TEXT_HTML)
   379     public Response getOpeningRoot(){
   380         return getOpeningNode("ROOT");
   381     }
   382 
   383     @GET
   384     @Path("openings/{code}")
   385     @Produces(MediaType.TEXT_HTML)
   386     public Response getOpeningNode(@PathParam("code") String code){
   387         Viewable v = checkLogin();
   388         if (v != null) {
   389             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   390         }
   391         final Document got = stat.path("openings").path(code).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
   392         Board b;
   393         try {
   394             b = Board.valueOf(got.getElementsByTagName("nodeCode").item(0).getTextContent());
   395         } catch (Exception ex) {
   396             Exceptions.printStackTrace(ex);
   397             b = Board.empty();
   398         }
   399         return Response.ok(viewable("openings.fmt", got, "whitefences",b.getPlayers().get(0).getFences(),"blackfences",b.getPlayers().get(1).getFences())).build();
   400     }
   401 
   402     @GET
   403     @Path("openings/{code}/{status}")
   404     @Produces(MediaType.TEXT_HTML)
   405     public Response getOpeningNodeGames(@PathParam("code") String code, @PathParam("status") String status){
   406         Viewable v = checkLogin();
   407         if (v != null) {
   408             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   409         }
   410         final Document got = stat.path("openings").path(code).path(status).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
   411         return Response.ok(viewable("opening_games.fmt", got,"code",code,"color",status)).build();
   412     }
   413 
   414     @GET
   415     @Path("openings/{code}.png")
   416     @Produces("image/png")
   417     public Response getOpeningBoardImage(
   418         @PathParam("code") String code,
   419         @QueryParam("fieldSize") @DefaultValue("40") int fieldSize
   420     ) throws IllegalPositionException {
   421         Board b = new Board(code);
   422         ResponseBuilder resp = Response.ok();
   423         CacheControl cc = new CacheControl();
   424         cc.setNoCache(true);
   425         resp.cacheControl(cc);
   426         return resp.entity(BoardImage.draw(b, fieldSize)).build();
   427     }
   428 
   429     //
   430     // start the server
   431     //
   432 
   433     public static void main(String[] args) throws Exception {
   434         int port = 9333;
   435         if (args.length > 1) {
   436             port = Integer.parseInt(args[0]);
   437         }
   438         String remoteAPI = args.length >= 2 ? args[1] : null;
   439 
   440         Locale.setDefault(Locale.ROOT);
   441 
   442         Callable<Void> r = startServers(port, remoteAPI);
   443 
   444         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   445             System.out.println("Hit enter to stop it...");
   446             System.in.read();
   447         } else {
   448             synchronized (UI.class) {
   449                 UI.class.wait();
   450             }
   451         }
   452         r.call();
   453         System.exit(0);
   454     }
   455 
   456     static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
   457         Client client = new Client();
   458         Client client1 = new Client();
   459 
   460         final HttpServer apiServer;
   461         if (remoteAPI == null) {
   462             throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
   463         } else {
   464             base = client.resource(new URI(remoteAPI));
   465             stat = client1.resource(new URI("http://localhost:9444"));
   466             apiServer = null;
   467         }
   468 
   469         ResourceConfig rc = new PackagesResourceConfig(
   470             "cz.xelfi.quoridor.freemarkerdor"
   471         );
   472 
   473         final String baseUri = "http://localhost:" + port + "/";
   474         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   475         server.start();
   476         System.out.println("Quoridor started at port " + port);
   477 
   478         return new Callable<Void>() {
   479             public Void call() throws Exception {
   480                 if (apiServer != null) {
   481                     apiServer.stop(0);
   482                 }
   483                 server.stop(0);
   484                 return null;
   485             }
   486         };
   487     }
   488 
   489     private Viewable viewable(String page, Document doc, Object... more) {
   490         ResourceBundle rb = null;
   491         String lng = user == null ? null : user.getProperty("language"); // NOI18N
   492         Locale locale = null;
   493         if (lng != null) {
   494                 try {
   495                     Locale l = new Locale(lng);
   496                     rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   497                     locale = l;
   498                 } catch (MissingResourceException e) {
   499                     // OK
   500                 }
   501         }
   502         if (rb == null) {
   503             for (Locale l : headers.getAcceptableLanguages()) {
   504                 try {
   505                     rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   506                     locale = l;
   507                     break;
   508                 } catch (MissingResourceException e) {
   509                     // OK
   510                 }
   511             }
   512         }
   513         if (rb == null) {
   514             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   515             locale = Locale.ENGLISH;
   516         }
   517 
   518         Map<String,Object> map = new HashMap<String,Object>();
   519         class ConvertToDate extends HashMap<Object,Object> {
   520             @Override
   521             public Object get(Object o) {
   522                 long time = Long.parseLong(o.toString());
   523                 return new Date(time);
   524             }
   525         }
   526 
   527         map.put("locale", locale.toString());
   528         map.put("doc", doc);
   529         if (user != null) {
   530             map.put("user", user.getId());
   531             map.put("email", user.getProperty("email"));
   532         }
   533         map.put("bundle", rb);
   534         map.put("toDate", new ConvertToDate());
   535         map.put("now", System.currentTimeMillis());
   536         map.put("version", version);
   537         for (int i = 0; i < more.length; i += 2) {
   538             map.put((String)more[i],more[i + 1]);
   539         }
   540         return new Viewable(page, map);
   541     }
   542 
   543 
   544     private static boolean isMobile(HttpHeaders headers) {
   545         final String[] keywords = {
   546             "Profile/MIDP",
   547         };
   548         List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
   549         if (agent != null) {
   550             for (String a : agent) {
   551                 for (String k : keywords) {
   552                     if (a.contains(k)) {
   553                         return true;
   554                     }
   555                 }
   556             }
   557         }
   558         return false;
   559     }
   560 
   561 }