freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/UI.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 23 Oct 2010 22:51:43 +0200
changeset 271 aa1c63b58149
parent 264 d60370059c3c
child 278 3a472605338f
permissions -rw-r--r--
rekonq sends some strange language feel which cannot be parsed by Jersey. It is 'Bad Accept-Language field: cs,en-US;q=0.9,en;q=0.8, cz, en_US'
     1 /*
     2  * Quoridor server and related libraries
     3  * Copyright (C) 2009-2010 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://www.gnu.org/licenses/.
    17  */
    18 package cz.xelfi.quoridor.freemarkerdor;
    19 
    20 import com.sun.jersey.api.client.Client;
    21 import com.sun.jersey.api.client.UniformInterfaceException;
    22 import com.sun.jersey.api.client.WebResource;
    23 import com.sun.jersey.api.container.httpserver.HttpServerFactory;
    24 import com.sun.jersey.api.core.PackagesResourceConfig;
    25 import com.sun.jersey.api.core.ResourceConfig;
    26 import com.sun.jersey.api.view.Viewable;
    27 import com.sun.net.httpserver.HttpServer;
    28 import cz.xelfi.quoridor.Board;
    29 import cz.xelfi.quoridor.IllegalPositionException;
    30 import java.io.IOException;
    31 import java.io.InputStream;
    32 import java.io.StringWriter;
    33 import java.net.URI;
    34 import java.text.MessageFormat;
    35 import java.text.ParseException;
    36 import java.util.ArrayList;
    37 import java.util.Arrays;
    38 import java.util.Date;
    39 import java.util.HashMap;
    40 import java.util.List;
    41 import java.util.Locale;
    42 import java.util.Map;
    43 import java.util.MissingResourceException;
    44 import java.util.Properties;
    45 import java.util.ResourceBundle;
    46 import java.util.concurrent.Callable;
    47 import javax.ws.rs.DefaultValue;
    48 import javax.ws.rs.FormParam;
    49 import javax.ws.rs.GET;
    50 import javax.ws.rs.POST;
    51 import javax.ws.rs.Path;
    52 import javax.ws.rs.PathParam;
    53 import javax.ws.rs.Produces;
    54 import javax.ws.rs.QueryParam;
    55 import javax.ws.rs.WebApplicationException;
    56 import javax.ws.rs.core.CacheControl;
    57 import javax.ws.rs.core.Context;
    58 import javax.ws.rs.core.Cookie;
    59 import javax.ws.rs.core.HttpHeaders;
    60 import javax.ws.rs.core.MediaType;
    61 import javax.ws.rs.core.NewCookie;
    62 import javax.ws.rs.core.Response;
    63 import javax.ws.rs.core.Response.ResponseBuilder;
    64 import org.openide.util.Exceptions;
    65 import org.w3c.dom.Document;
    66 
    67 /**
    68  *
    69  * @author Jaroslav Tulach <jtulach@netbeans.org>
    70  */
    71 @Path("/")
    72 public final class UI {
    73     private static final String version;
    74     static {
    75         Properties p = new Properties();
    76         try {
    77             InputStream is = FreemarkerProcessor.class.getResourceAsStream("/META-INF/maven/cz.xelfi.quoridor/freemarkerdor/pom.properties"); // NOI18N
    78             if (is != null) {
    79                 p.load(is);
    80             }
    81         } catch (IOException ex) {
    82             ex.printStackTrace();
    83         }
    84         version = p.getProperty("version", "unknown"); // NOI18N
    85     }
    86     private static WebResource base;
    87     private static WebResource stat;
    88     private static WebResource web;
    89     private static Requests requests;
    90 
    91     @Context
    92     private HttpHeaders headers;
    93     private UserInfo user;
    94     private String uuid;
    95 
    96     public UI() {
    97     }
    98 
    99     private String login() {
   100         Cookie cookie = headers.getCookies().get("login");
   101         if (cookie != null) {
   102             return cookie.getValue();
   103         }
   104         return null;
   105     }
   106 
   107     private Viewable checkLogin() {
   108         String id = login();
   109         if (id != null) {
   110             UserInfo us;
   111             try {
   112                 us = base.path("users").queryParam("loginID", id).
   113                     accept(MediaType.TEXT_XML).get(UserInfo.class);
   114             } catch (Exception ex) {
   115                 ex.printStackTrace();
   116                 us = null;
   117             }
   118             if (us != null && us.getId().length() > 0) {
   119                 user = us;
   120                 uuid = id;
   121                 return null;
   122             }
   123         }
   124         return viewable("login.fmt", null);
   125     }
   126 
   127     @POST
   128     @Path("login")
   129     @Produces(MediaType.TEXT_HTML)
   130     public Response login(
   131         @FormParam("name") String name, @FormParam("password") String password
   132     ) throws Exception {
   133         uuid = base.path("login").queryParam("name", name).queryParam("password", password).
   134             accept(MediaType.TEXT_PLAIN).put(String.class);
   135         if (uuid != null) {
   136             user = new UserInfo(name);
   137             NewCookie nc = new NewCookie("login", uuid, null, null, null, 3600 * 24 * 7, false);
   138             return Response.ok().cookie(nc).entity(viewable("login.fmt", null)).build();
   139         } else {
   140             Viewable v = viewable("login.fmt", null, "message", "Invalid name or password: " + name);
   141             return Response.status(1).entity(v).build();
   142         }
   143     }
   144 
   145     @GET
   146     @Produces(MediaType.TEXT_HTML)
   147     public Response welcome(@QueryParam("maxItems") @DefaultValue("10") int maxItems) {
   148         Viewable v = checkLogin();
   149         ResponseBuilder resp = Response.ok();
   150         if (v == null) {
   151             v = welcomeImpl("maxItems", maxItems);
   152         }
   153         CacheControl cc = new CacheControl();
   154         cc.setNoCache(true);
   155         resp.cacheControl(cc);
   156         return resp.entity(v).build();
   157     }
   158 
   159     @GET
   160     @Path("games/{id}.png")
   161     @Produces("image/png")
   162     public Response getBoardImage(
   163         @PathParam("id") String id,
   164         @QueryParam("fieldSize") @DefaultValue("50") int fieldSize,
   165         @QueryParam("move") @DefaultValue("-1") int move
   166     ) throws IllegalPositionException {
   167         WebResource wr = base.path("games").path(id);
   168         if (move != -1) {
   169             wr = wr.queryParam("move", "" + move);
   170         }
   171         String txt = wr.accept(MediaType.TEXT_PLAIN).get(String.class);
   172         Board b = Board.valueOf(txt);
   173 //        Board b = new Board(txt);
   174         ResponseBuilder resp = Response.ok();
   175         CacheControl cc = new CacheControl();
   176         cc.setNoCache(true);
   177         resp.cacheControl(cc);
   178         return resp.entity(BoardImage.draw(b, fieldSize)).build();
   179     }
   180 
   181 
   182     private Response board(String id) {
   183         return board(id, "", null);
   184     }
   185     @GET
   186     @Path("games/{id}/")
   187     @Produces(MediaType.TEXT_HTML)
   188     public Response board(
   189         @PathParam("id") String id,
   190         @QueryParam("format") @DefaultValue("") String format,
   191         @QueryParam("move") @DefaultValue("-1") String move
   192     ) {
   193         return board(id, null, format, move);
   194     }
   195     private Response board(@PathParam("id") String id, String msg, String format, String m) {
   196         Viewable v = checkLogin();
   197         if (v != null) {
   198             return Response.ok().entity(v).build();
   199         }
   200         int move;
   201         try {
   202             move = Integer.parseInt(m);
   203         } catch (NumberFormatException ex) {
   204             move = -1;
   205         }
   206         WebResource url = base.path("games").queryParam("loginID", uuid).path(id);
   207         if (move >= 0) {
   208             url = url.queryParam("move", "" + move);
   209         }
   210         ResponseBuilder resp = Response.ok();
   211         CacheControl cc = new CacheControl();
   212         cc.setNoCache(true);
   213         resp.cacheControl(cc);
   214         Cookie cFormat = headers.getCookies().get("format");
   215         if (format.length() == 0) {
   216             if (cFormat != null) {
   217                 format = cFormat.getValue();
   218             } else {
   219                 if (isMobile(headers)) {
   220                     format = "small";
   221                 }
   222             }
   223         } else {
   224             if (cFormat == null || !format.equals(cFormat.getValue())) {
   225                 resp.cookie(new NewCookie("format", format));
   226             }
   227         }
   228 
   229         Document doc = url.accept(MediaType.TEXT_XML).get(Document.class);
   230         Board b;
   231         String t = doc.getElementsByTagName("board").item(0).getTextContent();
   232         try {
   233             b = Board.valueOf(doc.getElementsByTagName("board").item(0).getTextContent());
   234         } catch (Exception ex) {
   235 //            b = new Board(t);
   236 //        } catch (IllegalStateException ex) {
   237             Exceptions.printStackTrace(ex);
   238             b = Board.empty();
   239         }
   240         String bCode = null;
   241         try{
   242             bCode = stat.path("openings").path(b.getCode()+".check").queryParam("loginID", user.getId()).accept(MediaType.TEXT_PLAIN).get(String.class);
   243         }catch(Exception e){
   244             bCode = null;
   245         }
   246         if(bCode == null || "".equals(bCode))
   247             v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture", boardToPicture(b));
   248         else
   249             v = viewable("game.fmt", doc, "message", msg, "format", format, "board", b,"textPicture", boardToPicture(b),"bCode", bCode);
   250         return resp.entity(v).build();
   251     }
   252 
   253     private static String boardToPicture(Board b) {
   254         StringWriter w = new StringWriter();
   255         try {
   256             b.write(w);
   257         } catch (IOException ex) {
   258             return ex.toString();
   259         }
   260         return w.toString();
   261     }
   262 
   263     @GET
   264     @Path("games/{id}/move")
   265     @Produces(MediaType.TEXT_HTML)
   266     public Response move(
   267         @PathParam("id") String id,
   268         @QueryParam("type") String type,
   269         @QueryParam("direction") String direction,
   270         @QueryParam("direction-next") @DefaultValue("") String directionNext,
   271         @QueryParam("column") @DefaultValue("") String column,
   272         @QueryParam("row") @DefaultValue("") String row
   273     ) {
   274         Viewable v = checkLogin();
   275         if (v != null) {
   276             return Response.ok().entity(v).build();
   277         }
   278         WebResource wr = base.path("games").path(id).
   279             queryParam("loginID", uuid).
   280             queryParam("player", user.getId());
   281         try {
   282             if (type.equals("resign")) {
   283                 wr.queryParam("move", "RESIGN").put();
   284                 return board(id);
   285             }
   286             if (type.equals("fence")) {
   287                 wr.queryParam("move", direction.charAt(0) + column + row).put();
   288                 return board(id);
   289             }
   290             if (type.equals("move")) {
   291                 wr.queryParam("move", direction + directionNext).put();
   292                 return board(id);
   293             }
   294         } catch (UniformInterfaceException ex) {
   295             return board(id, "WRONG_MOVE", "-1");
   296         }
   297         return board(id);
   298     }
   299 
   300     @GET
   301     @Path("games/{id}/comment")
   302     @Produces(MediaType.TEXT_HTML)
   303     public Response comment(
   304         @PathParam("id") String id,
   305         @QueryParam("comment") String comment
   306     ) {
   307         Viewable v = checkLogin();
   308         if (v != null) {
   309             return Response.ok().entity(v).build();
   310         }
   311         WebResource wr = base.path("games").path(id).
   312             queryParam("loginID", uuid).
   313             queryParam("player", user.getId()).
   314             queryParam("comment", comment);
   315         wr.put();
   316         
   317         return board(id);
   318     }
   319 
   320     @GET
   321     @Path("games/create")
   322     @Produces(MediaType.TEXT_HTML)
   323     public Response create(
   324         @QueryParam("white") String white,
   325         @QueryParam("black") String black
   326     ) {
   327         Viewable v = checkLogin();
   328         if (v != null) {
   329             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   330         }
   331 
   332         if (user.getId().equals(white) || user.getId().equals(black)) {
   333             Object obj =
   334                 base.path("games").
   335                 queryParam("loginID", uuid).
   336                 queryParam("white", white).
   337                 queryParam("black", black).accept(MediaType.TEXT_XML).post(Document.class);
   338             return Response.ok(welcomeImpl()).build();
   339         } else {
   340             return Response.status(Response.Status.NOT_FOUND).
   341                 entity(welcomeImpl("message", "You (" + user.getId() + ") must be white or black!")).build();
   342         }
   343     }
   344 
   345     private Viewable welcomeImpl(Object... args) {
   346         final Document got = base.path("games").queryParam("loginID", uuid).accept(MediaType.TEXT_XML).get(Document.class);
   347         return viewable("index.fmt", got, args);
   348     }
   349 
   350     @Path("requests")
   351     public Requests getRequests() {
   352         if (requests == null) {
   353             requests = new Requests(web.path("requests"));
   354         }
   355         return requests;
   356     }
   357 
   358 
   359     @GET
   360     @Path("options")
   361     public Response changeOptions(
   362         @QueryParam("email") String email,
   363         @QueryParam("language") String language,
   364         @QueryParam("verified") String verified
   365     ) throws IOException {
   366         Viewable v = checkLogin();
   367         if (v != null) {
   368             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   369         }
   370 
   371         if (email != null) {
   372             if (getRequests().isVerified(verified)) {
   373                 UserInfo ui = base.path("users/" + user.getId()).
   374                     queryParam("loginID", uuid).
   375                     queryParam("name", "email").
   376                     queryParam("value", email).accept(MediaType.TEXT_XML).post(UserInfo.class);
   377             } else {
   378                 WebResource request;
   379                 request = web.path("options").queryParam("name", "email").queryParam("email", email);
   380                 URI callback = getRequests().register(login(), request);
   381 
   382                 ResourceBundle rb = bundle(null);
   383                 String subject = rb.getString("MSG_ChangeEmailSubject");
   384                 String text = MessageFormat.format(rb.getString("MSG_ChangeEmailText"), user.getId(), callback);
   385                 EmailService.getDefault().sendEmail(email, subject, text);
   386                 return Response.ok(viewable("email.fmt", null)).build();
   387 
   388             }
   389         }
   390 
   391         if (language != null) {
   392             UserInfo ui = base.path("users/" + user.getId()).
   393                 queryParam("loginID", uuid).
   394                 queryParam("name", "language").
   395                 queryParam("value", language).
   396                 accept(MediaType.TEXT_XML).post(UserInfo.class);
   397         }
   398 
   399         return welcome(10);
   400     }
   401 
   402     @GET
   403     @Path("elo")
   404     @Produces(MediaType.TEXT_HTML)
   405     public Response getEloList(
   406             @QueryParam("historyId") @DefaultValue("0") Integer historyId){
   407         Viewable v = checkLogin();
   408         if (v != null) {
   409             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   410         }
   411         final Document got = stat.path("elo").path("list").path(historyId.toString()).accept(MediaType.TEXT_XML).get(Document.class);
   412         return Response.ok(viewable("elo.fmt", got, "historyId", historyId)).build();
   413     }
   414     
   415     @GET
   416     @Path("openings")
   417     @Produces(MediaType.TEXT_HTML)
   418     public Response getOpeningRoot(){
   419         return getOpeningNode("ROOT");
   420     }
   421 
   422     @GET
   423     @Path("openings/{code}")
   424     @Produces(MediaType.TEXT_HTML)
   425     public Response getOpeningNode(@PathParam("code") String code){
   426         Viewable v = checkLogin();
   427         if (v != null) {
   428             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   429         }
   430         final Document got = stat.path("openings").path(code).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
   431         Board b;
   432         try {
   433             b = Board.valueOf(got.getElementsByTagName("nodeCode").item(0).getTextContent());
   434         } catch (Exception ex) {
   435             Exceptions.printStackTrace(ex);
   436             b = Board.empty();
   437         }
   438         return Response.ok(viewable("openings.fmt", got, "whitefences",b.getPlayers().get(0).getFences(),"blackfences",b.getPlayers().get(1).getFences())).build();
   439     }
   440 
   441     @GET
   442     @Path("openings/{code}/{status}")
   443     @Produces(MediaType.TEXT_HTML)
   444     public Response getOpeningNodeGames(@PathParam("code") String code, @PathParam("status") String status){
   445         Viewable v = checkLogin();
   446         if (v != null) {
   447             return Response.status(Response.Status.FORBIDDEN).entity(v).build();
   448         }
   449         final Document got = stat.path("openings").path(code).path(status).queryParam("loginID", user.getId()).accept(MediaType.TEXT_XML).get(Document.class);
   450         return Response.ok(viewable("opening_games.fmt", got,"code",code,"color",status)).build();
   451     }
   452 
   453     @GET
   454     @Path("openings/{code}.png")
   455     @Produces("image/png")
   456     public Response getOpeningBoardImage(
   457         @PathParam("code") String code,
   458         @QueryParam("fieldSize") @DefaultValue("40") int fieldSize
   459     ) throws IllegalPositionException {
   460         Board b = Board.valueOf(code);
   461         ResponseBuilder resp = Response.ok();
   462         CacheControl cc = new CacheControl();
   463         cc.setNoCache(true);
   464         resp.cacheControl(cc);
   465         return resp.entity(BoardImage.draw(b, fieldSize)).build();
   466     }
   467 
   468     //
   469     // start the server
   470     //
   471 
   472     public static void main(String[] params) throws Exception {
   473         List<String> args = new ArrayList<String>(Arrays.asList(params));
   474 
   475         String publicURL = null;
   476         if (args.size() >= 2 && args.get(0).equals("--url")) {
   477             publicURL = args.get(1);
   478             args.remove(0);
   479             args.remove(0);
   480         }
   481 
   482         int port = 9333;
   483         if (args.size() > 1) {
   484             port = Integer.parseInt(args.get(0));
   485         }
   486         String remoteAPI = args.size() >= 2 ? args.get(1) : null;
   487         String remoteStatistics = args.size() >= 3 ? args.get(2) : null;
   488 
   489         Locale.setDefault(Locale.ROOT);
   490 
   491         Callable<Void> r = startServers(port, remoteAPI, remoteStatistics, publicURL);
   492 
   493         if (args.size() < 3 || !args.get(args.size() - 1).equals("--kill")) {
   494             System.out.println("Hit enter to stop it...");
   495             System.in.read();
   496         } else {
   497             synchronized (UI.class) {
   498                 UI.class.wait();
   499             }
   500         }
   501         r.call();
   502         System.exit(0);
   503     }
   504 
   505     static Callable<Void> startServers(int port, String remoteAPI, String remoteStatistics, String publicURL) throws Exception {
   506         Client client = new Client();
   507         Client client1 = new Client();
   508 
   509         final HttpServer apiServer;
   510         if (remoteAPI == null) {
   511             throw new IllegalArgumentException("Provide URL to API server"); // NOI18N
   512         } else {
   513             base = client.resource(new URI(remoteAPI));
   514             apiServer = null;
   515         }
   516 
   517         if (remoteStatistics != null) {
   518             stat = client1.resource(new URI(remoteStatistics));
   519         } else {
   520             stat = client1.resource(new URI("http://localhost:9444"));
   521         }
   522 
   523         ResourceConfig rc = new PackagesResourceConfig(
   524             "cz.xelfi.quoridor.freemarkerdor"
   525         );
   526 
   527         final String baseUri = "http://localhost:" + port + "/";
   528         if (publicURL == null) {
   529             publicURL = baseUri;
   530         }
   531         final HttpServer server = HttpServerFactory.create(baseUri, rc);
   532         Client c3 = new Client();
   533         web = c3.resource(publicURL);
   534         server.start();
   535         System.out.println("Quoridor started at port " + port);
   536 
   537         return new Callable<Void>() {
   538             public Void call() throws Exception {
   539                 if (apiServer != null) {
   540                     apiServer.stop(0);
   541                 }
   542                 server.stop(0);
   543                 return null;
   544             }
   545         };
   546     }
   547 
   548     private ResourceBundle bundle(Locale[] locale) {
   549         ResourceBundle rb = null;
   550         String lng = user == null ? null : user.getProperty("language"); // NOI18N
   551         if (lng != null) {
   552             try {
   553                 Locale l = new Locale(lng);
   554                 rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   555                 if (locale != null) {
   556                     locale[0] = l;
   557                 }
   558             } catch (MissingResourceException e) {
   559                 // OK
   560             }
   561         }
   562         if (rb == null) {
   563             try {
   564                 for (Locale l : headers.getAcceptableLanguages()) {
   565                     try {
   566                         rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", l);
   567                         if (locale != null) {
   568                             locale[0] = l;
   569                         }
   570                         break;
   571                     } catch (MissingResourceException e) {
   572                         // OK
   573                     }
   574                 }
   575             } catch (WebApplicationException ex) {
   576                 // OK, can't parse header
   577             }
   578         }
   579         if (rb == null) {
   580             rb = ResourceBundle.getBundle("cz.xelfi.quoridor.freemarkerdor.UI.Bundle", Locale.ENGLISH);
   581             if (locale != null) {
   582                 locale[0] = Locale.ENGLISH;
   583             }
   584         }
   585         return rb;
   586     }
   587 
   588     private Viewable viewable(String page, Document doc, Object... more) {
   589         Locale[] locale = new Locale[1];
   590         ResourceBundle rb = bundle(locale);
   591 
   592         Map<String,Object> map = new HashMap<String,Object>();
   593         class ConvertToDate extends HashMap<Object,Object> {
   594             @Override
   595             public Object get(Object o) {
   596                 long time = Long.parseLong(o.toString());
   597                 return new Date(time);
   598             }
   599         }
   600 
   601         map.put("locale", locale[0].toString());
   602         map.put("doc", doc);
   603         if (user != null) {
   604             map.put("user", user.getId());
   605             map.put("email", user.getProperty("email"));
   606         }
   607         map.put("bundle", rb);
   608         map.put("toDate", new ConvertToDate());
   609         map.put("now", System.currentTimeMillis());
   610         map.put("version", version);
   611         for (int i = 0; i < more.length; i += 2) {
   612             map.put((String)more[i],more[i + 1]);
   613         }
   614         return new Viewable(page, map);
   615     }
   616 
   617 
   618     private static boolean isMobile(HttpHeaders headers) {
   619         final String[] keywords = {
   620             "Profile/MIDP",
   621         };
   622         List<String> agent = headers.getRequestHeader(HttpHeaders.USER_AGENT);
   623         if (agent != null) {
   624             for (String a : agent) {
   625                 for (String k : keywords) {
   626                     if (a.contains(k)) {
   627                         return true;
   628                     }
   629                 }
   630             }
   631         }
   632         return false;
   633     }
   634 
   635 }