freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 29 Aug 2009 16:15:20 +0200
changeset 47 2b6c104e6a59
parent 46 71e4cf307c93
child 48 69e897fe8140
permissions -rw-r--r--
Using @FormParam to read data from forms
     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 javax.ws.rs.DefaultValue;
    48 import javax.ws.rs.FormParam;
    49 import javax.ws.rs.GET;
    50 import javax.ws.rs.POST;
    51 import javax.ws.rs.Path;
    52 import javax.ws.rs.PathParam;
    53 import javax.ws.rs.Produces;
    54 import javax.ws.rs.QueryParam;
    55 import javax.ws.rs.core.Context;
    56 import javax.ws.rs.core.HttpHeaders;
    57 import javax.ws.rs.core.MediaType;
    58 import javax.ws.rs.core.NewCookie;
    59 import javax.ws.rs.core.Response;
    60 import org.codehaus.jettison.json.JSONArray;
    61 import org.codehaus.jettison.json.JSONException;
    62 import org.codehaus.jettison.json.JSONObject;
    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 new 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         p.load(new FileInputStream(f));
    96         if (name != null && password.equals(p.getProperty(name))) {
    97             return Response.seeOther(new URI("/")).cookie(new NewCookie("login", name)).entity(welcomeImpl()).build();
    98         } else {
    99             Viewable v = new Viewable("login.fmt", "Invalid name or password: " + name);
   100             return Response.status(1).entity(v).build();
   101         }
   102     }
   103 
   104     @GET
   105     @Produces(MediaType.TEXT_HTML)
   106     public Viewable welcome() throws JSONException {
   107         Viewable v = checkLogin();
   108         if (v != null) {
   109             return v;
   110         }
   111         return welcomeImpl();
   112     }
   113 
   114     @GET
   115     @Path("games/{id}/")
   116     @Produces(MediaType.TEXT_HTML)
   117     public Viewable board(@PathParam("id") String id) throws JSONException {
   118         Viewable v = checkLogin();
   119         if (v != null) {
   120             return v;
   121         }
   122         Map<?,?> obj = (Map<?,?>)convert(base.path("games").path(id).accept(MediaType.APPLICATION_JSON_TYPE).get(JSONObject.class));
   123 
   124 
   125         return new Viewable("game.fmt", obj);
   126     }
   127 
   128     @GET
   129     @Path("games/{id}/move")
   130     @Produces(MediaType.TEXT_HTML)
   131     public Viewable move(
   132         @PathParam("id") String id,
   133         @QueryParam("type") String type,
   134         @QueryParam("direction") String direction,
   135         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   136         @QueryParam("column") @DefaultValue("") String column,
   137         @QueryParam("row") @DefaultValue("") String row
   138     ) throws JSONException {
   139         Viewable v = checkLogin();
   140         if (v != null) {
   141             return v;
   142         }
   143         WebResource wr = base.path("games").path(id).queryParam("player", user);
   144         if (type.equals("fence")) {
   145             wr.queryParam("move", direction.charAt(0) + column + row).put();
   146             return board(id);
   147         }
   148         if (type.equals("move")) {
   149             wr.queryParam("move", direction + directionNext).put();
   150             return board(id);
   151         }
   152         return board(id);
   153     }
   154 
   155     @GET
   156     @Path("games/create")
   157     @Produces(MediaType.TEXT_HTML)
   158     public Viewable create(
   159         @QueryParam("white") String white,
   160         @QueryParam("black") String black
   161     ) throws JSONException {
   162         Viewable v = checkLogin();
   163         if (v != null) {
   164             return v;
   165         }
   166         Object obj = convert(
   167             base.path("games").queryParam("white", white).
   168             queryParam("black", black).post(JSONObject.class)
   169         );
   170         Map<?,?> map = (Map<?,?>)obj;
   171         String id = (String)map.get("id");
   172         return board(id);
   173     }
   174 
   175 
   176     private static Object getJson(WebResource res) throws JSONException {
   177         return convert(res.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONArray.class));
   178     }
   179 
   180     private static Object convert(Object obj) throws JSONException {
   181         if (obj instanceof JSONArray) {
   182             JSONArray arr = (JSONArray)obj;
   183             final int length = arr.length();
   184             List<Object> res = new ArrayList<Object>(length);
   185             for (int i = 0; i < length; i++) {
   186                 res.add(convert(arr.get(i)));
   187             }
   188             return res;
   189         } else if (obj instanceof JSONObject) {
   190             JSONObject json = (JSONObject)obj;
   191             Map<Object,Object> map = new HashMap<Object,Object>(json.length() * 2 / 3);
   192             for (Iterator it = json.keys(); it.hasNext();) {
   193                 String key = (String)it.next();
   194                 map.put(key, convert(json.get(key)));
   195             }
   196             return map;
   197         } else {
   198             return obj;
   199         }
   200     }
   201 
   202     //
   203     // start the server
   204     //
   205 
   206     public static void main(String[] args) throws Exception {
   207         HttpServer api = Quoridor.start(9998);
   208         Client client = new Client();
   209         base = client.resource(new URI("http://localhost:9998/api/"));
   210 
   211         HttpServer s = start(9997);
   212         System.out.println(
   213             "Quoridor started at port 9997\n" + "Hit enter to stop it..."
   214         );
   215         System.in.read();
   216         s.stop(0);
   217         System.exit(0);
   218     }
   219 
   220     static HttpServer start(int port) throws IOException {
   221         final String baseUri = "http://localhost:" + port + "/";
   222         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
   223         HttpServer server = HttpServerFactory.create(baseUri, rc);
   224         server.start();
   225         return server;
   226     }
   227 
   228     private Viewable welcomeImpl() throws JSONException {
   229         Object obj = getJson(base.path("games"));
   230         return new Viewable("index.fmt", obj);
   231     }
   232 
   233 }