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