webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Quoridor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 15 Apr 2011 21:18:29 +0200
changeset 282 40fc213a7f43
parent 264 d60370059c3c
child 284 90be53f96e0c
permissions -rw-r--r--
Using Grizzly
     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 
    19 package cz.xelfi.quoridor.webidor.resources;
    20 
    21 import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
    22 import com.sun.jersey.api.core.PackagesResourceConfig;
    23 import com.sun.jersey.api.core.ResourceConfig;
    24 import com.sun.jersey.api.json.JSONWithPadding;
    25 import com.sun.jersey.spi.resource.Singleton;
    26 import java.io.File;
    27 import java.io.FileInputStream;
    28 import java.io.IOException;
    29 import java.net.ServerSocket;
    30 import java.util.HashMap;
    31 import java.util.Map;
    32 import java.util.Properties;
    33 import java.util.UUID;
    34 import javax.ws.rs.GET;
    35 import javax.ws.rs.PUT;
    36 import javax.ws.rs.Path;
    37 import javax.ws.rs.Produces;
    38 import javax.ws.rs.QueryParam;
    39 import javax.ws.rs.WebApplicationException;
    40 import javax.ws.rs.core.MediaType;
    41 import javax.ws.rs.core.Response.Status;
    42 import org.glassfish.grizzly.http.server.HttpServer;
    43 
    44 /**
    45  *
    46  * @author Jaroslav Tulach <jtulach@netbeans.org>
    47  */
    48 @Path("/")
    49 @Singleton
    50 public final class Quoridor {
    51     private final File path;
    52     private Games games;
    53     private Users users;
    54     private final Map<UUID,String> loggedIn;
    55 
    56     public Quoridor() {
    57         final String prop = System.getProperty("quoridor.dir"); // NOI18N
    58         if (prop == null) {
    59             throw new IllegalStateException("quoridor.dir property must be specified"); // NOI18N
    60         }
    61         path = new File(prop);
    62         path.mkdirs();
    63         loggedIn = new HashMap<UUID, String>();
    64         games = new Games(new File(path, "games"), this); // NOI18N
    65         users = new Users(new File(path, "users"), this); // NOI18N
    66     }
    67 
    68     @Path("games")
    69     public Games getGames() {
    70         return games;
    71     }
    72 
    73     @Path("users")
    74     public Users getUsers() {
    75         return users;
    76     }
    77 
    78     @Path("login")
    79     @PUT
    80     @Produces({ MediaType.TEXT_PLAIN })
    81     public String login(
    82         @QueryParam("name") String name,
    83         @QueryParam("password") String password
    84     ) throws IOException {
    85         File f = new File(path, "passwd"); // NOI18Nt
    86         Properties p = new Properties();
    87         try {
    88             p.load(new FileInputStream(f));
    89         } catch (IOException ex) {
    90             ex.printStackTrace();
    91         }
    92         boolean loggedInOK = false;
    93         if (name != null && password.equals(p.getProperty(name))) {
    94             loggedInOK = true;
    95         } else {
    96             loggedInOK = getUsers().verifyPassword(name, password);
    97         }
    98 
    99         if (loggedInOK) {
   100             UUID uuid = UUID.randomUUID();
   101             loggedIn.put(uuid, name);
   102             return uuid.toString();
   103         } else {
   104             return null;
   105         }
   106         
   107     }
   108 
   109     @Path("login")
   110     @GET
   111     @Produces({ MediaType.TEXT_PLAIN })
   112     public String isLoggedIn(
   113         @QueryParam("id") String id
   114     ) {
   115         String ret = null;
   116         try {
   117             if (id != null) {
   118                 ret = loggedIn.get(UUID.fromString(id));
   119             }
   120         } catch (IllegalArgumentException ex) {
   121             // OK, happens for invalid ids
   122         }
   123         return ret == null ? "" : ret;
   124     }
   125 
   126     @Path("login")
   127     @GET
   128     @Produces({ "application/x-javascript", MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
   129     public JSONWithPadding loggedInInfo(
   130         @QueryParam("callback") String callback,
   131         @QueryParam("id") String id
   132     ) throws IOException {
   133         String ret = null;
   134         try {
   135             if (id != null) {
   136                 ret = loggedIn.get(UUID.fromString(id));
   137             }
   138         } catch (IllegalArgumentException ex) {
   139             // OK, happens for invalid ids
   140         }
   141         if (ret == null) {
   142             throw new WebApplicationException(Status.UNAUTHORIZED);
   143         } else {
   144             return getUsers().getUserInfo(callback, id, ret);
   145         }
   146     }
   147 
   148     //
   149     // start the server
   150     //
   151 
   152     public static void main(String[] args) throws IOException, InterruptedException {
   153         int port = 9222;
   154         try {
   155             port = Integer.parseInt(args[0]);
   156         } catch (Exception ex) {
   157             // OK
   158         }
   159         HttpServer s = start(port);
   160         System.out.println(
   161             "Quoridor started at port " + port + "\n" + "Hit enter to stop it..."
   162         );
   163         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   164             System.out.println("Hit enter to stop it...");
   165             System.in.read();
   166         } else {
   167             synchronized (Quoridor.class) {
   168                 Quoridor.class.wait();
   169             }
   170         }
   171         System.in.read();
   172         s.stop();
   173         System.exit(0);
   174     }
   175 
   176     public static HttpServer start(int port) throws IOException {
   177         if (port == -1) {
   178             ServerSocket ss = new ServerSocket(0);
   179             port =ss.getLocalPort();
   180             ss.close();
   181         }
   182         final String baseUri = "http://localhost:" + port + "/";
   183 
   184         if (System.getProperty("quoridor.dir") == null) {
   185             File home = new File(System.getProperty("user.home"));
   186             File quoridor = new File(home, ".quoridor");
   187             System.setProperty("quoridor.dir", quoridor.getPath());
   188         }
   189 
   190         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.webidor");
   191         HttpServer server = GrizzlyServerFactory.createHttpServer(baseUri, rc);
   192         server.start();
   193         return server;
   194     }
   195 
   196 }