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