freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 10 Sep 2009 23:19:40 +0200
changeset 75 6802034b7a6f
parent 73 b3165f3a9ad7
child 78 5ea4172dcf8b
permissions -rw-r--r--
Support for giving up the 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;
jtulach@41
    37
import cz.xelfi.quoridor.webidor.resources.Quoridor;
jaroslav@46
    38
import java.io.File;
jaroslav@46
    39
import java.io.FileInputStream;
jtulach@41
    40
import java.io.IOException;
jtulach@41
    41
import java.net.URI;
jaroslav@55
    42
import java.util.HashMap;
jaroslav@59
    43
import java.util.Locale;
jaroslav@55
    44
import java.util.Map;
jaroslav@59
    45
import java.util.MissingResourceException;
jaroslav@46
    46
import java.util.Properties;
jaroslav@59
    47
import java.util.ResourceBundle;
jaroslav@50
    48
import java.util.concurrent.Callable;
jtulach@43
    49
import javax.ws.rs.DefaultValue;
jaroslav@47
    50
import javax.ws.rs.FormParam;
jtulach@41
    51
import javax.ws.rs.GET;
jaroslav@46
    52
import javax.ws.rs.POST;
jtulach@41
    53
import javax.ws.rs.Path;
jtulach@41
    54
import javax.ws.rs.PathParam;
jaroslav@46
    55
import javax.ws.rs.Produces;
jtulach@42
    56
import javax.ws.rs.QueryParam;
jtulach@42
    57
import javax.ws.rs.core.Context;
jtulach@42
    58
import javax.ws.rs.core.HttpHeaders;
jtulach@41
    59
import javax.ws.rs.core.MediaType;
jaroslav@46
    60
import javax.ws.rs.core.NewCookie;
jaroslav@46
    61
import javax.ws.rs.core.Response;
jaroslav@48
    62
import org.w3c.dom.Document;
jtulach@41
    63
jtulach@41
    64
/**
jtulach@41
    65
 *
jtulach@41
    66
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@41
    67
 */
jtulach@41
    68
@Path("/")
jtulach@41
    69
