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