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.client.config.DefaultClientConfig;
33 import com.sun.jersey.api.container.httpserver.HttpServerFactory;
34 import com.sun.jersey.api.core.PackagesResourceConfig;
35 import com.sun.jersey.api.core.ResourceConfig;
36 import com.sun.jersey.api.view.Viewable;
37 import com.sun.net.httpserver.HttpServer;
38 import cz.xelfi.quoridor.Board;
39 import cz.xelfi.quoridor.IllegalPositionException;
40 import java.io.IOException;
41 import java.io.InputStream;
43 import java.util.HashMap;
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();
211 if (cFormat == null || !format.equals(cFormat.getValue())) {
212 resp.cookie(new NewCookie("format", format));
216 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
219 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
220 } catch (IllegalPositionException ex) {
221 Exceptions.printStackTrace(ex);
224 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
225 return resp.entity(v).build();
229 @Path("games/{id}/move")
230 @Produces(MediaType.TEXT_HTML)
231 public Response move(
232 @PathParam("id") String id,
233 @QueryParam("type") String type,
234 @QueryParam("direction") String direction,
235 @QueryParam("direction-next") @DefaultValue("") String directionNext,
236 @QueryParam("column") @DefaultValue("") String column,
237 @QueryParam("row") @DefaultValue("") String row
239 Viewable v = checkLogin();
241 return Response.ok().entity(v).build();
243 WebResource wr = base.path("games").path(id).
244 queryParam("loginID", uuid).
245 queryParam("player", user.getId());
247 if (type.equals("resign")) {
248 wr.queryParam("move", "RESIGN").put();
251 if (type.equals("fence")) {
252 wr.queryParam("move", direction.charAt(0) + column + row).put();
255 if (type.equals("move")) {
256 wr.queryParam("move", direction + directionNext).put();
259 } catch (UniformInterfaceException ex) {
260 return board(id, "WRONG_MOVE", "-1");
266 @Path("games/{id}/comment")
267 @Produces(MediaType.TEXT_HTML)
268 public Response comment(
269 @PathParam("id") String id,
270 @QueryParam("comment") String comment
272 Viewable v = checkLogin();
274 return Response.ok().entity(v).build();
276 WebResource wr = base.path("games").path(id).
277 queryParam("loginID", uuid).
278 queryParam("player", user.getId()).
279 queryParam("comment", comment);
286 @Path("games/create")
287 @Produces(MediaType.TEXT_HTML)
288 public Response create(
289 @QueryParam("white") String white,
290 @QueryParam("black") String black
292 Viewable v = checkLogin();
294 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
297 if (user.getId().equals(white) || user.getId().equals(black)) {
300 queryParam("loginID", uuid).
301 queryParam("white", white).
302 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
303 return Response.ok(welcomeImpl()).build();
305 return Response.status(Response.Status.NOT_FOUND).
306 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
310 private Viewable welcomeImpl(Object... args) {
311 final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
312 return viewable("index.fmt", got, args);
318 public Response changeOptions(
319 @QueryParam("email") String email,
320 @QueryParam("language") String language
322 Viewable v = checkLogin();
324 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
328 UserInfo ui = base.path("users/" + user.getId()).
329 queryParam("loginID", uuid).
330 queryParam("name", "email").
331 queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
334 if (language != null) {
335 UserInfo ui = base.path("users/" + user.getId()).
336 queryParam("loginID", uuid).
337 queryParam("name", "language").
338 queryParam("value", language).
339 accept(MediaType.TEXT_XML).post(UserInfo.class);
349 public static void main(String[] args) throws Exception {
351 if (args.length > 1) {
352 port = Integer.parseInt(args[0]);
354 String remoteAPI = args.length >= 2 ? args[1] : null;
356 Locale.setDefault(Locale.ROOT);
358 Callable<Void> r = startServers(port, remoteAPI);
360 if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
361 System.out.println("Hit enter to stop it...");
364 synchronized (UI.class) {
372 static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
373 Client client = new Client();
375 final HttpServer apiServer;
376 if (remoteAPI == null) {
377 throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
379 base = client.resource(new URI(remoteAPI));
383 ResourceConfig rc = new PackagesResourceConfig(
384 "cz.xelfi.quoridor.freemarkerdor"
387 final String baseUri = "http://localhost:" + port + "/";
388 final HttpServer server = HttpServerFactory.create(baseUri, rc);
390 System.out.println("Quoridor started at port " + port);
392 return new Callable<Void>() {
393 public Void call() throws Exception {
394 if (apiServer != null) {
403 private Viewable viewable(String page, Document doc, Object... more) {
404 ResourceBundle rb = null;
405 String lng = user == null ? null : user.getProperty("language"); // NOI18N
408 Locale l = new Locale(lng);
409 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
410 } catch (MissingResourceException e) {
415 for (Locale l : headers.getAcceptableLanguages()) {
417 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
418 } catch (MissingResourceException e) {
424 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
427 Map<String,Object> map = new HashMap<String,Object>();
430 map.put("user", user.getId());
431 map.put("email", user.getProperty("email"));
433 map.put("bundle", rb);
434 map.put("now", System.currentTimeMillis());
435 map.put("version", version);
436 for (int i = 0; i < more.length; i += 2) {
437 map.put((String)more[i],more[i + 1]);
439 return new Viewable(page, map);