freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 18 Oct 2009 15:48:47 +0200
changeset 124 90371f3eb106
parent 122 e0ecef0c421b
child 126 e905cd9b1e4a
permissions -rw-r--r--
Removing /api prefix from the webidor server
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@121
    39
import cz.xelfi.quoridor.webidor.resources.Quoridor;
jaroslav@105
    40
import java.awt.Image;
jaroslav@88
    41
import java.io.IOException;
jaroslav@88
    42
import java.io.InputStream;
jtulach@41
    43
import java.net.URI;
jaroslav@55
    44
import java.util.HashMap;
jaroslav@59
    45
import java.util.Locale;
jaroslav@55
    46
import java.util.Map;
jaroslav@59
    47
import java.util.MissingResourceException;
jaroslav@88
    48
import java.util.Properties;
jaroslav@59
    49
import java.util.ResourceBundle;
jaroslav@50
    50
import java.util.concurrent.Callable;
jtulach@43
    51
import javax.ws.rs.DefaultValue;
jaroslav@47
    52
import javax.ws.rs.FormParam;
jtulach@41
    53
import javax.ws.rs.GET;
jaroslav@46
    54
import javax.ws.rs.POST;
jtulach@41
    55
import javax.ws.rs.Path;
jtulach@41
    56
import javax.ws.rs.PathParam;
jaroslav@46
    57
import javax.ws.rs.Produces;
jtulach@42
    58
import javax.ws.rs.QueryParam;
jtulach@42
    59
import javax.ws.rs.core.Context;
jaroslav@101
    60
import javax.ws.rs.core.Cookie;
jtulach@42
    61
import javax.ws.rs.core.HttpHeaders;
jtulach@41
    62
import javax.ws.rs.core.MediaType;
jaroslav@46
    63
import javax.ws.rs.core.NewCookie;
jaroslav@46
    64
import javax.ws.rs.core.Response;
jaroslav@101
    65
import javax.ws.rs.core.Response.ResponseBuilder;
jaroslav@99
    66
import org.openide.util.Exceptions;
jaroslav@48
    67
import org.w3c.dom.Document;
jtulach@41
    68
jtulach@41
    69
/**
jtulach@41
    70
 *
jtulach@41
    71
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@41
    72
 */
jtulach@41
    73
@Path("/")
jtulach@41
    74
public final class UI {
jaroslav@88
    75
    private static final String version;
jaroslav@88
    76
    static {
jaroslav@88
    77
        Properties p = new Properties();
jaroslav@88
    78
        try {
jaroslav@88
    79
            InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/org.apidesign/freemarkerdor/pom.properties"); // NOI18N
jaroslav@88
    80
            if (is != null) {
jaroslav@88
    81
                p.load(is);
jaroslav@88
    82
            }
jaroslav@88
    83
        } catch (IOException ex) {
jaroslav@88
    84
            ex.printStackTrace();
jaroslav@88
    85
        }
jaroslav@88
    86
        version = p.getProperty("version", "unknown"); // NOI18N
jaroslav@88
    87
    }
jtulach@41
    88
    private static WebResource base;
jtulach@42
    89
jtulach@42
    90
    @Context
jtulach@42
    91
    private HttpHeaders headers;
jaroslav@46
    92
    private String user;
jtulach@82
    93
    private String uuid;
jtulach@42
    94
jtulach@41
    95
    public UI() {
jtulach@41
    96
    }
jtulach@41
    97
jaroslav@46
    98
    private Viewable checkLogin() {
jaroslav@101
    99
        Cookie cookie = headers.getCookies().get("login");
jaroslav@101
   100
        if (cookie != null) {
jaroslav@101
   101
            String id = cookie.getValue();
jaroslav@85
   102
            String us;
jaroslav@85
   103
            try {
jaroslav@85
   104
                us = base.path("login").queryParam("id", id).
jaroslav@85
   105
                    accept(MediaType.TEXT_PLAIN).get(String.class);
jaroslav@85
   106
            } catch (UniformInterfaceException ex) {
jaroslav@85
   107
                ex.printStackTrace();
jaroslav@85
   108
                us = "";
jaroslav@85
   109
            }
jtulach@83
   110
            if (us.length() > 0) {
jtulach@83
   111
                user = us;
jtulach@83
   112
                uuid = id;
jtulach@83
   113
                return null;
jtulach@83
   114
            }
jaroslav@46
   115
        }
jaroslav@56
   116
        return viewable("login.fmt", null);
jaroslav@46
   117
    }
jaroslav@46
   118
jaroslav@46
   119
    @POST
jaroslav@46
   120
    @Path("login")
jaroslav@46
   121
    @Produces(MediaType.TEXT_HTML)
jaroslav@46
   122
    public Response login(
jaroslav@47
   123
        @FormParam("name") String name, @FormParam("password") String password
jaroslav@46
   124
    ) throws Exception {
jtulach@82
   125
        uuid = base.path("login").queryParam("name", name).queryParam("password", password).
jtulach@82
   126
            accept(MediaType.TEXT_PLAIN).put(String.class);
jtulach@82
   127
        if (uuid != null) {
jaroslav@70
   128
            user = name;
jaroslav@101
   129
            NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
jaroslav@101
   130
            return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
jaroslav@46
   131
        } else {
jaroslav@56
   132
            Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
jaroslav@46
   133
            return Response.status(1).entity(v).build();
jaroslav@46
   134
        }
jaroslav@46
   135
    }
jaroslav@46
   136
jtulach@41
   137
    @GET
jaroslav@46
   138
    @Produces(MediaType.TEXT_HTML)
jaroslav@119
   139
    public Viewable welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
jaroslav@46
   140
        Viewable v = checkLogin();
jaroslav@46
   141
        if (v != null) {
jaroslav@46
   142
            return v;
jtulach@42
   143
        }
jaroslav@119
   144
        return welcomeImpl("maxItems", maxItems);
jtulach@41
   145
    }
