freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 23 Dec 2009 20:45:19 +0100
changeset 172 3de0568f7ee8
parent 170 7d29ebd9c208
child 178 4b78d4f028b3
permissions -rw-r--r--
Older dates are displayed as absolute, not relative
     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 
    91     @Context
    92     private HttpHeaders headers;
    93     private UserInfo 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             UserInfo us;
   104             try {
   105                 us = base.path("users").queryParam("loginID", id).
   106                     accept(MediaType.TEXT_XML).get(UserInfo.class);
   107             } catch (Exception ex) {
   108                 ex.printStackTrace();
   109                 us = null;
   110             }
   111             if (us != null && us.getId().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 = new UserInfo(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 Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
   141         Viewable v = checkLogin();
   142         ResponseBuilder resp = Response.ok();
   143         if (v == null) {
   144             v = welcomeImpl("maxItems", maxItems);
   145         }
   146         CacheControl cc = new CacheControl();
   147         cc.setNoCache(true);
   148         resp.cacheControl(cc);
   149         return resp.entity(v).build();
   150     }
   151 
   152     @GET
   153     @Path("games/{id}.png")
   154     @Produces("image/png")
   155     public Response getBoardImage(
   156         @PathParam("id") String id,
   157         @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
   158         @QueryParam("move") @DefaultValue("-1") int move
   159     ) throws IllegalPositionException {
   160         WebResource wr = base.path("games").path(id);
   161         if (move != -1) {
   162             wr = wr.queryParam("move", "" + move);
   163         }
   164         String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
   165         Board b = Board.valueOf(txt);
   166         ResponseBuilder resp = Response.ok();
   167         CacheControl cc = new CacheControl();
   168         cc.setNoCache(true);
   169         resp.cacheControl(cc);
   170         return resp.entity(BoardImage.draw(b, fieldSize)).build();
   171     }
   172 
   173 
   174     private Response board(String id) {
   175         return board(id, "", null);
   176     }
   177     @GET
   178     @Path("games/{id}/")
   179     @Produces(MediaType.TEXT_HTML)
   180     public Response board(
   181         @PathParam("id") String id,
   182         @QueryParam("format") @DefaultValue("") String format,
   183         @QueryParam("move") @DefaultValue("-1") String move
   184     ) {
   185         return board(id, null, format, move);
   186     }
   187     private Response board(@PathParam("id") String id, String msg, String format, String m) {
   188         Viewable v = checkLogin();
   189         if (v != null) {
   190             return Response.ok().entity(v).build();
   191         }
   192         int move;
   193         try {
   194             move = Integer.parseInt(m);
   195         } catch (NumberFormatException ex) {
   196             move = -1;
   197         }
   198         WebResource url = base.path("games").queryParam("loginID", uuid).path(id);
   199         if (move >= 0) {
   200             url = url.queryParam("move", "" + move);
   201         }
   202         ResponseBuilder resp = Response.ok();
   203         CacheControl cc = new CacheControl();
   204         cc.setNoCache(true);
   205         resp.cacheControl(cc);
   206         Cookie cFormat = headers.getCookies().get("format");
   207         if (format.length() == 0) {
   208             if (cFormat != null) {
   209                 format = cFormat.getValue();
   210             } else {
   211                 if (isMobile(headers)) {
   212                     format = "small";
   213                 }
   214             }
   215         } else {
   216             if (cFormat == null || !format.equals(cFormat.getValue())) {
   217                 resp.cookie(new NewCookie("format", format));
   218             }
   219         }
   220 
   221         Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
   222         Board b;
   223         try {
   224             b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
   225         } catch (IllegalPositionException ex) {
   226             Exceptions.printStackTrace(ex);
   227             b = Board.empty();
   228         }
   229         v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
   230         return resp.entity(v).build();
   231     }
   232 
   233     @GET
   234     @Path("games/{id}/move")
   235     @Produces(MediaType.TEXT_HTML)
   236     public Response move(
   237         @PathParam("id") String id,
   238         @QueryParam("type") String type,
   239         @QueryParam("direction") String direction,
   240         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   241         @QueryParam("column") @DefaultValue("") String column,
   242         @QueryParam("row") @DefaultValue("") String row
   243     ) {
   244         Viewable v = checkLogin();
   245         if (v != null) {
   246             return Response.ok().entity(v).build();
   247         }
   248         WebResource wr = base.path("games").path(id).
   249             queryParam("loginID", uuid).
   250             queryParam("player", user.getId());
   251         try {
   252             if (type.equals("resign")) {
   253                 wr.queryParam("move", "RESIGN").put();
   254                 return board(id);
   255             }
   256             if (type.equals("fence")) {
   257                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   258                 return board(id);
   259             }
   260             if (type.equals("move")) {
   261                 wr.queryParam("move", direction + directionNext).put();
   262                 return board(id);
   263             }
   264         } catch (UniformInterfaceException ex) {
   265             return board(id, "WRONG_MOVE", "-1");
   266         }
   267         return board(id);
   268     }
   269 
   270     @GET
   271     @Path("games/{id}/comment")
   272     @Produces(MediaType.TEXT_HTML)
   273     public Response comment(
   274         @PathParam("id") String id,
   275         @QueryParam("comment") String comment
   276     ) {
   277         Viewable v = checkLogin();
   278         if (v != null) {
   279             return Response.ok().entity(v).build();
   280         }
   281         WebResource wr = base.path("games").path(id).
   282             queryParam("loginID", uuid).
   283             queryParam("player", user.getId()).
   284             queryParam("comment", comment);
   285         wr.put();
   286         
   287         return board(id);
   288     }
   289 
   290     @GET
   291     @Path("games/create")
   292     @Produces(MediaType.TEXT_HTML)
   293     public Response create(
   294         @QueryParam("white") String white,
   295         @QueryParam("black") String black
   296     ) {
   297         Viewable v = checkLogin();
   298         if (v != null) {
   299             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   300         }
   301 
   302         if (user.getId().equals(white) || user.getId().equals(black)) {
   303             Object obj =
   304                 base.path("games").
   305                 queryParam("loginID", uuid).
   306                 queryParam("white", white).
   307                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   308             return Response.ok(welcomeImpl()).build();
   309         } else {
   310             return Response.status(Response.Status.NOT_FOUND).
   311                 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
   312         }
   313     }
   314 
   315     private Viewable welcomeImpl(Object... args) {
   316         final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
   317         return viewable("index.fmt", got, args);
   318     }
   319 
   320 
   321     @GET
   322     @Path("options")
   323     public Response changeOptions(
   324         @QueryParam("email") String email,
   325         @QueryParam("language") String language
   326     ) {
   327         Viewable v = checkLogin();
   328         if (v != null) {
   329             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   330         }
   331 
   332         if (email != null) {
   333             UserInfo ui = base.path("users/" + user.getId()).
   334                 queryParam("loginID", uuid).
   335                 queryParam("name", "email").
   336                 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
   337         }
   338 
   339         if (language != null) {
   340             UserInfo ui = base.path("users/" + user.getId()).
   341                 queryParam("loginID", uuid).
   342                 queryParam("name", "language").
   343                 queryParam("value", language).
   344                 accept(MediaType.TEXT_XML).post(UserInfo.class);
   345         }
   346 
   347         return welcome(10);
   348     }
   349     
   350     //
   351     // start the server
   352     //
   353 
   354     public static void main(String[] args) throws Exception {
   355         int port = 9333;
   356         if (args.length > 1) {
   357             port = Integer.parseInt(args[0]);
   358         }
   359         String remoteAPI = args.length >= 2 ? args[1] : null;
   360 
   361         Locale.setDefault(Locale.ROOT);
   362 
   363         Callable<Void> r = startServers(port, remoteAPI);
   364 
   365         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   366             System.out.println("Hit enter to stop it...");
   367             System.in.read();
   368         } else {
   369             synchronized (UI.class) {
   370                 UI.class.wait();
   371             }
   372         }
   373         r.call();
   374         System.exit(0);
   375     }
   376 
   377     static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
   378         Client client = new Client();
   379 
   380         final HttpServer apiServer;
   381         if (remoteAPI == null) {
   382             throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
   383         } else {
   384             base = client.resource(new URI(remoteAPI));
   385             apiServer = null;
   386         }
   387 
   388         ResourceConfig rc = new PackagesResourceConfig(
   389             "cz.xelfi.quoridor.freemarkerdor"
   390         );
   391 
   392         final String baseUri = "http://localhost:" + port + "/";
   393         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   394         server.start();
   395         System.out.println("Quoridor started at port " + port);
   396 
   397         return new Callable<Void>() {
   398             public Void call() throws Exception {
   399                 if (apiServer != null) {
   400                     apiServer.stop(0);
   401                 }
   402                 server.stop(0);
   403                 return null;
   404             }
   405         };
   406     }
   407 
   408     private Viewable viewable(String page, Document doc, Object... more) {
   409         ResourceBundle rb = null;
   410         String lng = user == null ? null : user.getProperty("language"); // NOI18N
   411         Locale locale = null;
   412         if (lng != null) {
   413                 try {
   414                     Locale l = new Locale(lng);
   415                     rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   416                     locale = l;
   417                 } catch (MissingResourceException e) {
   418                     // OK
   419                 }
   420         }
   421         if (rb == null) {
   422             for (Locale l : headers.getAcceptableLanguages()) {
   423                 try {
   424                     rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   425                     locale = l;
   426                     break;
   427                 } catch (MissingResourceException e) {
   428                     // OK
   429                 }
   430             }
   431         }
   432         if (rb == null) {
   433             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   434             locale = Locale.ENGLISH;
   435         }
   436 
   437         Map<String,Object> map = new HashMap<String,Object>();
   438         class ConvertToDate extends HashMap<Object,Object> {
   439             @Override
   440             public Object get(Object o) {
   441                 long time = Long.parseLong(o.toString());
   442                 return new Date(time);
   443             }
   444         }
   445 
   446         map.put("locale", locale.toString());
   447         map.put("doc", doc);
   448         if (user != null) {
   449             map.put("user", user.getId());
   450             map.put("email", user.getProperty("email"));
   451         }
   452         map.put("bundle", rb);
   453         map.put("toDate", new ConvertToDate());
   454         map.put("now", System.currentTimeMillis());
   455         map.put("version", version);
   456         for (int i = 0; i < more.length; i += 2) {
   457             map.put((String)more[i],more[i + 1]);
   458         }
   459         return new Viewable(page, map);
   460     }
   461 
   462 
   463     private static boolean isMobile(HttpHeaders headers) {
   464         final String[] keywords = {
   465             "Profile/MIDP",
   466         };
   467         List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
   468         if (agent != null) {
   469             for (String a : agent) {
   470                 for (String k : keywords) {
   471                     if (a.contains(k)) {
   472                         return true;
   473                     }
   474                 }
   475             }
   476         }
   477         return false;
   478     }
   479 
   480 }