freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 30 Aug 2009 14:44:49 +0200
changeset 49 75074e02f345
parent 48 69e897fe8140
child 50 1cce50d16bb5
permissions -rw-r--r--
At least we are able to generate the index page
jtulach@41
     1
/*
jtulach@41
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jtulach@41
     3
 *
jtulach@41
     4
 * The contents of this file are subject to the terms of either the GNU
jtulach@41
     5
 * General Public License Version 2 only ("GPL") or the Common
jtulach@41
     6
 * Development and Distribution License("CDDL") (collectively, the
jtulach@41
     7
 * "License"). You may not use this file except in compliance with the
jtulach@41
     8
 * License. You can obtain a copy of the License at
jtulach@41
     9
 * http://www.netbeans.org/cddl-gplv2.html
jtulach@41
    10
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jtulach@41
    11
 * specific language governing permissions and limitations under the
jtulach@41
    12
 * License.  When distributing the software, include this License Header
jtulach@41
    13
 * Notice in each file and include the License file at
jtulach@41
    14
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
jtulach@41
    15
 * particular file as subject to the "Classpath" exception as provided
jtulach@41
    16
 * by Sun in the GPL Version 2 section of the License file that
jtulach@41
    17
 * accompanied this code. If applicable, add the following below the
jtulach@41
    18
 * License Header, with the fields enclosed by brackets [] replaced by
jtulach@41
    19
 * your own identifying information:
jtulach@41
    20
 * "Portions Copyrighted [year] [name of copyright owner]"
jtulach@41
    21
 *
jtulach@41
    22
 * Contributor(s):
jtulach@41
    23
 *
jtulach@41
    24
 * Portions Copyrighted 2009 Jaroslav Tulach
jtulach@41
    25
 */
jtulach@41
    26
jtulach@41
    27
package cz.xelfi.quoridor.freemarkerdor;
jtulach@41
    28
jtulach@41
    29
import com.sun.jersey.api.client.Client;
jtulach@41
    30
import com.sun.jersey.api.client.WebResource;
jtulach@41
    31
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
jtulach@41
    32
import com.sun.jersey.api.core.PackagesResourceConfig;
jtulach@41
    33
import com.sun.jersey.api.core.ResourceConfig;
jtulach@41
    34
import com.sun.jersey.api.view.Viewable;
jtulach@41
    35
import com.sun.net.httpserver.HttpServer;
jtulach@41
    36
import cz.xelfi.quoridor.webidor.resources.Quoridor;
jaroslav@46
    37
import java.io.File;
jaroslav@46
    38
import java.io.FileInputStream;
jtulach@41
    39
import java.io.IOException;
jtulach@41
    40
import java.net.URI;
jtulach@41
    41
import java.util.ArrayList;
jtulach@41
    42
import java.util.HashMap;
jtulach@41
    43
import java.util.Iterator;
jtulach@41
    44
import java.util.List;
jtulach@41
    45
import java.util.Map;
jaroslav@46
    46
import java.util.Properties;
jtulach@43
    47
import javax.ws.rs.DefaultValue;
jaroslav@47
    48
import javax.ws.rs.FormParam;
jtulach@41
    49
import javax.ws.rs.GET;
jaroslav@46
    50
import javax.ws.rs.POST;
jtulach@41
    51
import javax.ws.rs.Path;
jtulach@41
    52
import javax.ws.rs.PathParam;
jaroslav@46
    53
import javax.ws.rs.Produces;
jtulach@42
    54
import javax.ws.rs.QueryParam;
jtulach@42
    55
import javax.ws.rs.core.Context;
jtulach@42
    56
import javax.ws.rs.core.HttpHeaders;
jtulach@41
    57
import javax.ws.rs.core.MediaType;
jaroslav@46
    58
import javax.ws.rs.core.NewCookie;
jaroslav@46
    59
import javax.ws.rs.core.Response;
jtulach@41
    60
import org.codehaus.jettison.json.JSONArray;
jtulach@41
    61
import org.codehaus.jettison.json.JSONException;
jtulach@41
    62
import org.codehaus.jettison.json.JSONObject;
jaroslav@48
    63
import org.w3c.dom.Document;
jtulach@41
    64
jtulach@41
    65
/**
jtulach@41
    66
 *
jtulach@41
    67
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@41
    68
 */
jtulach@41
    69
@Path("/")
jtulach@41
    70