jtulach@41
   146
jaroslav@105
   147
    @GET
jaroslav@105
   148
    @Path("games/{id}.png")
jaroslav@105
   149
    @Produces("image/png")
jaroslav@105
   150
    public Image getBoardImage(
jaroslav@105
   151
        @PathParam("id") String id,
jaroslav@105
   152
        @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
jaroslav@105
   153
        @QueryParam("move") @DefaultValue("-1") int move
jaroslav@105
   154
    ) throws IllegalPositionException {
jaroslav@105
   155
        WebResource wr = base.path("games").path(id);
jaroslav@105
   156
        if (move != -1) {
jaroslav@106
   157
            wr = wr.queryParam("move", "" + move);
jaroslav@105
   158
        }
jaroslav@105
   159
        String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
jaroslav@105
   160
        Board b = Board.valueOf(txt);
jaroslav@105
   161
        return BoardImage.draw(b, fieldSize);
jaroslav@105
   162
    }
jaroslav@105
   163
jaroslav@105
   164
jaroslav@101
   165
    private Response board(String id) {
jaroslav@100
   166
        return board(id, "", null);
jaroslav@95
   167
    }
jtulach@41
   168
    @GET
jtulach@43
   169
    @Path("games/{id}/")
jaroslav@46
   170
    @Produces(MediaType.TEXT_HTML)
jaroslav@101
   171
    public Response board(
jaroslav@100
   172
        @PathParam("id") String id,
jaroslav@100
   173
        @QueryParam("format") @DefaultValue("") String format,
jaroslav@100
   174
        @QueryParam("move") @DefaultValue("-1") String move
jaroslav@100
   175
    ) {
jaroslav@100
   176
        return board(id, null, format, move);
jaroslav@56
   177
    }
jaroslav@101
   178
    private Response board(@PathParam("id") String id, String msg, String format, String m) {
jaroslav@46
   179
        Viewable v = checkLogin();
jaroslav@46
   180
        if (v != null) {
jaroslav@101
   181
            return Response.ok().entity(v).build();
jaroslav@46
   182
        }
jaroslav@100
   183
        int move;
jaroslav@100
   184
        try {
jaroslav@100
   185
            move = Integer.parseInt(m);
jaroslav@100
   186
        } catch (NumberFormatException ex) {
jaroslav@100
   187
            move = -1;
jaroslav@100
   188
        }
jaroslav@100
   189
        WebResource url = base.path("games").path(id);
jaroslav@100
   190
        if (move >= 0) {
jaroslav@100
   191
            url = url.queryParam("move", "" + move);
jaroslav@100
   192
        }
jaroslav@101
   193
        ResponseBuilder resp = Response.ok();
jaroslav@101
   194
        Cookie cFormat = headers.getCookies().get("format");
jaroslav@101
   195
        if (format.length() == 0) {
jaroslav@101
   196
            if (cFormat != null) {
jaroslav@101
   197
                format = cFormat.getValue();
jaroslav@101
   198
            }
jaroslav@101
   199
        } else {
jaroslav@101
   200
            if (cFormat == null || !format.equals(cFormat.getValue())) {
jaroslav@101
   201
                resp.cookie(new NewCookie("format", format));
jaroslav@101
   202
            }
jaroslav@101
   203
        }
jaroslav@101
   204
jaroslav@100
   205
        Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@99
   206
        Board b;
jaroslav@99
   207
        try {
jaroslav@99
   208
            b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
jaroslav@99
   209
        } catch (IllegalPositionException ex) {
jaroslav@99
   210
            Exceptions.printStackTrace(ex);
jaroslav@99
   211
            b = Board.empty();
jaroslav@99
   212
        }
jaroslav@101
   213
        v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
jaroslav@101
   214
        return resp.entity(v).build();
jtulach@42
   215
    }
