freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 04 Sep 2009 23:02:23 +0200
changeset 59 fd7e8e705b75
parent 57 fa12b02023a0
child 68 33cf89760fab
permissions -rw-r--r--
Localization of the game
     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.webidor.resources.Quoridor;
    38 import java.io.File;
    39 import java.io.FileInputStream;
    40 import java.io.IOException;
    41 import java.net.URI;
    42 import java.util.HashMap;
    43 import java.util.Locale;
    44 import java.util.Map;
    45 import java.util.MissingResourceException;
    46 import java.util.Properties;
    47 import java.util.ResourceBundle;
    48 import java.util.concurrent.Callable;
    49 import javax.ws.rs.DefaultValue;
    50 import javax.ws.rs.FormParam;
    51 import javax.ws.rs.GET;
    52 import javax.ws.rs.POST;
    53 import javax.ws.rs.Path;
    54 import javax.ws.rs.PathParam;
    55 import javax.ws.rs.Produces;
    56 import javax.ws.rs.QueryParam;
    57 import javax.ws.rs.core.Context;
    58 import javax.ws.rs.core.HttpHeaders;
    59 import javax.ws.rs.core.MediaType;
    60 import javax.ws.rs.core.NewCookie;
    61 import javax.ws.rs.core.Response;
    62 import org.w3c.dom.Document;
    63 
    64 /**
    65  *
    66  * @author Jaroslav Tulach <jtulach@netbeans.org>
    67  */
    68 @Path("/")
    69 public final class UI {
    70     private static WebResource base;
    71 
    72     @Context
    73     private HttpHeaders headers;
    74     private String user;
    75 
    76     public UI() {
    77     }
    78 
    79     private Viewable checkLogin() {
    80         if (headers.getCookies().containsKey("login")) {
    81             user = headers.getCookies().get("login").getValue();
    82             return null;
    83         }
    84         return viewable("login.fmt", null);
    85     }
    86 
    87     @POST
    88     @Path("login")
    89     @Produces(MediaType.TEXT_HTML)
    90     public Response login(
    91         @FormParam("name") String name, @FormParam("password") String password
    92     ) throws Exception {
    93         File f = new File(new File(new File(System.getProperty("user.home")), ".quoridor"), "passwd");
    94         Properties p = new Properties();
    95         try {
    96             p.load(new FileInputStream(f));
    97         } catch (IOException ex) {
    98             ex.printStackTrace();
    99         }
   100         if (name != null && password.equals(p.getProperty(name))) {
   101             return Response.seeOther(new URI("/")).cookie(new NewCookie("login", name)).entity(welcomeImpl()).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("fence")) {
   151                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   152                 return board(id);
   153             }
   154             if (type.equals("move")) {
   155                 wr.queryParam("move", direction + directionNext).put();
   156                 return board(id);
   157             }
   158         } catch (UniformInterfaceException ex) {
   159             return board(id, "WRONG_MOVE");
   160         }
   161         return board(id);
   162     }
   163 
   164     @GET
   165     @Path("games/create")
   166     @Produces(MediaType.TEXT_HTML)
   167     public Viewable create(
   168         @QueryParam("white") String white,
   169         @QueryParam("black") String black
   170     ) {
   171         Viewable v = checkLogin();
   172         if (v != null) {
   173             return v;
   174         }
   175 
   176         if (user.equals(white) || user.equals(black)) {
   177             Object obj =
   178                 base.path("games").queryParam("white", white).
   179                 queryParam("black", black).post(Document.class);
   180             return welcomeImpl();
   181         } else {
   182             return welcomeImpl("message", "You (" + user + ") must be white or black!");
   183         }
   184     }
   185 
   186     private Viewable welcomeImpl(Object... args) {
   187         final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   188         return viewable("index.fmt", got, args);
   189     }
   190 
   191     //
   192     // start the server
   193     //
   194 
   195     public static void main(String[] args) throws Exception {
   196         Callable<Void> r = startServers();
   197 
   198         System.in.read();
   199         r.call();
   200         System.exit(0);
   201     }
   202 
   203     static Callable<Void> startServers() throws Exception {
   204         final HttpServer api = Quoridor.start(9998);
   205         Client client = new Client();
   206         base = client.resource(new URI("http://localhost:9998/api/"));
   207 
   208         final HttpServer s = start(9997);
   209         System.out.println(
   210             "Quoridor started at port 9997\n" + "Hit enter to stop it..."
   211         );
   212 
   213         return new Callable<Void>() {
   214             public Void call() throws Exception {
   215                 s.stop(0);
   216                 api.stop(0);
   217                 return null;
   218             }
   219         };
   220     }
   221 
   222     static HttpServer start(int port) throws IOException {
   223         final String baseUri = "http://localhost:" + port + "/";
   224         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
   225         HttpServer server = HttpServerFactory.create(baseUri, rc);
   226         server.start();
   227         return server;
   228     }
   229 
   230     private Viewable viewable(String page, Document doc, Object... more) {
   231         String bundle = page.split("\\.")[0];
   232 
   233         ResourceBundle rb = null;
   234         for (Locale l : headers.getAcceptableLanguages()) {
   235             try {
   236                 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI." + bundle, l);
   237             } catch (MissingResourceException e) {
   238                 // OK
   239             }
   240         }
   241         if (rb == null) {
   242             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI." + bundle, Locale.ENGLISH);
   243         }
   244 
   245         Map<String,Object> map = new HashMap<String,Object>();
   246         map.put("doc", doc);
   247         map.put("user", user);
   248         map.put("bundle", rb);
   249         for (int i = 0; i < more.length; i += 2) {
   250             map.put((String)more[i],more[i + 1]);
   251         }
   252         return new Viewable(page, map);
   253     }
   254 
   255 }