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;
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.Context;
59 import javax.ws.rs.core.Cookie;
60 import javax.ws.rs.core.HttpHeaders;
61 import javax.ws.rs.core.MediaType;
62 import javax.ws.rs.core.NewCookie;
63 import javax.ws.rs.core.Response;
64 import javax.ws.rs.core.Response.ResponseBuilder;
65 import org.openide.util.Exceptions;
66 import org.w3c.dom.Document;
70 * @author Jaroslav Tulach <jtulach@netbeans.org>
73 public final class UI {
74 private static final String version;
76 Properties p = new Properties();
78 InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/org.apidesign/freemarkerdor/pom.properties"); // NOI18N
82 } catch (IOException ex) {
85 version = p.getProperty("version", "unknown"); // NOI18N
87 private static WebResource base;
90 private HttpHeaders headers;
97 private Viewable checkLogin() {
98 Cookie cookie = headers.getCookies().get("login");
100 String id = cookie.getValue();
103 us = base.path("login").queryParam("id", id).
104 accept(MediaType.TEXT_PLAIN).get(String.class);
105 } catch (UniformInterfaceException ex) {
106 ex.printStackTrace();
109 if (us.length() > 0) {
115 return viewable("login.fmt", null);
120 @Produces(MediaType.TEXT_HTML)
121 public Response login(
122 @FormParam("name") String name, @FormParam("password") String password
124 uuid = base.path("login").queryParam("name", name).queryParam("password", password).
125 accept(MediaType.TEXT_PLAIN).put(String.class);
128 NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
129 return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
131 Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
132 return Response.status(1).entity(v).build();
137 @Produces(MediaType.TEXT_HTML)
138 public Viewable welcome() {
139 Viewable v = checkLogin();
143 return welcomeImpl();
146 private Response board(String id) {
147 return board(id, "", null);
151 @Produces(MediaType.TEXT_HTML)
152 public Response board(
153 @PathParam("id") String id,
154 @QueryParam("format") @DefaultValue("") String format,
155 @QueryParam("move") @DefaultValue("-1") String move
157 return board(id, null, format, move);
159 private Response board(@PathParam("id") String id, String msg, String format, String m) {
160 Viewable v = checkLogin();
162 return Response.ok().entity(v).build();
166 move = Integer.parseInt(m);
167 } catch (NumberFormatException ex) {
170 WebResource url = base.path("games").path(id);
172 url = url.queryParam("move", "" + move);
174 ResponseBuilder resp = Response.ok();
175 Cookie cFormat = headers.getCookies().get("format");
176 if (format.length() == 0) {
177 if (cFormat != null) {
178 format = cFormat.getValue();
181 if (cFormat == null || !format.equals(cFormat.getValue())) {
182 resp.cookie(new NewCookie("format", format));
186 Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
189 b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
190 } catch (IllegalPositionException ex) {
191 Exceptions.printStackTrace(ex);
194 v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b);
195 return resp.entity(v).build();
199 @Path("games/{id}/move")
200 @Produces(MediaType.TEXT_HTML)
201 public Response move(
202 @PathParam("id") String id,
203 @QueryParam("type") String type,
204 @QueryParam("direction") String direction,
205 @QueryParam("direction-next") @DefaultValue("") String directionNext,
206 @QueryParam("column") @DefaultValue("") String column,
207 @QueryParam("row") @DefaultValue("") String row
209 Viewable v = checkLogin();
211 return Response.ok().entity(v).build();
213 WebResource wr = base.path("games").path(id).
214 queryParam("loginID", uuid).
215 queryParam("player", user);
217 if (type.equals("resign")) {
218 wr.queryParam("move", "RESIGN").put();
221 if (type.equals("fence")) {
222 wr.queryParam("move", direction.charAt(0) + column + row).put();
225 if (type.equals("move")) {
226 wr.queryParam("move", direction + directionNext).put();
229 } catch (UniformInterfaceException ex) {
230 return board(id, "WRONG_MOVE", "-1");
236 @Path("games/create")
237 @Produces(MediaType.TEXT_HTML)
238 public Response create(
239 @QueryParam("white") String white,
240 @QueryParam("black") String black
242 Viewable v = checkLogin();
244 return Response.status(Response.Status.FORBIDDEN).entity(v).build();
247 if (user.equals(white) || user.equals(black)) {
250 queryParam("loginID", uuid).
251 queryParam("white", white).
252 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
253 return Response.ok(welcomeImpl()).build();
255 return Response.status(Response.Status.NOT_FOUND).
256 entity(welcomeImpl("message", "You (" + user + ") must be white or black!")).build();
260 private Viewable welcomeImpl(Object... args) {
261 final Document got = base.path("games").accept(MediaType.TEXT_XML).get(Document.class);
262 return viewable("index.fmt", got, args);
269 public static void main(String[] args) throws Exception {
271 if (args.length > 1) {
272 port = Integer.parseInt(args[0]);
276 Callable<Void> r = startServers(port);
278 if (args.length < 2 || !args[1].equals("--kill")) {
279 System.out.println("Hit enter to stop it...");
282 synchronized (UI.class) {
290 static Callable<Void> startServers(int port) throws Exception {
292 if (System.getProperty("quoridor.dir") == null) {
293 File home = new File(System.getProperty("user.home"));
294 File quoridor = new File(home, ".quoridor");
295 System.setProperty("quoridor.dir", quoridor.getPath());
298 ResourceConfig rc = new PackagesResourceConfig(
299 "cz.xelfi.quoridor.webidor",
300 "cz.xelfi.quoridor.freemarkerdor"
303 Client client = new Client();
304 base = client.resource(new URI("http://localhost:" + port + "/api/"));
306 final String baseUri = "http://localhost:" + port + "/";
307 final HttpServer server = HttpServerFactory.create(baseUri, rc);
309 System.out.println("Quoridor started at port " + port);
311 return new Callable<Void>() {
312 public Void call() throws Exception {
319 private Viewable viewable(String page, Document doc, Object... more) {
320 ResourceBundle rb = null;
321 for (Locale l : headers.getAcceptableLanguages()) {
323 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
324 } catch (MissingResourceException e) {
329 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
332 Map<String,Object> map = new HashMap<String,Object>();
334 map.put("user", user);
335 map.put("bundle", rb);
336 map.put("now", System.currentTimeMillis());
337 map.put("version", version);
338 for (int i = 0; i < more.length; i += 2) {
339 map.put((String)more[i],more[i + 1]);
341 return new Viewable(page, map);