jtulach@41
   216
jtulach@42
   217
    @GET
jtulach@43
   218
    @Path("games/{id}/move")
jaroslav@46
   219
    @Produces(MediaType.TEXT_HTML)
jaroslav@101
   220
    public Response move(
jtulach@43
   221
        @PathParam("id") String id,
jtulach@43
   222
        @QueryParam("type") String type,
jtulach@43
   223
        @QueryParam("direction") String direction,
jtulach@43
   224
        @QueryParam("direction-next") @DefaultValue("") String directionNext,
jtulach@43
   225
        @QueryParam("column") @DefaultValue("") String column,
jtulach@43
   226
        @QueryParam("row") @DefaultValue("") String row
jtulach@54
   227
    ) {
jaroslav@46
   228
        Viewable v = checkLogin();
jaroslav@46
   229
        if (v != null) {
jaroslav@101
   230
            return Response.ok().entity(v).build();
jaroslav@46
   231
        }
jtulach@82
   232
        WebResource wr = base.path("games").path(id).
jtulach@82
   233
            queryParam("loginID", uuid).
jtulach@82
   234
            queryParam("player", user);
jaroslav@56
   235
        try {
jtulach@75
   236
            if (type.equals("resign")) {
jtulach@75
   237
                wr.queryParam("move", "RESIGN").put();
jtulach@75
   238
                return board(id);
jtulach@75
   239
            }
jaroslav@56
   240
            if (type.equals("fence")) {
jaroslav@56
   241
                wr.queryParam("move", direction.charAt(0) + column + row).put();
jaroslav@56
   242
                return board(id);
jaroslav@56
   243
            }
jaroslav@56
   244
            if (type.equals("move")) {
jaroslav@56
   245
                wr.queryParam("move", direction + directionNext).put();
jaroslav@56
   246
                return board(id);
jaroslav@56
   247
            }
jaroslav@56
   248
        } catch (UniformInterfaceException ex) {
jaroslav@100
   249
            return board(id, "WRONG_MOVE", "-1");
jtulach@43
   250
        }
jtulach@43
   251
        return board(id);
jtulach@43
   252
    }
jtulach@43
   253
jtulach@43
   254
    @GET
jaroslav@115
   255
    @Path("games/{id}/comment")
jaroslav@115
   256
    @Produces(MediaType.TEXT_HTML)
jaroslav@115
   257
    public Response comment(
jaroslav@115
   258
        @PathParam("id") String id,
jaroslav@115
   259
        @QueryParam("comment") String comment
jaroslav@115
   260
    ) {
jaroslav@115
   261
        Viewable v = checkLogin();
jaroslav@115
   262
        if (v != null) {
jaroslav@115
   263
            return Response.ok().entity(v).build();
jaroslav@115
   264
        }
jaroslav@115
   265
        WebResource wr = base.path("games").path(id).
jaroslav@115
   266
            queryParam("loginID", uuid).
jaroslav@115
   267
            queryParam("player", user).
jaroslav@115
   268
            queryParam("comment", comment);
jaroslav@115
   269
        wr.put();
jaroslav@115
   270
        
jaroslav@115
   271
        return board(id);
jaroslav@115
   272
    }
jaroslav@115
   273
jaroslav@115
   274
    @GET
jtulach@42
   275
    @Path("games/create")
jaroslav@46
   276
    @Produces(MediaType.TEXT_HTML)
jaroslav@73
   277
    public Response create(
jtulach@42
   278
        @QueryParam("white") String white,
jtulach@42
   279
        @QueryParam("black") String black
jtulach@54
   280
    ) {
jaroslav@46
   281
        Viewable v = checkLogin();
jaroslav@46
   282
        if (v != null) {
jaroslav@73
   283
            return Response.status(Response.Status.FORBIDDEN).entity(v).build();
jaroslav@46
   284
        }
jaroslav@57
   285
jaroslav@57
   286
        if (user.equals(white) || user.equals(black)) {
jaroslav@57
   287
            Object obj =
jtulach@82
   288
                base.path("games").
jtulach@82
   289
                queryParam("loginID", uuid).
jtulach@82
   290
                queryParam("white", white).
jaroslav@73
   291
                queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
jaroslav@73
   292
            return Response.ok(welcomeImpl()).build();
jaroslav@57
   293
        } else {
jaroslav@73
   294
            return Response.status(Response.Status.NOT_FOUND).
jaroslav@73
   295
                entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
jaroslav@57
   296
        }
jtulach@41
   297
    }
