freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 07 Sep 2009 22:27:39 +0200
changeset 70 3c9966fc0352
parent 68 33cf89760fab
child 72 5f081edc8502
permissions -rw-r--r--
More reliable way to login
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@46
    93
        File f = new File(new File(new File(System.getProperty("user.home")), ".quoridor"), "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 {
jaroslav@56
   151
            if (type.equals("fence")) {
jaroslav@56
   152
                wr.queryParam("move", direction.charAt(0) + column + row).put();
jaroslav@56
   153
                return board(id);
jaroslav@56
   154
            }
jaroslav@56
   155
            if (type.equals("move")) {
jaroslav@56
   156
                wr.queryParam("move", direction + directionNext).put();
jaroslav@56
   157
                return board(id);
jaroslav@56
   158
            }
jaroslav@56
   159
        } catch (UniformInterfaceException ex) {
jaroslav@56
   160
            return board(id, "WRONG_MOVE");
jtulach@43
   161
        }
jtulach@43
   162
        return board(id);
jtulach@43
   163
    }
jtulach@43
   164
jtulach@43
   165
    @GET
jtulach@42
   166
    @Path("games/create")
jaroslav@46
   167
    @Produces(MediaType.TEXT_HTML)
jtulach@42
   168
    public Viewable create(
jtulach@42
   169
        @QueryParam("white") String white,
jtulach@42
   170
        @QueryParam("black") String black
jtulach@54
   171
    ) {
jaroslav@46
   172
        Viewable v = checkLogin();
jaroslav@46
   173
        if (v != null) {
jaroslav@46
   174
            return v;
jaroslav@46
   175
        }
jaroslav@57
   176
jaroslav@57
   177
        if (user.equals(white) || user.equals(black)) {
jaroslav@57
   178
            Object obj =
jaroslav@57
   179
                base.path("games").queryParam("white", white).
jaroslav@57
   180
                queryParam("black", black).post(Document.class);
jaroslav@57
   181
            return welcomeImpl();
jaroslav@57
   182
        } else {
jaroslav@57
   183
            return welcomeImpl("message", "You (" + user + ") must be white or black!");
jaroslav@57
   184
        }
jtulach@41
   185
    }
jtulach@41
   186
jaroslav@57
   187
    private Viewable welcomeImpl(Object... args) {
jaroslav@56
   188
        final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
jaroslav@57
   189
        return viewable("index.fmt", got, args);
jtulach@41
   190
    }
jtulach@41
   191
jtulach@41
   192
    //
jtulach@41
   193
    // start the server
jtulach@41
   194
    //
jtulach@41
   195
jtulach@41
   196
    public static void main(String[] args) throws Exception {
jaroslav@68
   197
        int port = 9998;
jaroslav@68
   198
        if (args.length > 1) {
jaroslav@68
   199
            port = Integer.parseInt(args[0]);
jaroslav@68
   200
        }
jaroslav@50
   201
jaroslav@68
   202
jaroslav@68
   203
        Callable<Void> r = startServers(port);
jaroslav@68
   204
jaroslav@68
   205
        if (args.length > 2 && args[1].equals("--kill")) {
jaroslav@68
   206
            System.out.println("Hit enter to stop it...");
jaroslav@68
   207
            System.in.read();
jaroslav@68
   208
        } else {
jaroslav@68
   209
            synchronized (UI.class) {
jaroslav@68
   210
                UI.class.wait();
jaroslav@68
   211
            }
jaroslav@68
   212
        }
jaroslav@50
   213
        r.call();
jaroslav@50
   214
        System.exit(0);
jaroslav@50
   215
    }
jaroslav@50
   216
jaroslav@68
   217
    static Callable<Void> startServers(int port) throws Exception {
jaroslav@68
   218
        final HttpServer api = Quoridor.start(port + 1);
jtulach@41
   219
        Client client = new Client();
jaroslav@68
   220
        base = client.resource(new URI("http://localhost:" + (port + 1) + "/api/"));
jtulach@41
   221
jaroslav@68
   222
        final HttpServer s = start(port);
jaroslav@68
   223
        System.out.println("Quoridor started at port " + port);
jaroslav@50
   224
jaroslav@50
   225
        return new Callable<Void>() {
jaroslav@50
   226
            public Void call() throws Exception {
jaroslav@50
   227
                s.stop(0);
jaroslav@50
   228
                api.stop(0);
jaroslav@50
   229
                return null;
jaroslav@50
   230
            }
jaroslav@50
   231
        };
jtulach@41
   232
    }
jtulach@41
   233
jtulach@41
   234
    static HttpServer start(int port) throws IOException {
jtulach@41
   235
        final String baseUri = "http://localhost:" + port + "/";
jtulach@41
   236
        ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.freemarkerdor");
jtulach@41
   237
        HttpServer server = HttpServerFactory.create(baseUri, rc);
jtulach@41
   238
        server.start();
jtulach@41
   239
        return server;
jtulach@41
   240
    }
jtulach@41
   241
jaroslav@56
   242
    private Viewable viewable(String page, Document doc, Object... more) {
jaroslav@59
   243
        String bundle = page.split("\\.")[0];
jaroslav@59
   244
jaroslav@59
   245
        ResourceBundle rb = null;
jaroslav@59
   246
        for (Locale l : headers.getAcceptableLanguages()) {
jaroslav@59
   247
            try {
jaroslav@59
   248
                rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI." + bundle, l);
jaroslav@59
   249
            } catch (MissingResourceException e) {
jaroslav@59
   250
                // OK
jaroslav@59
   251
            }
jaroslav@59
   252
        }
jaroslav@59
   253
        if (rb == null) {
jaroslav@59
   254
            rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI." + bundle, Locale.ENGLISH);
jaroslav@59
   255
        }
jaroslav@59
   256
jaroslav@56
   257
        Map<String,Object> map = new HashMap<String,Object>();
jaroslav@56
   258
        map.put("doc", doc);
jaroslav@56
   259
        map.put("user", user);
jaroslav@59
   260
        map.put("bundle", rb);
jaroslav@56
   261
        for (int i = 0; i < more.length; i += 2) {
jaroslav@56
   262
            map.put((String)more[i],more[i + 1]);
jaroslav@56
   263
        }
jaroslav@56
   264
        return new Viewable(page, map);
jaroslav@56
   265
    }
jaroslav@56
   266
jtulach@41
   267
}