freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 30 Aug 2009 14:56:32 +0200
changeset 50 1cce50d16bb5
parent 49 75074e02f345
child 54 f041b6570ff9
permissions -rw-r--r--
Test to verify that we are able to read the main page
     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.ArrayList;
    42 import java.util.HashMap;
    43 import java.util.Iterator;
    44 import java.util.List;
    45 import java.util.Map;
    46 import java.util.Properties;
    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.codehaus.jettison.json.JSONArray;
    62 import org.codehaus.jettison.json.JSONException;
    63 import org.codehaus.jettison.json.JSONObject;
    64 import org.w3c.dom.Document;
    65 
    66 /**
    67  *
    68  * @author Jaroslav Tulach <jtulach@netbeans.org>
    69  */
    70 @Path("/")
    71 public final class UI {
    72     private static WebResource base;
    73 
    74     @Context
    75     private HttpHeaders headers;
    76     private String user;
    77 
    78     public UI() {
    79     }
    80 
    81     private Viewable checkLogin() {
    82         if (headers.getCookies().containsKey("login")) {
    83             user = headers.getCookies().get("login").getValue();
    84             return null;
    85         }
    86         return new Viewable("login.fmt", null);
    87     }
    88 
    89     @POST
    90     @Path("login")
    91     @Produces(MediaType.TEXT_HTML)
    92     public Response login(
    93         @FormParam("name") String name, @FormParam("password") String password
    94     ) throws Exception {
    95         File f = new File(new File(new File(System.getProperty("user.home")), ".quoridor"), "passwd");
    96         Properties p = new Properties();
    97         p.load(new FileInputStream(f));
    98         if (name != null && password.equals(p.getProperty(name))) {
    99             return Response.seeOther(new URI("/")).cookie(new NewCookie("login", name)).entity(welcomeImpl()).build();
   100         } else {
   101             Viewable v = new Viewable("login.fmt", "Invalid name or password: " + name);
   102             return Response.status(1).entity(v).build();
   103         }
   104     }
   105 
   106     @GET
   107     @Produces(MediaType.TEXT_HTML)
   108     public Viewable welcome() throws JSONException {
   109         Viewable v = checkLogin();
   110         if (v != null) {
   111             return v;
   112         }
   113         return welcomeImpl();
   114     }
   115 
   116     @GET
   117     @Path("games/{id}/")
   118     @Produces(MediaType.TEXT_HTML)
   119     public Viewable board(@PathParam("id") String id) throws JSONException {
   120         Viewable v = checkLogin();
   121         if (v != null) {
   122             return v;
   123         }
   124         Map<?,?> obj = (Map<?,?>)convert(base.path("games").path(id).accept(MediaType.APPLICATION_JSON_TYPE).get(JSONObject.class));
   125 
   126 
   127         return new Viewable("game.fmt", obj);
   128     }
   129 
   130     @GET
   131     @Path("games/{id}/move")
   132     @Produces(MediaType.TEXT_HTML)
   133     public Viewable move(
   134         @PathParam("id") String id,
   135         @QueryParam("type") String type,
   136         @QueryParam("direction") String direction,
   137         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   138         @QueryParam("column") @DefaultValue("") String column,
   139         @QueryParam("row") @DefaultValue("") String row
   140     ) throws JSONException {
   141         Viewable v = checkLogin();
   142         if (v != null) {
   143             return v;
   144         }
   145         WebResource wr = base.path("games").path(id).queryParam("player", user);
   146         if (type.equals("fence")) {
   147             wr.queryParam("move", direction.charAt(0) + column + row).put();
   148             return board(id);
   149         }
   150         if (type.equals("move")) {
   151             wr.queryParam("move", direction + directionNext).put();
   152             return board(id);
   153         }
   154         return board(id);
   155     }
   156 
   157     @GET
   158     @Path("games/create")
   159     @Produces(MediaType.TEXT_HTML)
   160     public Viewable create(
   161         @QueryParam("white") String white,
   162         @QueryParam("black") String black
   163     ) throws JSONException {
   164         Viewable v = checkLogin();
   165         if (v != null) {
   166             return v;
   167         }
   168         Object obj = convert(
   169             base.path("games").queryParam("white", white).
   170             queryParam("black", black).post(JSONObject.class)
   171         );
   172         Map<?,?> map = (Map<?,?>)obj;
   173         String id = (String)map.get("id");
   174         return board(id);
   175     }
   176 
   177 
   178     private static Object convert(Object obj) throws JSONException {
   179         if (obj instanceof JSONArray) {
   180             JSONArray arr = (JSONArray)obj;
   181             final int length = arr.length();
   182             List<Object> res = new ArrayList<Object>(length);
   183             for (int i = 0; i < length; i++) {
   184                 res.add(convert(arr.get(i)));
   185             }
   186             return res;
   187         } else if (obj instanceof JSONObject) {
   188             JSONObject json = (JSONObject)obj;
   189             Map<Object,Object> map = new HashMap<Object,Object>(json.length() * 2 / 3);
   190             for (Iterator it = json.keys(); it.hasNext();) {
   191                 String key = (String)it.next();
   192                 map.put(key, convert(json.get(key)));
   193             }
   194             return map;
   195         } else {
   196             return obj;
   197         }
   198     }
   199 
   200     //
   201     // start the server
   202     //
   203 
   204     public static void main(String[] args) throws Exception {
   205         Callable<Void> r = startServers();
   206 
   207         System.in.read();
   208         r.call();
   209         System.exit(0);
   210     }
   211 
   212     static Callable<Void> startServers() throws Exception {
   213         final HttpServer api = Quoridor.start(9998);
   214         Client client = new Client();
   215         base = client.resource(new URI("http://localhost:9998/api/"));
   216 
   217         final HttpServer s = start(9997);
   218         System.out.println(
   219             "Quoridor started at port 9997\n" + "Hit enter to stop it..."
   220         );
   221 
   222         return new Callable<Void>() {
   223             public Void call() throws Exception {
   224                 s.stop(0);
   225                 api.stop(0);
   226                 return null;
   227             }
   228         };
   229     }
   230 
   231     static HttpServer start(int port) throws IOException {
   232         final String baseUri = "http://localhost:" + port + "/";
   233         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
   234         HttpServer server = HttpServerFactory.create(baseUri, rc);
   235         server.start();
   236         return server;
   237     }
   238 
   239     private Viewable welcomeImpl() throws JSONException {
   240         final Object got = base.path("games").accept(MediaType.APPLICATION_JSON_TYPE).get(JSONArray.class);
   241         List<?> obj = (List<?>)convert(got);
   242         return new Viewable("index.fmt", obj);
   243     }
   244 
   245 }