freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jtulach@netbeans.org>
Mon, 31 Aug 2009 22:44:47 +0200
changeset 54 f041b6570ff9
parent 50 1cce50d16bb5
child 55 830e0ba29c04
permissions -rw-r--r--
Removing anything related to JSON from the HTML layer, using natural freemarker's W3C DOM processing capabilities
     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.WebResource;
    31 import com.sun.jersey.api.container.httpserver.HttpServerFactory;
    32 import com.sun.jersey.api.core.PackagesResourceConfig;
    33 import com.sun.jersey.api.core.ResourceConfig;
    34 import com.sun.jersey.api.view.Viewable;
    35 import com.sun.net.httpserver.HttpServer;
    36 import cz.xelfi.quoridor.webidor.resources.Quoridor;
    37 import java.io.File;
    38 import java.io.FileInputStream;
    39 import java.io.IOException;
    40 import java.net.URI;
    41 import java.util.Properties;
    42 import java.util.concurrent.Callable;
    43 import javax.ws.rs.DefaultValue;
    44 import javax.ws.rs.FormParam;
    45 import javax.ws.rs.GET;
    46 import javax.ws.rs.POST;
    47 import javax.ws.rs.Path;
    48 import javax.ws.rs.PathParam;
    49 import javax.ws.rs.Produces;
    50 import javax.ws.rs.QueryParam;
    51 import javax.ws.rs.core.Context;
    52 import javax.ws.rs.core.HttpHeaders;
    53 import javax.ws.rs.core.MediaType;
    54 import javax.ws.rs.core.NewCookie;
    55 import javax.ws.rs.core.Response;
    56 import org.w3c.dom.Document;
    57 
    58 /**
    59  *
    60  * @author Jaroslav Tulach <jtulach@netbeans.org>
    61  */
    62 @Path("/")
    63 public final class UI {
    64     private static WebResource base;
    65 
    66     @Context
    67     private HttpHeaders headers;
    68     private String user;
    69 
    70     public UI() {
    71     }
    72 
    73     private Viewable checkLogin() {
    74         if (headers.getCookies().containsKey("login")) {
    75             user = headers.getCookies().get("login").getValue();
    76             return null;
    77         }
    78         return new Viewable("login.fmt", null);
    79     }
    80 
    81     @POST
    82     @Path("login")
    83     @Produces(MediaType.TEXT_HTML)
    84     public Response login(
    85         @FormParam("name") String name, @FormParam("password") String password
    86     ) throws Exception {
    87         File f = new File(new File(new File(System.getProperty("user.home")), ".quoridor"), "passwd");
    88         Properties p = new Properties();
    89         try {
    90             p.load(new FileInputStream(f));
    91         } catch (IOException ex) {
    92             ex.printStackTrace();
    93         }
    94         if (name != null && password.equals(p.getProperty(name))) {
    95             return Response.seeOther(new URI("/")).cookie(new NewCookie("login", name)).entity(welcomeImpl()).build();
    96         } else {
    97             Viewable v = new Viewable("login.fmt", "Invalid name or password: " + name);
    98             return Response.status(1).entity(v).build();
    99         }
   100     }
   101 
   102     @GET
   103     @Produces(MediaType.TEXT_HTML)
   104     public Viewable welcome() {
   105         Viewable v = checkLogin();
   106         if (v != null) {
   107             return v;
   108         }
   109         return welcomeImpl();
   110     }
   111 
   112     @GET
   113     @Path("games/{id}/")
   114     @Produces(MediaType.TEXT_HTML)
   115     public Viewable board(@PathParam("id") String id) {
   116         Viewable v = checkLogin();
   117         if (v != null) {
   118             return v;
   119         }
   120         Document doc = base.path("games").path(id).accept(MediaType.TEXT_XML).get(Document.class);
   121         return new Viewable("game.fmt", doc);
   122     }
   123 
   124     @GET
   125     @Path("games/{id}/move")
   126     @Produces(MediaType.TEXT_HTML)
   127     public Viewable move(
   128         @PathParam("id") String id,
   129         @QueryParam("type") String type,
   130         @QueryParam("direction") String direction,
   131         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   132         @QueryParam("column") @DefaultValue("") String column,
   133         @QueryParam("row") @DefaultValue("") String row
   134     ) {
   135         Viewable v = checkLogin();
   136         if (v != null) {
   137             return v;
   138         }
   139         WebResource wr = base.path("games").path(id).queryParam("player", user);
   140         if (type.equals("fence")) {
   141             wr.queryParam("move", direction.charAt(0) + column + row).put();
   142             return board(id);
   143         }
   144         if (type.equals("move")) {
   145             wr.queryParam("move", direction + directionNext).put();
   146             return board(id);
   147         }
   148         return board(id);
   149     }
   150 
   151     @GET
   152     @Path("games/create")
   153     @Produces(MediaType.TEXT_HTML)
   154     public Viewable create(
   155         @QueryParam("white") String white,
   156         @QueryParam("black") String black
   157     ) {
   158         Viewable v = checkLogin();
   159         if (v != null) {
   160             return v;
   161         }
   162         Object obj =
   163             base.path("games").queryParam("white", white).
   164             queryParam("black", black).post(Document.class);
   165         return welcome();
   166     }
   167 
   168     private Viewable welcomeImpl() {
   169         final Object got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
   170         return new Viewable("index.fmt", got);
   171     }
   172 
   173     //
   174     // start the server
   175     //
   176 
   177     public static void main(String[] args) throws Exception {
   178         Callable<Void> r = startServers();
   179 
   180         System.in.read();
   181         r.call();
   182         System.exit(0);
   183     }
   184 
   185     static Callable<Void> startServers() throws Exception {
   186         final HttpServer api = Quoridor.start(9998);
   187         Client client = new Client();
   188         base = client.resource(new URI("http://localhost:9998/api/"));
   189 
   190         final HttpServer s = start(9997);
   191         System.out.println(
   192             "Quoridor started at port 9997\n" + "Hit enter to stop it..."
   193         );
   194 
   195         return new Callable<Void>() {
   196             public Void call() throws Exception {
   197                 s.stop(0);
   198                 api.stop(0);
   199                 return null;
   200             }
   201         };
   202     }
   203 
   204     static HttpServer start(int port) throws IOException {
   205         final String baseUri = "http://localhost:" + port + "/";
   206         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
   207         HttpServer server = HttpServerFactory.create(baseUri, rc);
   208         server.start();
   209         return server;
   210     }
   211 
   212 }