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;
41 import java.io.StringWriter;
43 import java.util.Date;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Locale;
48 import java.util.MissingResourceException;
49 import java.util.Properties;
50 import java.util.ResourceBundle;
51 import java.util.concurrent.Callable;
52 import javax.ws.rs.DefaultValue;
53 import javax.ws.rs.FormParam;
54 import javax.ws.rs.GET;
55 import javax.ws.rs.POST;
56 import javax.ws.rs.Path;
57 import javax.ws.rs.PathParam;
58 import javax.ws.rs.Produces;
59 import javax.ws.rs.QueryParam;
60 import javax.ws.rs.core.CacheControl;
61 import javax.ws.rs.core.Context;
62 import javax.ws.rs.core.Cookie;
63 import javax.ws.rs.core.HttpHeaders;
64 import javax.ws.rs.core.MediaType;
65 import javax.ws.rs.core.NewCookie;
66 import javax.ws.rs.core.Response;
67 import javax.ws.rs.core.Response.ResponseBuilder;
68 import org.openide.util.Exceptions;
69 import org.w3c.dom.Document;
73 * @author Jaroslav Tulach <jtulach@netbeans.org>
76 public final class UI {
77 private static final String version;
79 Properties p = new Properties();
81 InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/cz.xelfi.quoridor/freemarkerdor/pom.properties"); // NOI18N
85 } catch (IOException ex) {
88 version = p.getProperty("version", "unknown"); // NOI18N
90 private static WebResource base;
91 private static WebResource stat;
94 private HttpHeaders headers;
95 private UserInfo user;
101 private Viewable checkLogin() {
102 Cookie cookie = headers.getCookies().get("login");
103 if (cookie != null) {
104 String id = cookie.getValue();
107 us = base.path("users").queryParam("loginID", id).
108 accept(MediaType.TEXT_XML).get(UserInfo.class);
109 } catch (Exception ex) {
110 ex.printStackTrace();
113 if (us != null && us.getId().length() > 0) {
119 return viewable("login.fmt", null);
124 @Produces(MediaType.TEXT_HTML)
125 public Response login(
126 @FormParam("name") String name, @FormParam("password") String password
128 uuid = base.path("login").queryParam("name", name).queryParam("password", password).
129 accept(MediaType.TEXT_PLAIN).put(String.class);
131 user = new UserInfo(name);
132 NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
133 return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
135 Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
136 return Response.status(1).entity(v).build();
141 @Produces(MediaType.TEXT_HTML)
142 public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
143 Viewable v = checkLogin();
144 ResponseBuilder resp = Response.ok();
146 v = welcomeImpl("maxItems", maxItems);
148 CacheControl cc = new CacheControl();
150 resp.cacheControl(cc);
151 return resp.entity(v).build();
155 @Path("games/{id}.png")
156 @Produces("image/png")
157 public Response getBoardImage(
158 @PathParam("id") String id,
159 @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
160 @QueryParam("move") @DefaultValue("-1") int move
161 ) throws IllegalPositionException {
162 WebResource wr = base.path("games").path(id);
164 wr = wr.queryParam("move", "" + move);
166 String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
167 Board b = Board.valueOf(txt);
168 // Board b = new Board(txt);
169 ResponseBuilder resp = Response.ok();
170 CacheControl cc = new CacheControl();
172 resp.cacheControl(cc);
173 return resp.entity(BoardImage.draw(b, fieldSize)).build();
177 private Response board(String id) {
178 return board(id, "", null);
182 @Produces(MediaType.TEXT_HTML)
183 public Response board(
184 @PathParam("id") String id,
185 @QueryParam("format") @DefaultValue("") String format,
186 @QueryParam("move") @DefaultValue("-1") String move
188 return board(id, null, format, move);
190 private Response board(@PathParam("id") String id, String msg, String format, String m) {
191 Viewable v = checkLogin();
193 return Response.ok().entity(v).build();
197 move = Integer.parseInt(m);
198 } catch (NumberFormatException ex) {
201 WebResource url = base.path("games").queryParam("loginID", uuid).path(id);
203 url = url.queryParam("move", "" + move);
205 ResponseBuilder resp = Response.ok();
206 CacheControl cc = new CacheControl();
208 resp.cacheControl(cc);
209 Cookie cFormat = headers.getCookies().get("format");
210 if (format.length() == 0) {
211 if (cFormat != null) {
212 format = cFormat.getValue();
214 if (isMobile(headers)) {
219 if (cFormat == null || !format.equals(cFormat.getValue())) {
220 resp.cookie(new NewCookie("format", format));
224 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
226 String t = doc.getElementsByTagName("board").item(0).getTextContent();
228 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
229 } catch (Exception ex) {
231 // } catch (IllegalStateException ex) {
232 Exceptions.printStackTrace(ex);
237 bCode = stat.path("openings").path(b.getCode()+".check").queryParam("loginID", user.getId()).accept(MediaType.TEXT_PLAIN).get(String.class);
241 if(bCode == null || "".equals(bCode))
242 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture", boardToPicture(b));
244 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture", boardToPicture(b),"bCode", bCode);
245 return resp.entity(v).build();
248 private static String boardToPicture(Board b) {
249 StringWriter w = new StringWriter();
252 } catch (IOException ex) {
253 return ex.toString();
259 @Path("games/{id}/move")
260 @Produces(MediaType.TEXT_HTML)
261 public Response move(
262 @PathParam("id") String id,
263 @QueryParam("type") String type,
264 @QueryParam("direction") String direction,
265 @QueryParam("direction-next") @DefaultValue("") String directionNext,
266 @QueryParam("column") @DefaultValue("") String column,
267 @QueryParam("row") @DefaultValue("") String row
269 Viewable v = checkLogin();
271 return Response.ok().entity(v).build();
273 WebResource wr = base.path("games").path(id).
274 queryParam("loginID", uuid).
275 queryParam("player", user.getId());
277 if (type.equals("resign")) {
278 wr.queryParam("move", "RESIGN").put();
281 if (type.equals("fence")) {
282 wr.queryParam("move", direction.charAt(0) + column + row).put();
285 if (type.equals("move")) {
286 wr.queryParam("move", direction + directionNext).put();
289 } catch (UniformInterfaceException ex) {
290 return board(id, "WRONG_MOVE", "-1");
296 @Path("games/{id}/comment")
297 @Produces(MediaType.TEXT_HTML)
298 public Response comment(
299 @PathParam("id") String id,
300 @QueryParam("comment") String comment
302 Viewable v = checkLogin();
304 return Response.ok().entity(v).build();
306 WebResource wr = base.path("games").path(id).
307 queryParam("loginID", uuid).
308 queryParam("player", user.getId()).
309 queryParam("comment", comment);
316 @Path("games/create")
317 @Produces(MediaType.TEXT_HTML)
318 public Response create(
319 @QueryParam("white") String white,
320 @QueryParam("black") String black
322 Viewable v = checkLogin();
324 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
327 if (user.getId().equals(white) || user.getId().equals(black)) {
330 queryParam("loginID", uuid).
331 queryParam("white", white).
332 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
333 return Response.ok(welcomeImpl()).build();
335 return Response.status(Response.Status.NOT_FOUND).
336 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
340 private Viewable welcomeImpl(Object... args) {
341 final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
342 return viewable("index.fmt", got, args);
348 public Response changeOptions(
349 @QueryParam("email") String email,
350 @QueryParam("language") String language
352 Viewable v = checkLogin();
354 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
358 UserInfo ui = base.path("users/" + user.getId()).
359 queryParam("loginID", uuid).
360 queryParam("name", "email").
361 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
364 if (language != null) {
365 UserInfo ui = base.path("users/" + user.getId()).
366 queryParam("loginID", uuid).
367 queryParam("name", "language").
368 queryParam("value", language).
369 accept(MediaType.TEXT_XML).post(UserInfo.class);
377 @Produces(MediaType.TEXT_HTML)
378 public Response getEloList(
379 @QueryParam("historyId") @DefaultValue("0") Integer historyId){
380 Viewable v = checkLogin();
382 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
384 final Document got = stat.path("elo").path("list").path(historyId.toString()).accept(MediaType.TEXT_XML).get(Document.class);
385 return Response.ok(viewable("elo.fmt", got, "historyId", historyId)).build();
390 @Produces(MediaType.TEXT_HTML)
391 public Response getOpeningRoot(){
392 return getOpeningNode("ROOT");
396 @Path("openings/{code}")
397 @Produces(MediaType.TEXT_HTML)
398 public Response getOpeningNode(@PathParam("code") String code){
399 Viewable v = checkLogin();
401 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
403 final Document got = stat.path("openings").path(code).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
406 b = Board.valueOf(got.getElementsByTagName("nodeCode").item(0).getTextContent());
407 } catch (Exception ex) {
408 Exceptions.printStackTrace(ex);
411 return Response.ok(viewable("openings.fmt", got, "whitefences",b.getPlayers().get(0).getFences(),"blackfences",b.getPlayers().get(1).getFences())).build();
415 @Path("openings/{code}/{status}")
416 @Produces(MediaType.TEXT_HTML)
417 public Response getOpeningNodeGames(@PathParam("code") String code, @PathParam("status") String status){
418 Viewable v = checkLogin();
420 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
422 final Document got = stat.path("openings").path(code).path(status).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
423 return Response.ok(viewable("opening_games.fmt", got,"code",code,"color",status)).build();
427 @Path("openings/{code}.png")
428 @Produces("image/png")
429 public Response getOpeningBoardImage(
430 @PathParam("code") String code,
431 @QueryParam("fieldSize") @DefaultValue("40") int fieldSize
432 ) throws IllegalPositionException {
433 Board b = Board.valueOf(code);
434 ResponseBuilder resp = Response.ok();
435 CacheControl cc = new CacheControl();
437 resp.cacheControl(cc);
438 return resp.entity(BoardImage.draw(b, fieldSize)).build();
445 public static void main(String[] args) throws Exception {
447 if (args.length > 1) {
448 port = Integer.parseInt(args[0]);
450 String remoteAPI = args.length >= 2 ? args[1] : null;
451 String remoteStatistics = args.length >= 3 ? args[2] : null;
453 Locale.setDefault(Locale.ROOT);
455 Callable<Void> r = startServers(port, remoteAPI, remoteStatistics);
457 if (args.length < 3 || !args[args.length - 1].equals("--kill")) {
458 System.out.println("Hit enter to stop it...");
461 synchronized (UI.class) {
469 static Callable<Void> startServers(int port, String remoteAPI, String remoteStatistics) throws Exception {
470 Client client = new Client();
471 Client client1 = new Client();
473 final HttpServer apiServer;
474 if (remoteAPI == null) {
475 throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
477 base = client.resource(new URI(remoteAPI));
481 if (remoteStatistics == null) {
482 throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
484 stat = client1.resource(new URI("http://localhost:9444"));
487 ResourceConfig rc = new PackagesResourceConfig(
488 "cz.xelfi.quoridor.freemarkerdor"
491 final String baseUri = "http://localhost:" + port + "/";
492 final HttpServer server = HttpServerFactory.create(baseUri, rc);
494 System.out.println("Quoridor started at port " + port);
496 return new Callable<Void>() {
497 public Void call() throws Exception {
498 if (apiServer != null) {
507 private Viewable viewable(String page, Document doc, Object... more) {
508 ResourceBundle rb = null;
509 String lng = user == null ? null : user.getProperty("language"); // NOI18N
510 Locale locale = null;
513 Locale l = new Locale(lng);
514 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
516 } catch (MissingResourceException e) {
521 for (Locale l : headers.getAcceptableLanguages()) {
523 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
526 } catch (MissingResourceException e) {
532 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
533 locale = Locale.ENGLISH;
536 Map<String,Object> map = new HashMap<String,Object>();
537 class ConvertToDate extends HashMap<Object,Object> {
539 public Object get(Object o) {
540 long time = Long.parseLong(o.toString());
541 return new Date(time);
545 map.put("locale", locale.toString());
548 map.put("user", user.getId());
549 map.put("email", user.getProperty("email"));
551 map.put("bundle", rb);
552 map.put("toDate", new ConvertToDate());
553 map.put("now", System.currentTimeMillis());
554 map.put("version", version);
555 for (int i = 0; i < more.length; i += 2) {
556 map.put((String)more[i],more[i + 1]);
558 return new Viewable(page, map);
562 private static boolean isMobile(HttpHeaders headers) {
563 final String[] keywords = {
566 List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
568 for (String a : agent) {
569 for (String k : keywords) {