jtulach@41
   298
jaroslav@57
   299
    private Viewable welcomeImpl(Object... args) {
jaroslav@56
   300
        final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@57
   301
        return viewable("index.fmt", got, args);
jtulach@41
   302
    }
jtulach@41
   303
jtulach@41
   304
    //
jtulach@41
   305
    // start the server
jtulach@41
   306
    //
jtulach@41
   307
jtulach@41
   308
    public static void main(String[] args) throws Exception {
jaroslav@121
   309
        int port = 9333;
jaroslav@68
   310
        if (args.length > 1) {
jaroslav@68
   311
            port = Integer.parseInt(args[0]);
jaroslav@68
   312
        }
jaroslav@121
   313
        String remoteAPI = args.length > 2 ? args[1] : null;
jaroslav@50
   314
jaroslav@68
   315
jaroslav@121
   316
        Callable<Void> r = startServers(port, remoteAPI);
jaroslav@68
   317
jaroslav@122
   318
        if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
jaroslav@68
   319
            System.out.println("Hit enter to stop it...");
jaroslav@68
   320
            System.in.read();
jaroslav@68
   321
        } else {
jaroslav@68
   322
            synchronized (UI.class) {
jaroslav@68
   323
                UI.class.wait();
jaroslav@68
   324
            }
jaroslav@68
   325
        }
jaroslav@50
   326
        r.call();
jaroslav@50
   327
        System.exit(0);
jaroslav@50
   328
    }
jaroslav@50
   329
jaroslav@121
   330
    static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
jaroslav@121
   331
        Client client = new Client();
jaroslav@72
   332
jaroslav@121
   333
        final HttpServer apiServer;
jaroslav@121
   334
        if (remoteAPI == null) {
jaroslav@121
   335
            int localAPIPort = port - 1;
jaroslav@121
   336
            apiServer = Quoridor.start(localAPIPort);
jaroslav@124
   337
            base = client.resource(new URI("http://localhost:" + localAPIPort));
jaroslav@121
   338
        } else {
jaroslav@121
   339
            base = client.resource(new URI(remoteAPI));
jaroslav@121
   340
            apiServer = null;
jaroslav@73
   341
        }
jaroslav@72
   342
jaroslav@72
   343
        ResourceConfig rc = new PackagesResourceConfig(
jaroslav@72
   344
            "cz.xelfi.quoridor.freemarkerdor"
jaroslav@72
   345
        );
jaroslav@72
   346
jaroslav@72
   347
        final String baseUri = "http://localhost:" + port + "/";
jaroslav@72
   348
        final HttpServer server = HttpServerFactory.create(baseUri, rc);
jaroslav@72
   349
        server.start();
jaroslav@68
   350
        System.out.println("Quoridor started at port " + port);
jaroslav@50
   351
jaroslav@50
   352
        return new Callable<Void>() {
jaroslav@50
   353
            public Void call() throws Exception {
jaroslav@121
   354
                if (apiServer != null) {
jaroslav@121
   355
                    apiServer.stop(0);
jaroslav@121
   356
                }
jaroslav@72
   357
                server.stop(0);
jaroslav@50
   358
                return null;
jaroslav@50
   359
            }
jaroslav@50
   360
        };
jtulach@41
   361
    }
jtulach@41
   362
jaroslav@56
   363
    private Viewable viewable(String page, Document doc, Object... more) {
jaroslav@59
   364
        ResourceBundle rb = null;
jaroslav@59
   365
        for (Locale l : headers.getAcceptableLanguages()) {
jaroslav@59
   366
            try {
jtulach@80
   367
                rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
jaroslav@59
   368
            } catch (MissingResourceException e) {
jaroslav@59
   369
                // OK
jaroslav@59
   370
            }
jaroslav@59
   371
        }
jaroslav@59
   372
        if (rb == null) {
jtulach@80
   373
            rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
jaroslav@59
   374
        }
jaroslav@59
   375
jaroslav@56
   376
        Map<String,Object> map = new HashMap<String,Object>();
jaroslav@56
   377
        map.put("doc", doc);
jaroslav@56
   378
        map.put("user", user);
jaroslav@59
   379
        map.put("bundle", rb);
jtulach@78
   380
        map.put("now", System.currentTimeMillis());
jaroslav@88
   381
        map.put("version", version);
jaroslav@56
   382
        for (int i = 0; i < more.length; i += 2) {
jaroslav@56
   383
            map.put((String)more[i],more[i + 1]);
jaroslav@56
   384
        }
jaroslav@56
   385
        return new Viewable(page, map);
jaroslav@56
   386
    }
jaroslav@56
   387
jtulach@41
   388
}