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