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