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