freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Sep 2009 14:38:29 +0200
changeset 100 8b899ed24f9f
parent 99 fed05535725f
child 101 c7244cdd143e
permissions -rw-r--r--
Browsable history of each game
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;
jaroslav@56
    30
import com.sun.jersey.api.client.UniformInterfaceException;
jtulach@41
    31
import com.sun.jersey.api.client.WebResource;
jtulach@41
    32
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
jtulach@41
    33
import com.sun.jersey.api.core.PackagesResourceConfig;
jtulach@41
    34
import com.sun.jersey.api.core.ResourceConfig;
jtulach@41
    35
import com.sun.jersey.api.view.Viewable;
jtulach@41
    36
import com.sun.net.httpserver.HttpServer;
jaroslav@99
    37
import cz.xelfi.quoridor.Board;
jaroslav@99
    38
import cz.xelfi.quoridor.IllegalPositionException;
jaroslav@46
    39
import java.io.File;
jaroslav@88
    40
import java.io.IOException;
jaroslav@88
    41
import java.io.InputStream;
jtulach@41
    42
import java.net.URI;
jaroslav@55
    43
import java.util.HashMap;
jaroslav@59
    44
import java.util.Locale;
jaroslav@55
    45
import java.util.Map;
jaroslav@59
    46
import java.util.MissingResourceException;
jaroslav@88
    47
import java.util.Properties;
jaroslav@59
    48
import java.util.ResourceBundle;
jaroslav@50
    49
import java.util.concurrent.Callable;
jtulach@43
    50
import javax.ws.rs.DefaultValue;
jaroslav@47
    51
import javax.ws.rs.FormParam;
jtulach@41
    52
import javax.ws.rs.GET;
jaroslav@46
    53
import javax.ws.rs.POST;
jtulach@41
    54
import javax.ws.rs.Path;
jtulach@41
    55
import javax.ws.rs.PathParam;
jaroslav@46
    56
import javax.ws.rs.Produces;
jtulach@42
    57
import javax.ws.rs.QueryParam;
jtulach@42
    58
import javax.ws.rs.core.Context;
jtulach@42
    59
import javax.ws.rs.core.HttpHeaders;
jtulach@41
    60
import javax.ws.rs.core.MediaType;
jaroslav@46
    61
import javax.ws.rs.core.NewCookie;
jaroslav@46
    62
import javax.ws.rs.core.Response;
jaroslav@99
    63
