Initial version of statistics and ELO rating. Donated by Martin Rexa
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * The contents of this file are subject to the terms of either the GNU
5 * General Public License Version 2 only ("GPL") or the Common
6 * Development and Distribution License("CDDL") (collectively, the
7 * "License"). You may not use this file except in compliance with the
8 * License. You can obtain a copy of the License at
9 * http://www.netbeans.org/cddl-gplv2.html
10 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
11 * specific language governing permissions and limitations under the
12 * License. When distributing the software, include this License Header
13 * Notice in each file and include the License file at
14 * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
15 * particular file as subject to the "Classpath" exception as provided
16 * by Sun in the GPL Version 2 section of the License file that
17 * accompanied this code. If applicable, add the following below the
18 * License Header, with the fields enclosed by brackets [] replaced by
19 * your own identifying information:
20 * "Portions Copyrighted [year] [name of copyright owner]"
24 * Portions Copyrighted 2009 Jaroslav Tulach
27 package cz.xelfi.quoridor.freemarkerdor;
29 import com.sun.jersey.api.client.Client;
30 import com.sun.jersey.api.client.UniformInterfaceException;
31 import com.sun.jersey.api.client.WebResource;
32 import com.sun.jersey.api.container.httpserver.HttpServerFactory;
33 import com.sun.jersey.api.core.PackagesResourceConfig;
34 import com.sun.jersey.api.core.ResourceConfig;
35 import com.sun.jersey.api.view.Viewable;
36 import com.sun.net.httpserver.HttpServer;
37 import cz.xelfi.quoridor.Board;
38 import cz.xelfi.quoridor.IllegalPositionException;
39 import java.io.IOException;
40 import java.io.InputStream;
42 import java.util.Date;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Locale;
47 import java.util.MissingResourceException;
48 import java.util.Properties;
49 import java.util.ResourceBundle;
50 import java.util.concurrent.Callable;
51 import javax.ws.rs.DefaultValue;
52 import javax.ws.rs.FormParam;
53 import javax.ws.rs.GET;
54 import javax.ws.rs.POST;
55 import javax.ws.rs.Path;
56 import javax.ws.rs.PathParam;
57 import javax.ws.rs.Produces;
58 import javax.ws.rs.QueryParam;
59 import javax.ws.rs.core.CacheControl;
60 import javax.ws.rs.core.Context;
61 import javax.ws.rs.core.Cookie;
62 import javax.ws.rs.core.HttpHeaders;
63 import javax.ws.rs.core.MediaType;
64 import javax.ws.rs.core.NewCookie;
65 import javax.ws.rs.core.Response;
66 import javax.ws.rs.core.Response.ResponseBuilder;
67 import org.openide.util.Exceptions;
68 import org.w3c.dom.Document;
72 * @author Jaroslav Tulach <jtulach@netbeans.org>
75 public final class UI {
76 private static final String version;
78 Properties p = new Properties();
80 InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/org.apidesign/freemarkerdor/pom.properties"); // NOI18N
84 } catch (IOException ex) {
87 version = p.getProperty("version", "unknown"); // NOI18N
89 private static WebResource base;
90 private static WebResource stat;
93 private HttpHeaders headers;
94 private UserInfo user;
100 private Viewable checkLogin() {
101 Cookie cookie = headers.getCookies().get("login");
102 if (cookie != null) {
103 String id = cookie.getValue();
106 us = base.path("users").queryParam("loginID", id).
107 accept(MediaType.TEXT_XML).get(UserInfo.class);
108 } catch (Exception ex) {
109 ex.printStackTrace();
112 if (us != null && us.getId().length() > 0) {
118 return viewable("login.fmt", null);
123 @Produces(MediaType.TEXT_HTML)
124 public Response login(
125 @FormParam("name") String name, @FormParam("password") String password
127 uuid = base.path("login").queryParam("name", name).queryParam("password", password).
128 accept(MediaType.TEXT_PLAIN).put(String.class);
130 user = new UserInfo(name);
131 NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
132 return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
134 Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
135 return Response.status(1).entity(v).build();
140 @Produces(MediaType.TEXT_HTML)
141 public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
142 Viewable v = checkLogin();
143 ResponseBuilder resp = Response.ok();
145 v = welcomeImpl("maxItems", maxItems);
147 CacheControl cc = new CacheControl();
149 resp.cacheControl(cc);
150 return resp.entity(v).build();
154 @Path("games/{id}.png")
155 @Produces("image/png")
156 public Response getBoardImage(
157 @PathParam("id") String id,
158 @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
159 @QueryParam("move") @DefaultValue("-1") int move
160 ) throws IllegalPositionException {
161 WebResource wr = base.path("games").path(id);
163 wr = wr.queryParam("move", "" + move);
165 String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
166 Board b = Board.valueOf(txt);
167 // Board b = new Board(txt);
168 ResponseBuilder resp = Response.ok();
169 CacheControl cc = new CacheControl();
171 resp.cacheControl(cc);
172 return resp.entity(BoardImage.draw(b, fieldSize)).build();
176 private Response board(String id) {
177 return board(id, "", null);
181 @Produces(MediaType.TEXT_HTML)
182 public Response board(
183 @PathParam("id") String id,
184 @QueryParam("format") @DefaultValue("") String format,
185 @QueryParam("move") @DefaultValue("-1") String move
187 return board(id, null, format, move);
189 private Response board(@PathParam("id") String id, String msg, String format, String m) {
190 Viewable v = checkLogin();
192 return Response.ok().entity(v).build();
196 move = Integer.parseInt(m);
197 } catch (NumberFormatException ex) {
200 WebResource url = base.path("games").queryParam("loginID", uuid).path(id);
202 url = url.queryParam("move", "" + move);
204 ResponseBuilder resp = Response.ok();
205 CacheControl cc = new CacheControl();
207 resp.cacheControl(cc);
208 Cookie cFormat = headers.getCookies().get("format");
209 if (format.length() == 0) {
210 if (cFormat != null) {
211 format = cFormat.getValue();
213 if (isMobile(headers)) {
218 if (cFormat == null || !format.equals(cFormat.getValue())) {
219 resp.cookie(new NewCookie("format", format));
223 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
225 String t = doc.getElementsByTagName("board").item(0).getTextContent();
227 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
228 } catch (Exception ex) {
230 // } catch (IllegalStateException ex) {
231 Exceptions.printStackTrace(ex);
236 bCode = stat.path("openings").path(Board.board2HashCode(b)+".check").queryParam("loginID", user.getId()).accept(MediaType.TEXT_PLAIN).get(String.class);
240 if(bCode == null || "".equals(bCode))
241 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture",b.boardToPicture());
243 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture",b.boardToPicture(),"bCode", bCode);
244 return resp.entity(v).build();
248 @Path("games/{id}/move")
249 @Produces(MediaType.TEXT_HTML)
250 public Response move(
251 @PathParam("id") String id,
252 @QueryParam("type") String type,
253 @QueryParam("direction") String direction,
254 @QueryParam("direction-next") @DefaultValue("") String directionNext,
255 @QueryParam("column") @DefaultValue("") String column,
256 @QueryParam("row") @DefaultValue("") String row
258 Viewable v = checkLogin();
260 return Response.ok().entity(v).build();
262 WebResource wr = base.path("games").path(id).
263 queryParam("loginID", uuid).
264 queryParam("player", user.getId());
266 if (type.equals("resign")) {
267 wr.queryParam("move", "RESIGN").put();
270 if (type.equals("fence")) {
271 wr.queryParam("move", direction.charAt(0) + column + row).put();
274 if (type.equals("move")) {
275 wr.queryParam("move", direction + directionNext).put();
278 } catch (UniformInterfaceException ex) {
279 return board(id, "WRONG_MOVE", "-1");
285 @Path("games/{id}/comment")
286 @Produces(MediaType.TEXT_HTML)
287 public Response comment(
288 @PathParam("id") String id,
289 @QueryParam("comment") String comment
291 Viewable v = checkLogin();
293 return Response.ok().entity(v).build();
295 WebResource wr = base.path("games").path(id).
296 queryParam("loginID", uuid).
297 queryParam("player", user.getId()).
298 queryParam("comment", comment);
305 @Path("games/create")
306 @Produces(MediaType.TEXT_HTML)
307 public Response create(
308 @QueryParam("white") String white,
309 @QueryParam("black") String black
311 Viewable v = checkLogin();
313 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
316 if (user.getId().equals(white) || user.getId().equals(black)) {
319 queryParam("loginID", uuid).
320 queryParam("white", white).
321 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
322 return Response.ok(welcomeImpl()).build();
324 return Response.status(Response.Status.NOT_FOUND).
325 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
329 private Viewable welcomeImpl(Object... args) {
330 final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
331 return viewable("index.fmt", got, args);
337 public Response changeOptions(
338 @QueryParam("email") String email,
339 @QueryParam("language") String language
341 Viewable v = checkLogin();
343 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
347 UserInfo ui = base.path("users/" + user.getId()).
348 queryParam("loginID", uuid).
349 queryParam("name", "email").
350 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
353 if (language != null) {
354 UserInfo ui = base.path("users/" + user.getId()).
355 queryParam("loginID", uuid).
356 queryParam("name", "language").
357 queryParam("value", language).
358 accept(MediaType.TEXT_XML).post(UserInfo.class);
366 @Produces(MediaType.TEXT_HTML)
367 public Response getEloList(){
368 Viewable v = checkLogin();
370 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
372 final Document got = stat.path("elo").path("list").accept(MediaType.TEXT_XML).get(Document.class);
373 return Response.ok(viewable("elo.fmt", got)).build();
378 @Produces(MediaType.TEXT_HTML)
379 public Response getOpeningRoot(){
380 return getOpeningNode("ROOT");
384 @Path("openings/{code}")
385 @Produces(MediaType.TEXT_HTML)
386 public Response getOpeningNode(@PathParam("code") String code){
387 Viewable v = checkLogin();
389 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
391 final Document got = stat.path("openings").path(code).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
394 b = Board.valueOf(got.getElementsByTagName("nodeCode").item(0).getTextContent());
395 } catch (Exception ex) {
396 Exceptions.printStackTrace(ex);
399 return Response.ok(viewable("openings.fmt", got, "whitefences",b.getPlayers().get(0).getFences(),"blackfences",b.getPlayers().get(1).getFences())).build();
403 @Path("openings/{code}/{status}")
404 @Produces(MediaType.TEXT_HTML)
405 public Response getOpeningNodeGames(@PathParam("code") String code, @PathParam("status") String status){
406 Viewable v = checkLogin();
408 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
410 final Document got = stat.path("openings").path(code).path(status).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
411 return Response.ok(viewable("opening_games.fmt", got,"code",code,"color",status)).build();
415 @Path("openings/{code}.png")
416 @Produces("image/png")
417 public Response getOpeningBoardImage(
418 @PathParam("code") String code,
419 @QueryParam("fieldSize") @DefaultValue("40") int fieldSize
420 ) throws IllegalPositionException {
421 Board b = new Board(code);
422 ResponseBuilder resp = Response.ok();
423 CacheControl cc = new CacheControl();
425 resp.cacheControl(cc);
426 return resp.entity(BoardImage.draw(b, fieldSize)).build();
433 public static void main(String[] args) throws Exception {
435 if (args.length > 1) {
436 port = Integer.parseInt(args[0]);
438 String remoteAPI = args.length >= 2 ? args[1] : null;
440 Locale.setDefault(Locale.ROOT);
442 Callable<Void> r = startServers(port, remoteAPI);
444 if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
445 System.out.println("Hit enter to stop it...");
448 synchronized (UI.class) {
456 static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
457 Client client = new Client();
458 Client client1 = new Client();
460 final HttpServer apiServer;
461 if (remoteAPI == null) {
462 throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
464 base = client.resource(new URI(remoteAPI));
465 stat = client1.resource(new URI("http://localhost:9444"));
469 ResourceConfig rc = new PackagesResourceConfig(
470 "cz.xelfi.quoridor.freemarkerdor"
473 final String baseUri = "http://localhost:" + port + "/";
474 final HttpServer server = HttpServerFactory.create(baseUri, rc);
476 System.out.println("Quoridor started at port " + port);
478 return new Callable<Void>() {
479 public Void call() throws Exception {
480 if (apiServer != null) {
489 private Viewable viewable(String page, Document doc, Object... more) {
490 ResourceBundle rb = null;
491 String lng = user == null ? null : user.getProperty("language"); // NOI18N
492 Locale locale = null;
495 Locale l = new Locale(lng);
496 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
498 } catch (MissingResourceException e) {
503 for (Locale l : headers.getAcceptableLanguages()) {
505 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
508 } catch (MissingResourceException e) {
514 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
515 locale = Locale.ENGLISH;
518 Map<String,Object> map = new HashMap<String,Object>();
519 class ConvertToDate extends HashMap<Object,Object> {
521 public Object get(Object o) {
522 long time = Long.parseLong(o.toString());
523 return new Date(time);
527 map.put("locale", locale.toString());
530 map.put("user", user.getId());
531 map.put("email", user.getProperty("email"));
533 map.put("bundle", rb);
534 map.put("toDate", new ConvertToDate());
535 map.put("now", System.currentTimeMillis());
536 map.put("version", version);
537 for (int i = 0; i < more.length; i += 2) {
538 map.put((String)more[i],more[i + 1]);
540 return new Viewable(page, map);
544 private static boolean isMobile(HttpHeaders headers) {
545 final String[] keywords = {
548 List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
550 for (String a : agent) {
551 for (String k : keywords) {