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.HashMap;
43 import java.util.List;
44 import java.util.Locale;
46 import java.util.MissingResourceException;
47 import java.util.Properties;
48 import java.util.ResourceBundle;
49 import java.util.concurrent.Callable;
50 import javax.ws.rs.DefaultValue;
51 import javax.ws.rs.FormParam;
52 import javax.ws.rs.GET;
53 import javax.ws.rs.POST;
54 import javax.ws.rs.Path;
55 import javax.ws.rs.PathParam;
56 import javax.ws.rs.Produces;
57 import javax.ws.rs.QueryParam;
58 import javax.ws.rs.core.CacheControl;
59 import javax.ws.rs.core.Context;
60 import javax.ws.rs.core.Cookie;
61 import javax.ws.rs.core.HttpHeaders;
62 import javax.ws.rs.core.MediaType;
63 import javax.ws.rs.core.NewCookie;
64 import javax.ws.rs.core.Response;
65 import javax.ws.rs.core.Response.ResponseBuilder;
66 import org.openide.util.Exceptions;
67 import org.w3c.dom.Document;
71 * @author Jaroslav Tulach <jtulach@netbeans.org>
74 public final class UI {
75 private static final String version;
77 Properties p = new Properties();
79 InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/org.apidesign/freemarkerdor/pom.properties"); // NOI18N
83 } catch (IOException ex) {
86 version = p.getProperty("version", "unknown"); // NOI18N
88 private static WebResource base;
91 private HttpHeaders headers;
92 private UserInfo user;
98 private Viewable checkLogin() {
99 Cookie cookie = headers.getCookies().get("login");
100 if (cookie != null) {
101 String id = cookie.getValue();
104 us = base.path("users").queryParam("loginID", id).
105 accept(MediaType.TEXT_XML).get(UserInfo.class);
106 } catch (Exception ex) {
107 ex.printStackTrace();
110 if (us != null && us.getId().length() > 0) {
116 return viewable("login.fmt", null);
121 @Produces(MediaType.TEXT_HTML)
122 public Response login(
123 @FormParam("name") String name, @FormParam("password") String password
125 uuid = base.path("login").queryParam("name", name).queryParam("password", password).
126 accept(MediaType.TEXT_PLAIN).put(String.class);
128 user = new UserInfo(name);
129 NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
130 return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
132 Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
133 return Response.status(1).entity(v).build();
138 @Produces(MediaType.TEXT_HTML)
139 public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
140 Viewable v = checkLogin();
141 ResponseBuilder resp = Response.ok();
143 v = welcomeImpl("maxItems", maxItems);
145 CacheControl cc = new CacheControl();
147 resp.cacheControl(cc);
148 return resp.entity(v).build();
152 @Path("games/{id}.png")
153 @Produces("image/png")
154 public Response getBoardImage(
155 @PathParam("id") String id,
156 @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
157 @QueryParam("move") @DefaultValue("-1") int move
158 ) throws IllegalPositionException {
159 WebResource wr = base.path("games").path(id);
161 wr = wr.queryParam("move", "" + move);
163 String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
164 Board b = Board.valueOf(txt);
165 ResponseBuilder resp = Response.ok();
166 CacheControl cc = new CacheControl();
168 resp.cacheControl(cc);
169 return resp.entity(BoardImage.draw(b, fieldSize)).build();
173 private Response board(String id) {
174 return board(id, "", null);
178 @Produces(MediaType.TEXT_HTML)
179 public Response board(
180 @PathParam("id") String id,
181 @QueryParam("format") @DefaultValue("") String format,
182 @QueryParam("move") @DefaultValue("-1") String move
184 return board(id, null, format, move);
186 private Response board(@PathParam("id") String id, String msg, String format, String m) {
187 Viewable v = checkLogin();
189 return Response.ok().entity(v).build();
193 move = Integer.parseInt(m);
194 } catch (NumberFormatException ex) {
197 WebResource url = base.path("games").path(id);
199 url = url.queryParam("move", "" + move);
201 ResponseBuilder resp = Response.ok();
202 CacheControl cc = new CacheControl();
204 resp.cacheControl(cc);
205 Cookie cFormat = headers.getCookies().get("format");
206 if (format.length() == 0) {
207 if (cFormat != null) {
208 format = cFormat.getValue();
210 if (isMobile(headers)) {
215 if (cFormat == null || !format.equals(cFormat.getValue())) {
216 resp.cookie(new NewCookie("format", format));
220 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
223 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
224 } catch (IllegalPositionException ex) {
225 Exceptions.printStackTrace(ex);
228 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
229 return resp.entity(v).build();
233 @Path("games/{id}/move")
234 @Produces(MediaType.TEXT_HTML)
235 public Response move(
236 @PathParam("id") String id,
237 @QueryParam("type") String type,
238 @QueryParam("direction") String direction,
239 @QueryParam("direction-next") @DefaultValue("") String directionNext,
240 @QueryParam("column") @DefaultValue("") String column,
241 @QueryParam("row") @DefaultValue("") String row
243 Viewable v = checkLogin();
245 return Response.ok().entity(v).build();
247 WebResource wr = base.path("games").path(id).
248 queryParam("loginID", uuid).
249 queryParam("player", user.getId());
251 if (type.equals("resign")) {
252 wr.queryParam("move", "RESIGN").put();
255 if (type.equals("fence")) {
256 wr.queryParam("move", direction.charAt(0) + column + row).put();
259 if (type.equals("move")) {
260 wr.queryParam("move", direction + directionNext).put();
263 } catch (UniformInterfaceException ex) {
264 return board(id, "WRONG_MOVE", "-1");
270 @Path("games/{id}/comment")
271 @Produces(MediaType.TEXT_HTML)
272 public Response comment(
273 @PathParam("id") String id,
274 @QueryParam("comment") String comment
276 Viewable v = checkLogin();
278 return Response.ok().entity(v).build();
280 WebResource wr = base.path("games").path(id).
281 queryParam("loginID", uuid).
282 queryParam("player", user.getId()).
283 queryParam("comment", comment);
290 @Path("games/create")
291 @Produces(MediaType.TEXT_HTML)
292 public Response create(
293 @QueryParam("white") String white,
294 @QueryParam("black") String black
296 Viewable v = checkLogin();
298 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
301 if (user.getId().equals(white) || user.getId().equals(black)) {
304 queryParam("loginID", uuid).
305 queryParam("white", white).
306 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
307 return Response.ok(welcomeImpl()).build();
309 return Response.status(Response.Status.NOT_FOUND).
310 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
314 private Viewable welcomeImpl(Object... args) {
315 final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
316 return viewable("index.fmt", got, args);
322 public Response changeOptions(
323 @QueryParam("email") String email,
324 @QueryParam("language") String language
326 Viewable v = checkLogin();
328 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
332 UserInfo ui = base.path("users/" + user.getId()).
333 queryParam("loginID", uuid).
334 queryParam("name", "email").
335 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
338 if (language != null) {
339 UserInfo ui = base.path("users/" + user.getId()).
340 queryParam("loginID", uuid).
341 queryParam("name", "language").
342 queryParam("value", language).
343 accept(MediaType.TEXT_XML).post(UserInfo.class);
353 public static void main(String[] args) throws Exception {
355 if (args.length > 1) {
356 port = Integer.parseInt(args[0]);
358 String remoteAPI = args.length >= 2 ? args[1] : null;
360 Locale.setDefault(Locale.ROOT);
362 Callable<Void> r = startServers(port, remoteAPI);
364 if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
365 System.out.println("Hit enter to stop it...");
368 synchronized (UI.class) {
376 static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
377 Client client = new Client();
379 final HttpServer apiServer;
380 if (remoteAPI == null) {
381 throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
383 base = client.resource(new URI(remoteAPI));
387 ResourceConfig rc = new PackagesResourceConfig(
388 "cz.xelfi.quoridor.freemarkerdor"
391 final String baseUri = "http://localhost:" + port + "/";
392 final HttpServer server = HttpServerFactory.create(baseUri, rc);
394 System.out.println("Quoridor started at port " + port);
396 return new Callable<Void>() {
397 public Void call() throws Exception {
398 if (apiServer != null) {
407 private Viewable viewable(String page, Document doc, Object... more) {
408 ResourceBundle rb = null;
409 String lng = user == null ? null : user.getProperty("language"); // NOI18N
412 Locale l = new Locale(lng);
413 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
414 } catch (MissingResourceException e) {
419 for (Locale l : headers.getAcceptableLanguages()) {
421 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
422 } catch (MissingResourceException e) {
428 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
431 Map<String,Object> map = new HashMap<String,Object>();
434 map.put("user", user.getId());
435 map.put("email", user.getProperty("email"));
437 map.put("bundle", rb);
438 map.put("now", System.currentTimeMillis());
439 map.put("version", version);
440 for (int i = 0; i < more.length; i += 2) {
441 map.put((String)more[i],more[i + 1]);
443 return new Viewable(page, map);
447 private static boolean isMobile(HttpHeaders headers) {
448 final String[] keywords = {
451 List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
453 for (String a : agent) {
454 for (String k : keywords) {