public final class UI {
jtulach@41
    70
    private static WebResource base;
jtulach@42
    71
jtulach@42
    72
    @Context
jtulach@42
    73
    private HttpHeaders headers;
jaroslav@46
    74
    private String user;
jtulach@42
    75
jtulach@41
    76
    public UI() {
jtulach@41
    77
    }
jtulach@41
    78
jaroslav@46
    79
    private Viewable checkLogin() {
jaroslav@46
    80
        if (headers.getCookies().containsKey("login")) {
jaroslav@46
    81
            user = headers.getCookies().get("login").getValue();
jaroslav@46
    82
            return null;
jaroslav@46
    83
        }
jaroslav@56
    84
        return viewable("login.fmt", null);
jaroslav@46
    85
    }
jaroslav@46
    86
jaroslav@46
    87
    @POST
jaroslav@46
    88
    @Path("login")
jaroslav@46
    89
    @Produces(MediaType.TEXT_HTML)
jaroslav@46
    90
    public Response login(
jaroslav@47
    91
        @FormParam("name") String name, @FormParam("password") String password
jaroslav@46
    92
    ) throws Exception {
jaroslav@73
    93
        File f = new File(new File(System.getProperty("quoridor.dir")), "passwd");
jaroslav@46
    94
        Properties p = new Properties();
jtulach@54
    95
        try {
jtulach@54
    96
            p.load(new FileInputStream(f));
jtulach@54
    97
        } catch (IOException ex) {
jtulach@54
    98
            ex.printStackTrace();
jtulach@54
    99
        }
jaroslav@46
   100
        if (name != null && password.equals(p.getProperty(name))) {
jaroslav@70
   101
            user = name;
jaroslav@70
   102
            return Response.ok().cookie(new NewCookie("login", name)).entity(viewable("login.fmt", null)).build();
jaroslav@46
   103
        } else {
jaroslav@56
   104
            Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
jaroslav@46
   105
            return Response.status(1).entity(v).build();
jaroslav@46
   106
        }
jaroslav@46
   107
    }
jaroslav@46
   108
jtulach@41
   109
    @GET
jaroslav@46
   110
    @Produces(MediaType.TEXT_HTML)
jtulach@54
   111
    public Viewable welcome() {
jaroslav@46
   112
        Viewable v = checkLogin();
jaroslav@46
   113
        if (v != null) {
jaroslav@46
   114
            return v;
jtulach@42
   115
        }
jaroslav@46
   116
        return welcomeImpl();
jtulach@41
   117
    }
jtulach@41
   118
jtulach@41
   119
    @GET
jtulach@43
   120
    @Path("games/{id}/")
jaroslav@46
   121
    @Produces(MediaType.TEXT_HTML)
jtulach@54
   122
    public Viewable board(@PathParam("id") String id) {
jaroslav@56
   123
        return board(id, null);
jaroslav@56
   124
    }
jaroslav@56
   125
    private Viewable board(@PathParam("id") String id, String msg) {
jaroslav@46
   126
        Viewable v = checkLogin();
jaroslav@46
   127
        if (v != null) {
jaroslav@46
   128
            return v;
jaroslav@46
   129
        }
jtulach@54
   130
        Document doc = base.path("games").path(id).accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@56
   131
        return viewable("game.fmt", doc, "message", msg);
jtulach@42
   132
    }
jtulach@41
   133
jtulach@42
   134
    @GET
jtulach@43
   135
    @Path("games/{id}/move")
jaroslav@46
   136
    @Produces(MediaType.TEXT_HTML)
jtulach@43
   137
    public Viewable move(
jtulach@43
   138
        @PathParam("id") String id,
jtulach@43
   139
        @QueryParam("type") String type,
jtulach@43
   140
        @QueryParam("direction") String direction,
jtulach@43
   141
        @QueryParam("direction-next") @DefaultValue("") String directionNext,
jtulach@43
   142
        @QueryParam("column") @DefaultValue("") String column,
jtulach@43
   143
        @QueryParam("row") @DefaultValue("") String row
jtulach@54
   144
    ) {
jaroslav@46
   145
        Viewable v = checkLogin();
jaroslav@46
   146
        if (v != null) {
jaroslav@46
   147
            return v;
jaroslav@46
   148
        }
jaroslav@46
   149
        WebResource wr = base.path("games").path(id).queryParam("player", user);
jaroslav@56
   150
        try {
jtulach@75
   151
            if (type.equals("resign")) {
jtulach@75
   152
                wr.queryParam("move", "RESIGN").put();
jtulach@75
   153
                return board(id);
jtulach@75
   154
            }
jaroslav@56
   155
            if (type.equals("fence")) {
jaroslav@56
   156
                wr.queryParam("move", direction.charAt(0) + column + row).put();
jaroslav@56
   157
                return board(id);
jaroslav@56
   158
            }
jaroslav@56
   159
            if (type.equals("move")) {
jaroslav@56
   160
                wr.queryParam("move", direction + directionNext).put();
jaroslav@56
   161
                return board(id);
jaroslav@56
   162
            }
jaroslav@56
   163
        } catch (UniformInterfaceException ex) {
jaroslav@56
   164
            return board(id, "WRONG_MOVE");
jtulach@43
   165
        }
jtulach@43
   166
        return board(id);
jtulach@43
   167
    }
jtulach@43
   168
jtulach@43
   169
    @GET
jtulach@42
   170
    @Path("games/create")
jaroslav@46
   171
    @Produces(MediaType.TEXT_HTML)
jaroslav@73
   172
    public Response create(
jtulach@42
   173
        @QueryParam("white") String white,
jtulach@42
   174
        @QueryParam("black") String black
jtulach@54
   175
    ) {
jaroslav@46
   176
        Viewable v = checkLogin();
jaroslav@46
   177
        if (v != null) {
jaroslav@73
   178
            return Response.status(Response.Status.FORBIDDEN).entity(v).build();
jaroslav@46
   179
        }
jaroslav@57
   180
jaroslav@57
   181
        if (user.equals(white) || user.equals(black)) {
jaroslav@57
   182
            Object obj =
jaroslav@57
   183
                base.path("games").queryParam("white", white).
jaroslav@73
   184
                queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
jaroslav@73
   185
            return Response.ok(welcomeImpl()).build();
jaroslav@57
   186
        } else {
jaroslav@73
   187
            return Response.status(Response.Status.NOT_FOUND).
jaroslav@73
   188
                entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
jaroslav@57
   189
        }
jtulach@41
   190
    }
jtulach@41
   191
jaroslav@57
   192
    private Viewable welcomeImpl(Object... args) {
jaroslav@56
   193
        final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@57
   194
        return viewable("index.fmt", got, args);
jtulach@41
   195
    }
jtulach@41
   196
jtulach@41
   197
    //
jtulach@41
   198
    // start the server
jtulach@41
   199
    //
jtulach@41
   200
jtulach@41
   201
    public static void main(String[] args) throws Exception {
jaroslav@68
   202
        int port = 9998;
jaroslav@68
   203
        if (args.length > 1) {
jaroslav@68
   204
            port = Integer.parseInt(args[0]);
jaroslav@68
   205
        }
jaroslav@50
   206
jaroslav@68
   207
jaroslav@68
   208
        Callable<Void> r = startServers(port);
jaroslav@68
   209
jaroslav@68
   210
        if (args.length > 2 && args[1].equals("--kill")) {
jaroslav@68
   211
            System.out.println("Hit enter to stop it...");
jaroslav@68
   212
            System.in.read();
jaroslav@68
   213
        } else {
jaroslav@68
   214
            synchronized (UI.class) {
jaroslav@68
   215
                UI.class.wait();
jaroslav@68
   216
            }
jaroslav@68
   217
        }
jaroslav@50
   218
        r.call();
jaroslav@50
   219
        System.exit(0);
jaroslav@50
   220
    }
jaroslav@50
   221
jaroslav@68
   222
    static Callable<Void> startServers(int port) throws Exception {
jaroslav@72
   223
jaroslav@73
   224
        if (System.getProperty("quoridor.dir") == null) {
jaroslav@73
   225
            File home = new File(System.getProperty("user.home"));
jaroslav@73
   226
            File quoridor = new File(home, ".quoridor");
jaroslav@73
   227
            System.setProperty("quoridor.dir", quoridor.getPath());
jaroslav@73
   228
        }
jaroslav@72
   229
jaroslav@72
   230
        ResourceConfig rc = new PackagesResourceConfig(
jaroslav@72
   231
            "cz.xelfi.quoridor.webidor",
jaroslav@72
   232
            "cz.xelfi.quoridor.freemarkerdor"
jaroslav@72
   233
        );
jaroslav@72
   234
jtulach@41
   235
        Client client = new Client();
jaroslav@72
   236
        base = client.resource(new URI("http://localhost:" + port + "/api/"));
jtulach@41
   237
jaroslav@72
   238
        final String baseUri = "http://localhost:" + port + "/";
jaroslav@72
   239
        final HttpServer server = HttpServerFactory.create(baseUri, rc);
jaroslav@72
   240
        server.start();
jaroslav@68
   241
        System.out.println("Quoridor started at port " + port);
jaroslav@50
   242
jaroslav@50
   243
        return new Callable<Void>() {
jaroslav@50
   244
            public Void call() throws Exception {
jaroslav@72
   245
                server.stop(0);
jaroslav@50
   246
                return null;
jaroslav@50
   247
            }
jaroslav@50
   248
        };
jtulach@41
   249
    }
jtulach@41
   250
jaroslav@56
   251
    private Viewable viewable(String page, Document doc, Object... more) {
jaroslav@59
   252
        String bundle = page.split("\\.")[0];
jaroslav@59
   253
jaroslav@59
   254
        ResourceBundle rb = null;
jaroslav@59
   255
        for (Locale l : headers.getAcceptableLanguages()) {
jaroslav@59
   256
            try {
jaroslav@59
   257
                rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI." + bundle, l);
jaroslav@59
   258
            } catch (MissingResourceException e) {
jaroslav@59
   259
                // OK
jaroslav@59
   260
            }
jaroslav@59
   261
        }
jaroslav@59
   262
        if (rb == null) {
jaroslav@59
   263
            rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI." + bundle, Locale.ENGLISH);
jaroslav@59
   264
        }
jaroslav@59
   265
jaroslav@56
   266
        Map<String,Object> map = new HashMap<String,Object>();
jaroslav@56
   267
        map.put("doc", doc);
jaroslav@56
   268
        map.put("user", user);
jaroslav@59
   269
        map.put("bundle", rb);
jaroslav@56
   270
        for (int i = 0; i < more.length; i += 2) {
jaroslav@56
   271
            map.put((String)more[i],more[i + 1]);
jaroslav@56
   272
        }
jaroslav@56
   273
        return new Viewable(page, map);
jaroslav@56
   274
    }
jaroslav@56
   275
jtulach@41
   276
}