freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 08 Nov 2009 09:54:32 +0100
changeset 146 0b889d9e4ee1
parent 132 23055e2d6539
child 152 07e3bcb65c1d
permissions -rw-r--r--
Allowing users to specify their preferred language
     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.client.config.DefaultClientConfig;
    33 import com.sun.jersey.api.container.httpserver.HttpServerFactory;
    34 import com.sun.jersey.api.core.PackagesResourceConfig;
    35 import com.sun.jersey.api.core.ResourceConfig;
    36 import com.sun.jersey.api.view.Viewable;
    37 import com.sun.net.httpserver.HttpServer;
    38 import cz.xelfi.quoridor.Board;
    39 import cz.xelfi.quoridor.IllegalPositionException;
    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.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             }
   210         } else {
   211             if (cFormat == null || !format.equals(cFormat.getValue())) {
   212                 resp.cookie(new NewCookie("format", format));
   213             }
   214         }
   215 
   216         Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
   217         Board b;
   218         try {
   219             b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
   220         } catch (IllegalPositionException ex) {
   221             Exceptions.printStackTrace(ex);
   222             b = Board.empty();
   223         }
   224         v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
   225         return resp.entity(v).build();
   226     }
   227 
   228     @GET
   229     @Path("games/{id}/move")
   230     @Produces(MediaType.TEXT_HTML)
   231     public Response move(
   232         @PathParam("id") String id,
   233         @QueryParam("type") String type,
   234         @QueryParam("direction") String direction,
   235         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   236         @QueryParam("column") @DefaultValue("") String column,
   237         @QueryParam("row") @DefaultValue("") String row
   238     ) {
   239         Viewable v = checkLogin();
   240         if (v != null) {
   241             return Response.ok().entity(v).build();
   242         }
   243         WebResource wr = base.path("games").path(id).
   244             queryParam("loginID", uuid).
   245             queryParam("player", user.getId());
   246         try {
   247             if (type.equals("resign")) {
   248                 wr.queryParam("move", "RESIGN").put();
   249                 return board(id);
   250             }
   251             if (type.equals("fence")) {
   252                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   253                 return board(id);
   254             }
   255             if (type.equals("move")) {
   256                 wr.queryParam("move", direction + directionNext).put();
   257                 return board(id);
   258             }
   259         } catch (UniformInterfaceException ex) {
   260             return board(id, "WRONG_MOVE", "-1");
   261         }
   262         return board(id);
   263     }
   264 
   265     @GET
   266     @Path("games/{id}/comment")
   267     @Produces(MediaType.TEXT_HTML)
   268     public Response comment(
   269         @PathParam("id") String id,
   270         @QueryParam("comment") String comment
   271     ) {
   272         Viewable v = checkLogin();
   273         if (v != null) {
   274             return Response.ok().entity(v).build();
   275         }
   276         WebResource wr = base.path("games").path(id).
   277             queryParam("loginID", uuid).
   278             queryParam("player", user.getId()).
   279             queryParam("comment", comment);
   280         wr.put();
   281         
   282         return board(id);
   283     }
   284 
   285     @GET
   286     @Path("games/create")
   287     @Produces(MediaType.TEXT_HTML)
   288     public Response create(
   289         @QueryParam("white") String white,
   290         @QueryParam("black") String black
   291     ) {
   292         Viewable v = checkLogin();
   293         if (v != null) {
   294             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   295         }
   296 
   297         if (user.getId().equals(white) || user.getId().equals(black)) {
   298             Object obj =
   299                 base.path("games").
   300                 queryParam("loginID", uuid).
   301                 queryParam("white", white).
   302                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   303             return Response.ok(welcomeImpl()).build();
   304         } else {
   305             return Response.status(Response.Status.NOT_FOUND).
   306                 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
   307         }
   308     }
   309 
   310     private Viewable welcomeImpl(Object... args) {
   311         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   312         return viewable("index.fmt", got, args);
   313     }
   314 
   315 
   316     @GET
   317     @Path("options")
   318     public Response changeOptions(
   319         @QueryParam("email") String email,
   320         @QueryParam("language") String language
   321     ) {
   322         Viewable v = checkLogin();
   323         if (v != null) {
   324             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   325         }
   326 
   327         if (email != null) {
   328             UserInfo ui = base.path("users/" + user.getId()).
   329                 queryParam("loginID", uuid).
   330                 queryParam("name", "email").
   331                 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
   332         }
   333 
   334         if (language != null) {
   335             UserInfo ui = base.path("users/" + user.getId()).
   336                 queryParam("loginID", uuid).
   337                 queryParam("name", "language").
   338                 queryParam("value", language).
   339                 accept(MediaType.TEXT_XML).post(UserInfo.class);
   340         }
   341 
   342         return welcome(10);
   343     }
   344     
   345     //
   346     // start the server
   347     //
   348 
   349     public static void main(String[] args) throws Exception {
   350         int port = 9333;
   351         if (args.length > 1) {
   352             port = Integer.parseInt(args[0]);
   353         }
   354         String remoteAPI = args.length >= 2 ? args[1] : null;
   355 
   356         Locale.setDefault(Locale.ROOT);
   357 
   358         Callable<Void> r = startServers(port, remoteAPI);
   359 
   360         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   361             System.out.println("Hit enter to stop it...");
   362             System.in.read();
   363         } else {
   364             synchronized (UI.class) {
   365                 UI.class.wait();
   366             }
   367         }
   368         r.call();
   369         System.exit(0);
   370     }
   371 
   372     static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
   373         Client client = new Client();
   374 
   375         final HttpServer apiServer;
   376         if (remoteAPI == null) {
   377             throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
   378         } else {
   379             base = client.resource(new URI(remoteAPI));
   380             apiServer = null;
   381         }
   382 
   383         ResourceConfig rc = new PackagesResourceConfig(
   384             "cz.xelfi.quoridor.freemarkerdor"
   385         );
   386 
   387         final String baseUri = "http://localhost:" + port + "/";
   388         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   389         server.start();
   390         System.out.println("Quoridor started at port " + port);
   391 
   392         return new Callable<Void>() {
   393             public Void call() throws Exception {
   394                 if (apiServer != null) {
   395                     apiServer.stop(0);
   396                 }
   397                 server.stop(0);
   398                 return null;
   399             }
   400         };
   401     }
   402 
   403     private Viewable viewable(String page, Document doc, Object... more) {
   404         ResourceBundle rb = null;
   405         String lng = user == null ? null : user.getProperty("language"); // NOI18N
   406         if (lng != null) {
   407                 try {
   408                     Locale l = new Locale(lng);
   409                     rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   410                 } catch (MissingResourceException e) {
   411                     // OK
   412                 }
   413         }
   414         if (rb == null) {
   415             for (Locale l : headers.getAcceptableLanguages()) {
   416                 try {
   417                     rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   418                 } catch (MissingResourceException e) {
   419                     // OK
   420                 }
   421             }
   422         }
   423         if (rb == null) {
   424             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   425         }
   426 
   427         Map<String,Object> map = new HashMap<String,Object>();
   428         map.put("doc", doc);
   429         if (user != null) {
   430             map.put("user", user.getId());
   431             map.put("email", user.getProperty("email"));
   432         }
   433         map.put("bundle", rb);
   434         map.put("now", System.currentTimeMillis());
   435         map.put("version", version);
   436         for (int i = 0; i < more.length; i += 2) {
   437             map.put((String)more[i],more[i + 1]);
   438         }
   439         return new Viewable(page, map);
   440     }
   441 
   442 }