public final class UI {
jtulach@41
    71
    private static WebResource base;
jtulach@42
    72
jtulach@42
    73
    @Context
jtulach@42
    74
    private HttpHeaders headers;
jaroslav@46
    75
    private String user;
jtulach@42
    76
jtulach@41
    77
    public UI() {
jtulach@41
    78
    }
jtulach@41
    79
jaroslav@46
    80
    private Viewable checkLogin() {
jaroslav@46
    81
        if (headers.getCookies().containsKey("login")) {
jaroslav@46
    82
            user = headers.getCookies().get("login").getValue();
jaroslav@46
    83
            return null;
jaroslav@46
    84
        }
jaroslav@46
    85
        return new Viewable("login.fmt", null);
jaroslav@46
    86
    }
jaroslav@46
    87
jaroslav@46
    88
    @POST
jaroslav@46
    89
    @Path("login")
jaroslav@46
    90
    @Produces(MediaType.TEXT_HTML)
jaroslav@46
    91
    public Response login(
jaroslav@47
    92
        @FormParam("name") String name, @FormParam("password") String password
jaroslav@46
    93
    ) throws Exception {
jaroslav@46
    94
        File f = new File(new File(new File(System.getProperty("user.home")), ".quoridor"), "passwd");
jaroslav@46
    95
        Properties p = new Properties();
jaroslav@46
    96
        p.load(new FileInputStream(f));
jaroslav@46
    97
        if (name != null && password.equals(p.getProperty(name))) {
jaroslav@46
    98
            return Response.seeOther(new URI("/")).cookie(new NewCookie("login", name)).entity(welcomeImpl()).build();
jaroslav@46
    99
        } else {
jaroslav@46
   100
            Viewable v = new Viewable("login.fmt", "Invalid name or password: " + name);
jaroslav@46
   101
            return Response.status(1).entity(v).build();
jaroslav@46
   102
        }
jaroslav@46
   103
    }
jaroslav@46
   104
jtulach@41
   105
    @GET
jaroslav@46
   106
    @Produces(MediaType.TEXT_HTML)
jtulach@41
   107
    public Viewable welcome() throws JSONException {
jaroslav@46
   108
        Viewable v = checkLogin();
jaroslav@46
   109
        if (v != null) {
jaroslav@46
   110
            return v;
jtulach@42
   111
        }
jaroslav@46
   112
        return welcomeImpl();
jtulach@41
   113
    }
jtulach@41
   114
jtulach@41
   115
    @GET
jtulach@43
   116
    @Path("games/{id}/")
jaroslav@46
   117
    @Produces(MediaType.TEXT_HTML)
jtulach@41
   118
    public Viewable board(@PathParam("id") String id) throws JSONException {
jaroslav@46
   119
        Viewable v = checkLogin();
jaroslav@46
   120
        if (v != null) {
jaroslav@46
   121
            return v;
jaroslav@46
   122
        }
jaroslav@46
   123
        Map<?,?> obj = (Map<?,?>)convert(base.path("games").path(id).accept(MediaType.APPLICATION_JSON_TYPE).get(JSONObject.class));
jaroslav@46
   124
jaroslav@46
   125
jtulach@42
   126
        return new Viewable("game.fmt", obj);
jtulach@42
   127
    }
jtulach@41
   128
jtulach@42
   129
    @GET
jtulach@43
   130
    @Path("games/{id}/move")
jaroslav@46
   131
    @Produces(MediaType.TEXT_HTML)
jtulach@43
   132
    public Viewable move(
jtulach@43
   133
        @PathParam("id") String id,
jtulach@43
   134
        @QueryParam("type") String type,
jtulach@43
   135
        @QueryParam("direction") String direction,
jtulach@43
   136
        @QueryParam("direction-next") @DefaultValue("") String directionNext,
jtulach@43
   137
        @QueryParam("column") @DefaultValue("") String column,
jtulach@43
   138
        @QueryParam("row") @DefaultValue("") String row
jtulach@43
   139
    ) throws JSONException {
jaroslav@46
   140
        Viewable v = checkLogin();
jaroslav@46
   141
        if (v != null) {
jaroslav@46
   142
            return v;
jaroslav@46
   143
        }
jaroslav@46
   144
        WebResource wr = base.path("games").path(id).queryParam("player", user);
jtulach@43
   145
        if (type.equals("fence")) {
jaroslav@46
   146
            wr.queryParam("move", direction.charAt(0) + column + row).put();
jtulach@43
   147
            return board(id);
jtulach@43
   148
        }
jtulach@43
   149
        if (type.equals("move")) {
jaroslav@46
   150
            wr.queryParam("move", direction + directionNext).put();
jtulach@43
   151
            return board(id);
jtulach@43
   152
        }
jtulach@43
   153
        return board(id);
jtulach@43
   154
    }
jtulach@43
   155
jtulach@43
   156
    @GET
jtulach@42
   157
    @Path("games/create")
jaroslav@46
   158
    @Produces(MediaType.TEXT_HTML)
jtulach@42
   159
    public Viewable create(
jtulach@42
   160
        @QueryParam("white") String white,
jtulach@42
   161
        @QueryParam("black") String black
jtulach@42
   162
    ) throws JSONException {
jaroslav@46
   163
        Viewable v = checkLogin();
jaroslav@46
   164
        if (v != null) {
jaroslav@46
   165
            return v;
jaroslav@46
   166
        }
jtulach@42
   167
        Object obj = convert(
jtulach@42
   168
            base.path("games").queryParam("white", white).
jtulach@42
   169
            queryParam("black", black).post(JSONObject.class)
jtulach@42
   170
        );
jtulach@42
   171
        Map<?,?> map = (Map<?,?>)obj;
jtulach@42
   172
        String id = (String)map.get("id");
jtulach@42
   173
        return board(id);
jtulach@41
   174
    }
jtulach@41
   175
jtulach@41
   176
jtulach@41
   177
    private static Object convert(Object obj) throws JSONException {
jtulach@41
   178
        if (obj instanceof JSONArray) {
jtulach@41
   179
            JSONArray arr = (JSONArray)obj;
jtulach@41
   180
            final int length = arr.length();
jtulach@41
   181
            List<Object> res = new ArrayList<Object>(length);
jtulach@41
   182
            for (int i = 0; i < length; i++) {
jtulach@41
   183
                res.add(convert(arr.get(i)));
jtulach@41
   184
            }
jtulach@41
   185
            return res;
jtulach@41
   186
        } else if (obj instanceof JSONObject) {
jtulach@41
   187
            JSONObject json = (JSONObject)obj;
jtulach@41
   188
            Map<Object,Object> map = new HashMap<Object,Object>(json.length() * 2 / 3);
jtulach@41
   189
            for (Iterator it = json.keys(); it.hasNext();) {
jtulach@41
   190
                String key = (String)it.next();
jtulach@41
   191
                map.put(key, convert(json.get(key)));
jtulach@41
   192
            }
jtulach@41
   193
            return map;
jtulach@41
   194
        } else {
jtulach@41
   195
            return obj;
jtulach@41
   196
        }
jtulach@41
   197
    }
jtulach@41
   198
jtulach@41
   199
    //
jtulach@41
   200
    // start the server
jtulach@41
   201
    //
jtulach@41
   202
jtulach@41
   203
    public static void main(String[] args) throws Exception {
jtulach@41
   204
        HttpServer api = Quoridor.start(9998);
jtulach@41
   205
        Client client = new Client();
jtulach@41
   206
        base = client.resource(new URI("http://localhost:9998/api/"));
jtulach@41
   207
jtulach@41
   208
        HttpServer s = start(9997);
jtulach@41
   209
        System.out.println(
jtulach@41
   210
            "Quoridor started at port 9997\n" + "Hit enter to stop it..."
jtulach@41
   211
        );
jtulach@41
   212
        System.in.read();
jtulach@41
   213
        s.stop(0);
jtulach@41
   214
        System.exit(0);
jtulach@41
   215
    }
jtulach@41
   216
jtulach@41
   217
    static HttpServer start(int port) throws IOException {
jtulach@41
   218
        final String baseUri = "http://localhost:" + port + "/";
jtulach@41
   219
        ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
jtulach@41
   220
        HttpServer server = HttpServerFactory.create(baseUri, rc);
jtulach@41
   221
        server.start();
jtulach@41
   222
        return server;
jtulach@41
   223
    }
jtulach@41
   224
jaroslav@46
   225
    private Viewable welcomeImpl() throws JSONException {
jaroslav@49
   226
        final Object got = base.path("games").accept(MediaType.APPLICATION_JSON_TYPE).get(JSONArray.class);
jaroslav@49
   227
        List<?> obj = (List<?>)convert(got);
jaroslav@46
   228
        return new Viewable("index.fmt", obj);
jaroslav@46
   229
    }
jaroslav@46
   230
jtulach@41
   231
}