import org.openide.util.Exceptions;
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 {
jaroslav@88
    72
    private static final String version;
jaroslav@88
    73
    static {
jaroslav@88
    74
        Properties p = new Properties();
jaroslav@88
    75
        try {
jaroslav@88
    76
            InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/org.apidesign/freemarkerdor/pom.properties"); // NOI18N
jaroslav@88
    77
            if (is != null) {
jaroslav@88
    78
                p.load(is);
jaroslav@88
    79
            }
jaroslav@88
    80
        } catch (IOException ex) {
jaroslav@88
    81
            ex.printStackTrace();
jaroslav@88
    82
        }
jaroslav@88
    83
        version = p.getProperty("version", "unknown"); // NOI18N
jaroslav@88
    84
    }
jtulach@41
    85
    private static WebResource base;
jtulach@42
    86
jtulach@42
    87
    @Context
jtulach@42
    88
    private HttpHeaders headers;
jaroslav@46
    89
    private String user;
jtulach@82
    90
    private String uuid;
jtulach@42
    91
jtulach@41
    92
    public UI() {
jtulach@41
    93
    }
jtulach@41
    94
jaroslav@46
    95
    private Viewable checkLogin() {
jaroslav@46
    96
        if (headers.getCookies().containsKey("login")) {
jtulach@83
    97
            String id = headers.getCookies().get("login").getValue();
jaroslav@85
    98
            String us;
jaroslav@85
    99
            try {
jaroslav@85
   100
                us = base.path("login").queryParam("id", id).
jaroslav@85
   101
                    accept(MediaType.TEXT_PLAIN).get(String.class);
jaroslav@85
   102
            } catch (UniformInterfaceException ex) {
jaroslav@85
   103
                ex.printStackTrace();
jaroslav@85
   104
                us = "";
jaroslav@85
   105
            }
jtulach@83
   106
            if (us.length() > 0) {
jtulach@83
   107
                user = us;
jtulach@83
   108
                uuid = id;
jtulach@83
   109
                return null;
jtulach@83
   110
            }
jaroslav@46
   111
        }
jaroslav@56
   112
        return viewable("login.fmt", null);
jaroslav@46
   113
    }
jaroslav@46
   114
jaroslav@46
   115
    @POST
jaroslav@46
   116
    @Path("login")
jaroslav@46
   117
    @Produces(MediaType.TEXT_HTML)
jaroslav@46
   118
    public Response login(
jaroslav@47
   119
        @FormParam("name") String name, @FormParam("password") String password
jaroslav@46
   120
    ) throws Exception {
jtulach@82
   121
        uuid = base.path("login").queryParam("name", name).queryParam("password", password).
jtulach@82
   122
            accept(MediaType.TEXT_PLAIN).put(String.class);
jtulach@82
   123
        if (uuid != null) {
jaroslav@70
   124
            user = name;
jtulach@82
   125
            return Response.ok().cookie(new NewCookie("login", uuid)).entity(viewable("login.fmt", null)).build();
jaroslav@46
   126
        } else {
jaroslav@56
   127
            Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
jaroslav@46
   128
            return Response.status(1).entity(v).build();
jaroslav@46
   129
        }
jaroslav@46
   130
    }
jaroslav@46
   131
jtulach@41
   132
    @GET
jaroslav@46
   133
    @Produces(MediaType.TEXT_HTML)
jtulach@54
   134
    public Viewable welcome() {
jaroslav@46
   135
        Viewable v = checkLogin();
jaroslav@46
   136
        if (v != null) {
jaroslav@46
   137
            return v;
jtulach@42
   138
        }
jaroslav@46
   139
        return welcomeImpl();
jtulach@41
   140
    }
jtulach@41
   141
jaroslav@95
   142
    private Viewable board(String id) {
jaroslav@100
   143
        return board(id, "", null);
jaroslav@95
   144
    }
jtulach@41
   145
    @GET
jtulach@43
   146
    @Path("games/{id}/")
jaroslav@46
   147
    @Produces(MediaType.TEXT_HTML)
jaroslav@100
   148
    public Viewable board(
jaroslav@100
   149
        @PathParam("id") String id,
jaroslav@100
   150
        @QueryParam("format") @DefaultValue("") String format,
jaroslav@100
   151
        @QueryParam("move") @DefaultValue("-1") String move
jaroslav@100
   152
    ) {
jaroslav@100
   153
        return board(id, null, format, move);
jaroslav@56
   154
    }
jaroslav@100
   155
    private Viewable board(@PathParam("id") String id, String msg, String format, String m) {
jaroslav@46
   156
        Viewable v = checkLogin();
jaroslav@46
   157
        if (v != null) {
jaroslav@46
   158
            return v;
jaroslav@46
   159
        }
jaroslav@100
   160
        int move;
jaroslav@100
   161
        try {
jaroslav@100
   162
            move = Integer.parseInt(m);
jaroslav@100
   163
        } catch (NumberFormatException ex) {
jaroslav@100
   164
            move = -1;
jaroslav@100
   165
        }
jaroslav@100
   166
        WebResource url = base.path("games").path(id);
jaroslav@100
   167
        if (move >= 0) {
jaroslav@100
   168
            url = url.queryParam("move", "" + move);
jaroslav@100
   169
        }
jaroslav@100
   170
        Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@99
   171
        Board b;
jaroslav@99
   172
        try {
jaroslav@99
   173
            b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
jaroslav@99
   174
        } catch (IllegalPositionException ex) {
jaroslav@99
   175
            Exceptions.printStackTrace(ex);
jaroslav@99
   176
            b = Board.empty();
jaroslav@99
   177
        }
jaroslav@99
   178
        return viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
jtulach@42
   179
    }
jtulach@41
   180
jtulach@42
   181
    @GET
jtulach@43
   182
    @Path("games/{id}/move")
jaroslav@46
   183
    @Produces(MediaType.TEXT_HTML)
jtulach@43
   184
    public Viewable move(
jtulach@43
   185
        @PathParam("id") String id,
jtulach@43
   186
        @QueryParam("type") String type,
jtulach@43
   187
        @QueryParam("direction") String direction,
jtulach@43
   188
        @QueryParam("direction-next") @DefaultValue("") String directionNext,
jtulach@43
   189
        @QueryParam("column") @DefaultValue("") String column,
jtulach@43
   190
        @QueryParam("row") @DefaultValue("") String row
jtulach@54
   191
    ) {
jaroslav@46
   192
        Viewable v = checkLogin();
jaroslav@46
   193
        if (v != null) {
jaroslav@46
   194
            return v;
jaroslav@46
   195
        }
jtulach@82
   196
        WebResource wr = base.path("games").path(id).
jtulach@82
   197
            queryParam("loginID", uuid).
jtulach@82
   198
            queryParam("player", user);
jaroslav@56
   199
        try {
jtulach@75
   200
            if (type.equals("resign")) {
jtulach@75
   201
                wr.queryParam("move", "RESIGN").put();
jtulach@75
   202
                return board(id);
jtulach@75
   203
            }
jaroslav@56
   204
            if (type.equals("fence")) {
jaroslav@56
   205
                wr.queryParam("move", direction.charAt(0) + column + row).put();
jaroslav@56
   206
                return board(id);
jaroslav@56
   207
            }
jaroslav@56
   208
            if (type.equals("move")) {
jaroslav@56
   209
                wr.queryParam("move", direction + directionNext).put();
jaroslav@56
   210
                return board(id);
jaroslav@56
   211
            }
jaroslav@56
   212
        } catch (UniformInterfaceException ex) {
jaroslav@100
   213
            return board(id, "WRONG_MOVE", "-1");
jtulach@43
   214
        }
jtulach@43
   215
        return board(id);
jtulach@43
   216
    }
jtulach@43
   217
jtulach@43
   218
    @GET
jtulach@42
   219
    @Path("games/create")
jaroslav@46
   220
    @Produces(MediaType.TEXT_HTML)
jaroslav@73
   221
    public Response create(
jtulach@42
   222
        @QueryParam("white") String white,
jtulach@42
   223
        @QueryParam("black") String black
jtulach@54
   224
    ) {
jaroslav@46
   225
        Viewable v = checkLogin();
jaroslav@46
   226
        if (v != null) {
jaroslav@73
   227
            return Response.status(Response.Status.FORBIDDEN).entity(v).build();
jaroslav@46
   228
        }
jaroslav@57
   229
jaroslav@57
   230
        if (user.equals(white) || user.equals(black)) {
jaroslav@57
   231
            Object obj =
jtulach@82
   232
                base.path("games").
jtulach@82
   233
                queryParam("loginID", uuid).
jtulach@82
   234
                queryParam("white", white).
jaroslav@73
   235
                queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
jaroslav@73
   236
            return Response.ok(welcomeImpl()).build();
jaroslav@57
   237
        } else {
jaroslav@73
   238
            return Response.status(Response.Status.NOT_FOUND).
jaroslav@73
   239
                entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
jaroslav@57
   240
        }
jtulach@41
   241
    }
jtulach@41
   242
jaroslav@57
   243
    private Viewable welcomeImpl(Object... args) {
jaroslav@56
   244
        final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@57
   245
        return viewable("index.fmt", got, args);
jtulach@41
   246
    }
jtulach@41
   247
jtulach@41
   248
    //
jtulach@41
   249
    // start the server
jtulach@41
   250
    //
jtulach@41
   251
jtulach@41
   252
    public static void main(String[] args) throws Exception {
jaroslav@68
   253
        int port = 9998;
jaroslav@68
   254
        if (args.length > 1) {
jaroslav@68
   255
            port = Integer.parseInt(args[0]);
jaroslav@68
   256
        }
jaroslav@50
   257
jaroslav@68
   258
jaroslav@68
   259
        Callable<Void> r = startServers(port);
jaroslav@68
   260
jaroslav@97
   261
        if (args.length < 2 || !args[1].equals("--kill")) {
jaroslav@68
   262
            System.out.println("Hit enter to stop it...");
jaroslav@68
   263
            System.in.read();
jaroslav@68
   264
        } else {
jaroslav@68
   265
            synchronized (UI.class) {
jaroslav@68
   266
                UI.class.wait();
jaroslav@68
   267
            }
jaroslav@68
   268
        }
jaroslav@50
   269
        r.call();
jaroslav@50
   270
        System.exit(0);
jaroslav@50
   271
    }
jaroslav@50
   272
jaroslav@68
   273
    static Callable<Void> startServers(int port) throws Exception {
jaroslav@72
   274
jaroslav@73
   275
        if (System.getProperty("quoridor.dir") == null) {
jaroslav@73
   276
            File home = new File(System.getProperty("user.home"));
jaroslav@73
   277
            File quoridor = new File(home, ".quoridor");
jaroslav@73
   278
            System.setProperty("quoridor.dir", quoridor.getPath());
jaroslav@73
   279
        }
jaroslav@72
   280
jaroslav@72
   281
        ResourceConfig rc = new PackagesResourceConfig(
jaroslav@72
   282
            "cz.xelfi.quoridor.webidor",
jaroslav@72
   283
            "cz.xelfi.quoridor.freemarkerdor"
jaroslav@72
   284
        );
jaroslav@72
   285
jtulach@41
   286
        Client client = new Client();
jaroslav@72
   287
        base = client.resource(new URI("http://localhost:" + port + "/api/"));
jtulach@41
   288
jaroslav@72
   289
        final String baseUri = "http://localhost:" + port + "/";
jaroslav@72
   290
        final HttpServer server = HttpServerFactory.create(baseUri, rc);
jaroslav@72
   291
        server.start();
jaroslav@68
   292
        System.out.println("Quoridor started at port " + port);
jaroslav@50
   293
jaroslav@50
   294
        return new Callable<Void>() {
jaroslav@50
   295
            public Void call() throws Exception {
jaroslav@72
   296
                server.stop(0);
jaroslav@50
   297
                return null;
jaroslav@50
   298
            }
jaroslav@50
   299
        };
jtulach@41
   300
    }
jtulach@41
   301
jaroslav@56
   302
    private Viewable viewable(String page, Document doc, Object... more) {
jaroslav@59
   303
        ResourceBundle rb = null;
jaroslav@59
   304
        for (Locale l : headers.getAcceptableLanguages()) {
jaroslav@59
   305
            try {
jtulach@80
   306
                rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
jaroslav@59
   307
            } catch (MissingResourceException e) {
jaroslav@59
   308
                // OK
jaroslav@59
   309
            }
jaroslav@59
   310
        }
jaroslav@59
   311
        if (rb == null) {
jtulach@80
   312
            rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
jaroslav@59
   313
        }
jaroslav@59
   314
jaroslav@56
   315
        Map<String,Object> map = new HashMap<String,Object>();
jaroslav@56
   316
        map.put("doc", doc);
jaroslav@56
   317
        map.put("user", user);
jaroslav@59
   318
        map.put("bundle", rb);
jtulach@78
   319
        map.put("now", System.currentTimeMillis());
jaroslav@88
   320
        map.put("version", version);
jaroslav@56
   321
        for (int i = 0; i < more.length; i += 2) {
jaroslav@56
   322
            map.put((String)more[i],more[i + 1]);
jaroslav@56
   323
        }
jaroslav@56
   324
        return new Viewable(page, map);
jaroslav@56
   325
    }
jaroslav@56
   326
jtulach@41
   327
}