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;
92 private HttpHeaders headers;
93 private UserInfo user;
99 private Viewable checkLogin() {
100 Cookie cookie = headers.getCookies().get("login");
101 if (cookie != null) {
102 String id = cookie.getValue();
105 us = base.path("users").queryParam("loginID", id).
106 accept(MediaType.TEXT_XML).get(UserInfo.class);
107 } catch (Exception ex) {
108 ex.printStackTrace();
111 if (us != null && us.getId().length() > 0) {
117 return viewable("login.fmt", null);
122 @Produces(MediaType.TEXT_HTML)
123 public Response login(
124 @FormParam("name") String name, @FormParam("password") String password
126 uuid = base.path("login").queryParam("name", name).queryParam("password", password).
127 accept(MediaType.TEXT_PLAIN).put(String.class);
129 user = new UserInfo(name);
130 NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
131 return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
133 Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
134 return Response.status(1).entity(v).build();
139 @Produces(MediaType.TEXT_HTML)
140 public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
141 Viewable v = checkLogin();
142 ResponseBuilder resp = Response.ok();
144 v = welcomeImpl("maxItems", maxItems);
146 CacheControl cc = new CacheControl();
148 resp.cacheControl(cc);
149 return resp.entity(v).build();
153 @Path("games/{id}.png")
154 @Produces("image/png")
155 public Response getBoardImage(
156 @PathParam("id") String id,
157 @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
158 @QueryParam("move") @DefaultValue("-1") int move
159 ) throws IllegalPositionException {
160 WebResource wr = base.path("games").path(id);
162 wr = wr.queryParam("move", "" + move);
164 String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
165 Board b = Board.valueOf(txt);
166 ResponseBuilder resp = Response.ok();
167 CacheControl cc = new CacheControl();
169 resp.cacheControl(cc);
170 return resp.entity(BoardImage.draw(b, fieldSize)).build();
174 private Response board(String id) {
175 return board(id, "", null);
179 @Produces(MediaType.TEXT_HTML)
180 public Response board(
181 @PathParam("id") String id,
182 @QueryParam("format") @DefaultValue("") String format,
183 @QueryParam("move") @DefaultValue("-1") String move
185 return board(id, null, format, move);
187 private Response board(@PathParam("id") String id, String msg, String format, String m) {
188 Viewable v = checkLogin();
190 return Response.ok().entity(v).build();
194 move = Integer.parseInt(m);
195 } catch (NumberFormatException ex) {
198 WebResource url = base.path("games").queryParam("loginID", uuid).path(id);
200 url = url.queryParam("move", "" + move);
202 ResponseBuilder resp = Response.ok();
203 CacheControl cc = new CacheControl();
205 resp.cacheControl(cc);
206 Cookie cFormat = headers.getCookies().get("format");
207 if (format.length() == 0) {
208 if (cFormat != null) {
209 format = cFormat.getValue();
211 if (isMobile(headers)) {
216 if (cFormat == null || !format.equals(cFormat.getValue())) {
217 resp.cookie(new NewCookie("format", format));
221 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
224 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
225 } catch (IllegalPositionException ex) {
226 Exceptions.printStackTrace(ex);
229 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
230 return resp.entity(v).build();
234 @Path("games/{id}/move")
235 @Produces(MediaType.TEXT_HTML)
236 public Response move(
237 @PathParam("id") String id,
238 @QueryParam("type") String type,
239 @QueryParam("direction") String direction,
240 @QueryParam("direction-next") @DefaultValue("") String directionNext,
241 @QueryParam("column") @DefaultValue("") String column,
242 @QueryParam("row") @DefaultValue("") String row
244 Viewable v = checkLogin();
246 return Response.ok().entity(v).build();
248 WebResource wr = base.path("games").path(id).
249 queryParam("loginID", uuid).
250 queryParam("player", user.getId());
252 if (type.equals("resign")) {
253 wr.queryParam("move", "RESIGN").put();
256 if (type.equals("fence")) {
257 wr.queryParam("move", direction.charAt(0) + column + row).put();
260 if (type.equals("move")) {
261 wr.queryParam("move", direction + directionNext).put();
264 } catch (UniformInterfaceException ex) {
265 return board(id, "WRONG_MOVE", "-1");
271 @Path("games/{id}/comment")
272 @Produces(MediaType.TEXT_HTML)
273 public Response comment(
274 @PathParam("id") String id,
275 @QueryParam("comment") String comment
277 Viewable v = checkLogin();
279 return Response.ok().entity(v).build();
281 WebResource wr = base.path("games").path(id).
282 queryParam("loginID", uuid).
283 queryParam("player", user.getId()).
284 queryParam("comment", comment);
291 @Path("games/create")
292 @Produces(MediaType.TEXT_HTML)
293 public Response create(
294 @QueryParam("white") String white,
295 @QueryParam("black") String black
297 Viewable v = checkLogin();
299 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
302 if (user.getId().equals(white) || user.getId().equals(black)) {
305 queryParam("loginID", uuid).
306 queryParam("white", white).
307 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
308 return Response.ok(welcomeImpl()).build();
310 return Response.status(Response.Status.NOT_FOUND).
311 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
315 private Viewable welcomeImpl(Object... args) {
316 final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
317 return viewable("index.fmt", got, args);
323 public Response changeOptions(
324 @QueryParam("email") String email,
325 @QueryParam("language") String language
327 Viewable v = checkLogin();
329 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
333 UserInfo ui = base.path("users/" + user.getId()).
334 queryParam("loginID", uuid).
335 queryParam("name", "email").
336 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
339 if (language != null) {
340 UserInfo ui = base.path("users/" + user.getId()).
341 queryParam("loginID", uuid).
342 queryParam("name", "language").
343 queryParam("value", language).
344 accept(MediaType.TEXT_XML).post(UserInfo.class);
354 public static void main(String[] args) throws Exception {
356 if (args.length > 1) {
357 port = Integer.parseInt(args[0]);
359 String remoteAPI = args.length >= 2 ? args[1] : null;
361 Locale.setDefault(Locale.ROOT);
363 Callable<Void> r = startServers(port, remoteAPI);
365 if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
366 System.out.println("Hit enter to stop it...");
369 synchronized (UI.class) {
377 static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
378 Client client = new Client();
380 final HttpServer apiServer;
381 if (remoteAPI == null) {
382 throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
384 base = client.resource(new URI(remoteAPI));
388 ResourceConfig rc = new PackagesResourceConfig(
389 "cz.xelfi.quoridor.freemarkerdor"
392 final String baseUri = "http://localhost:" + port + "/";
393 final HttpServer server = HttpServerFactory.create(baseUri, rc);
395 System.out.println("Quoridor started at port " + port);
397 return new Callable<Void>() {
398 public Void call() throws Exception {
399 if (apiServer != null) {
408 private Viewable viewable(String page, Document doc, Object... more) {
409 ResourceBundle rb = null;
410 String lng = user == null ? null : user.getProperty("language"); // NOI18N
411 Locale locale = null;
414 Locale l = new Locale(lng);
415 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
417 } catch (MissingResourceException e) {
422 for (Locale l : headers.getAcceptableLanguages()) {
424 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
427 } catch (MissingResourceException e) {
433 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
434 locale = Locale.ENGLISH;
437 Map<String,Object> map = new HashMap<String,Object>();
438 class ConvertToDate extends HashMap<Object,Object> {
440 public Object get(Object o) {
441 long time = Long.parseLong(o.toString());
442 return new Date(time);
446 map.put("locale", locale.toString());
449 map.put("user", user.getId());
450 map.put("email", user.getProperty("email"));
452 map.put("bundle", rb);
453 map.put("toDate", new ConvertToDate());
454 map.put("now", System.currentTimeMillis());
455 map.put("version", version);
456 for (int i = 0; i < more.length; i += 2) {
457 map.put((String)more[i],more[i + 1]);
459 return new Viewable(page, map);
463 private static boolean isMobile(HttpHeaders headers) {
464 final String[] keywords = {
467 List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
469 for (String a : agent) {
470 for (String k : keywords) {