freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 12 Sep 2009 09:11:13 +0200
changeset 80 e03f660f0e0a
parent 79 89bca098e14e
child 82 9ac7acee7d9f
permissions -rw-r--r--
Moving all localized strings into one Bundle
     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 java.io.File;
    38 import java.io.FileInputStream;
    39 import java.io.IOException;
    40 import java.net.URI;
    41 import java.util.HashMap;
    42 import java.util.Locale;
    43 import java.util.Map;
    44 import java.util.MissingResourceException;
    45 import java.util.Properties;
    46 import java.util.ResourceBundle;
    47 import java.util.concurrent.Callable;
    48 import javax.ws.rs.DefaultValue;
    49 import javax.ws.rs.FormParam;
    50 import javax.ws.rs.GET;
    51 import javax.ws.rs.POST;
    52 import javax.ws.rs.Path;
    53 import javax.ws.rs.PathParam;
    54 import javax.ws.rs.Produces;
    55 import javax.ws.rs.QueryParam;
    56 import javax.ws.rs.core.Context;
    57 import javax.ws.rs.core.HttpHeaders;
    58 import javax.ws.rs.core.MediaType;
    59 import javax.ws.rs.core.NewCookie;
    60 import javax.ws.rs.core.Response;
    61 import org.w3c.dom.Document;
    62 
    63 /**
    64  *
    65  * @author Jaroslav Tulach <jtulach@netbeans.org>
    66  */
    67 @Path("/")
    68 public final class UI {
    69     private static WebResource base;
    70 
    71     @Context
    72     private HttpHeaders headers;
    73     private String user;
    74 
    75     public UI() {
    76     }
    77 
    78     private Viewable checkLogin() {
    79         if (headers.getCookies().containsKey("login")) {
    80             user = headers.getCookies().get("login").getValue();
    81             return null;
    82         }
    83         return viewable("login.fmt", null);
    84     }
    85 
    86     @POST
    87     @Path("login")
    88     @Produces(MediaType.TEXT_HTML)
    89     public Response login(
    90         @FormParam("name") String name, @FormParam("password") String password
    91     ) throws Exception {
    92         File f = new File(new File(System.getProperty("quoridor.dir")), "passwd");
    93         Properties p = new Properties();
    94         try {
    95             p.load(new FileInputStream(f));
    96         } catch (IOException ex) {
    97             ex.printStackTrace();
    98         }
    99         if (name != null && password.equals(p.getProperty(name))) {
   100             user = name;
   101             return Response.ok().cookie(new NewCookie("login", name)).entity(viewable("login.fmt", null)).build();
   102         } else {
   103             Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
   104             return Response.status(1).entity(v).build();
   105         }
   106     }
   107 
   108     @GET
   109     @Produces(MediaType.TEXT_HTML)
   110     public Viewable welcome() {
   111         Viewable v = checkLogin();
   112         if (v != null) {
   113             return v;
   114         }
   115         return welcomeImpl();
   116     }
   117 
   118     @GET
   119     @Path("games/{id}/")
   120     @Produces(MediaType.TEXT_HTML)
   121     public Viewable board(@PathParam("id") String id) {
   122         return board(id, null);
   123     }
   124     private Viewable board(@PathParam("id") String id, String msg) {
   125         Viewable v = checkLogin();
   126         if (v != null) {
   127             return v;
   128         }
   129         Document doc = base.path("games").path(id).accept(MediaType.TEXT_XML).get(Document.class);
   130         return viewable("game.fmt", doc, "message", msg);
   131     }
   132 
   133     @GET
   134     @Path("games/{id}/move")
   135     @Produces(MediaType.TEXT_HTML)
   136     public Viewable move(
   137         @PathParam("id") String id,
   138         @QueryParam("type") String type,
   139         @QueryParam("direction") String direction,
   140         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   141         @QueryParam("column") @DefaultValue("") String column,
   142         @QueryParam("row") @DefaultValue("") String row
   143     ) {
   144         Viewable v = checkLogin();
   145         if (v != null) {
   146             return v;
   147         }
   148         WebResource wr = base.path("games").path(id).queryParam("player", user);
   149         try {
   150             if (type.equals("resign")) {
   151                 wr.queryParam("move", "RESIGN").put();
   152                 return board(id);
   153             }
   154             if (type.equals("fence")) {
   155                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   156                 return board(id);
   157             }
   158             if (type.equals("move")) {
   159                 wr.queryParam("move", direction + directionNext).put();
   160                 return board(id);
   161             }
   162         } catch (UniformInterfaceException ex) {
   163             return board(id, "WRONG_MOVE");
   164         }
   165         return board(id);
   166     }
   167 
   168     @GET
   169     @Path("games/create")
   170     @Produces(MediaType.TEXT_HTML)
   171     public Response create(
   172         @QueryParam("white") String white,
   173         @QueryParam("black") String black
   174     ) {
   175         Viewable v = checkLogin();
   176         if (v != null) {
   177             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   178         }
   179 
   180         if (user.equals(white) || user.equals(black)) {
   181             Object obj =
   182                 base.path("games").queryParam("white", white).
   183                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   184             return Response.ok(welcomeImpl()).build();
   185         } else {
   186             return Response.status(Response.Status.NOT_FOUND).
   187                 entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
   188         }
   189     }
   190 
   191     private Viewable welcomeImpl(Object... args) {
   192         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   193         return viewable("index.fmt", got, args);
   194     }
   195 
   196     //
   197     // start the server
   198     //
   199 
   200     public static void main(String[] args) throws Exception {
   201         int port = 9998;
   202         if (args.length > 1) {
   203             port = Integer.parseInt(args[0]);
   204         }
   205 
   206 
   207         Callable<Void> r = startServers(port);
   208 
   209         if (args.length > 2 && args[1].equals("--kill")) {
   210             System.out.println("Hit enter to stop it...");
   211             System.in.read();
   212         } else {
   213             synchronized (UI.class) {
   214                 UI.class.wait();
   215             }
   216         }
   217         r.call();
   218         System.exit(0);
   219     }
   220 
   221     static Callable<Void> startServers(int port) throws Exception {
   222 
   223         if (System.getProperty("quoridor.dir") == null) {
   224             File home = new File(System.getProperty("user.home"));
   225             File quoridor = new File(home, ".quoridor");
   226             System.setProperty("quoridor.dir", quoridor.getPath());
   227         }
   228 
   229         ResourceConfig rc = new PackagesResourceConfig(
   230             "cz.xelfi.quoridor.webidor",
   231             "cz.xelfi.quoridor.freemarkerdor"
   232         );
   233 
   234         Client client = new Client();
   235         base = client.resource(new URI("http://localhost:" + port + "/api/"));
   236 
   237         final String baseUri = "http://localhost:" + port + "/";
   238         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   239         server.start();
   240         System.out.println("Quoridor started at port " + port);
   241 
   242         return new Callable<Void>() {
   243             public Void call() throws Exception {
   244                 server.stop(0);
   245                 return null;
   246             }
   247         };
   248     }
   249 
   250     private Viewable viewable(String page, Document doc, Object... more) {
   251         ResourceBundle rb = null;
   252         for (Locale l : headers.getAcceptableLanguages()) {
   253             try {
   254                 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   255             } catch (MissingResourceException e) {
   256                 // OK
   257             }
   258         }
   259         if (rb == null) {
   260             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   261         }
   262 
   263         Map<String,Object> map = new HashMap<String,Object>();
   264         map.put("doc", doc);
   265         map.put("user", user);
   266         map.put("bundle", rb);
   267         map.put("now", System.currentTimeMillis());
   268         for (int i = 0; i < more.length; i += 2) {
   269             map.put((String)more[i],more[i + 1]);
   270         }
   271         return new Viewable(page, map);
   272     }
   273 
   274 }