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 cz.xelfi.quoridor.webidor.resources.Quoridor;
40 import java.awt.Image;
42 import java.io.IOException;
43 import java.io.InputStream;
45 import java.util.HashMap;
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.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;
99 private Viewable checkLogin() {
100 Cookie cookie = headers.getCookies().get("login");
101 if (cookie != null) {
102 String id = cookie.getValue();
105 us = base.path("login").queryParam("id", id).
106 accept(MediaType.TEXT_PLAIN).get(String.class);
107 } catch (UniformInterfaceException ex) {
108 ex.printStackTrace();
111 if (us.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);
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 Viewable welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
141 Viewable v = checkLogin();
145 return welcomeImpl("maxItems", maxItems);
149 @Path("games/{id}.png")
150 @Produces("image/png")
151 public Image getBoardImage(
152 @PathParam("id") String id,
153 @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
154 @QueryParam("move") @DefaultValue("-1") int move
155 ) throws IllegalPositionException {
156 WebResource wr = base.path("games").path(id);
158 wr = wr.queryParam("move", "" + move);
160 String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
161 Board b = Board.valueOf(txt);
162 return BoardImage.draw(b, fieldSize);
166 private Response board(String id) {
167 return board(id, "", null);
171 @Produces(MediaType.TEXT_HTML)
172 public Response board(
173 @PathParam("id") String id,
174 @QueryParam("format") @DefaultValue("") String format,
175 @QueryParam("move") @DefaultValue("-1") String move
177 return board(id, null, format, move);
179 private Response board(@PathParam("id") String id, String msg, String format, String m) {
180 Viewable v = checkLogin();
182 return Response.ok().entity(v).build();
186 move = Integer.parseInt(m);
187 } catch (NumberFormatException ex) {
190 WebResource url = base.path("games").path(id);
192 url = url.queryParam("move", "" + move);
194 ResponseBuilder resp = Response.ok();
195 Cookie cFormat = headers.getCookies().get("format");
196 if (format.length() == 0) {
197 if (cFormat != null) {
198 format = cFormat.getValue();
201 if (cFormat == null || !format.equals(cFormat.getValue())) {
202 resp.cookie(new NewCookie("format", format));
206 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
209 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
210 } catch (IllegalPositionException ex) {
211 Exceptions.printStackTrace(ex);
214 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
215 return resp.entity(v).build();
219 @Path("games/{id}/move")
220 @Produces(MediaType.TEXT_HTML)
221 public Response move(
222 @PathParam("id") String id,
223 @QueryParam("type") String type,
224 @QueryParam("direction") String direction,
225 @QueryParam("direction-next") @DefaultValue("") String directionNext,
226 @QueryParam("column") @DefaultValue("") String column,
227 @QueryParam("row") @DefaultValue("") String row
229 Viewable v = checkLogin();
231 return Response.ok().entity(v).build();
233 WebResource wr = base.path("games").path(id).
234 queryParam("loginID", uuid).
235 queryParam("player", user);
237 if (type.equals("resign")) {
238 wr.queryParam("move", "RESIGN").put();
241 if (type.equals("fence")) {
242 wr.queryParam("move", direction.charAt(0) + column + row).put();
245 if (type.equals("move")) {
246 wr.queryParam("move", direction + directionNext).put();
249 } catch (UniformInterfaceException ex) {
250 return board(id, "WRONG_MOVE", "-1");
256 @Path("games/{id}/comment")
257 @Produces(MediaType.TEXT_HTML)
258 public Response comment(
259 @PathParam("id") String id,
260 @QueryParam("comment") String comment
262 Viewable v = checkLogin();
264 return Response.ok().entity(v).build();
266 WebResource wr = base.path("games").path(id).
267 queryParam("loginID", uuid).
268 queryParam("player", user).
269 queryParam("comment", comment);
276 @Path("games/create")
277 @Produces(MediaType.TEXT_HTML)
278 public Response create(
279 @QueryParam("white") String white,
280 @QueryParam("black") String black
282 Viewable v = checkLogin();
284 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
287 if (user.equals(white) || user.equals(black)) {
290 queryParam("loginID", uuid).
291 queryParam("white", white).
292 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
293 return Response.ok(welcomeImpl()).build();
295 return Response.status(Response.Status.NOT_FOUND).
296 entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
300 private Viewable welcomeImpl(Object... args) {
301 final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
302 return viewable("index.fmt", got, args);
309 public static void main(String[] args) throws Exception {
311 if (args.length > 1) {
312 port = Integer.parseInt(args[0]);
314 String remoteAPI = args.length > 2 ? args[1] : null;
317 Callable<Void> r = startServers(port, remoteAPI);
319 if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
320 System.out.println("Hit enter to stop it...");
323 synchronized (UI.class) {
331 static Callable<Void> startServers(int port, String remoteAPI) throws Exception {
332 Client client = new Client();
334 final HttpServer apiServer;
335 if (remoteAPI == null) {
336 int localAPIPort = port - 1;
337 apiServer = Quoridor.start(localAPIPort);
338 base = client.resource(new URI("http://localhost:" + localAPIPort + "/api/"));
340 base = client.resource(new URI(remoteAPI));
344 ResourceConfig rc = new PackagesResourceConfig(
345 "cz.xelfi.quoridor.freemarkerdor"
348 final String baseUri = "http://localhost:" + port + "/";
349 final HttpServer server = HttpServerFactory.create(baseUri, rc);
351 System.out.println("Quoridor started at port " + port);
353 return new Callable<Void>() {
354 public Void call() throws Exception {
355 if (apiServer != null) {
364 private Viewable viewable(String page, Document doc, Object... more) {
365 ResourceBundle rb = null;
366 for (Locale l : headers.getAcceptableLanguages()) {
368 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
369 } catch (MissingResourceException e) {
374 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
377 Map<String,Object> map = new HashMap<String,Object>();
379 map.put("user", user);
380 map.put("bundle", rb);
381 map.put("now", System.currentTimeMillis());
382 map.put("version", version);
383 for (int i = 0; i < more.length; i += 2) {
384 map.put((String)more[i],more[i + 1]);
386 return new Viewable(page, map);