webidor/src/main/java/cz/xelfi/quoridor/webidor/resources/Quoridor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 11 Jan 2010 10:16:57 +0100
changeset 189 6245e1b634aa
parent 145 ac9bd9be5263
child 239 a47345ebbdd7
permissions -rw-r--r--
Jiri Tulach requested support for JSONP. Changing all the @GET methods to also support application/x-javascript
     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     ) {
    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         if (name != null && password.equals(p.getProperty(name))) {
   102             UUID uuid = UUID.randomUUID();
   103             loggedIn.put(uuid, name);
   104             return uuid.toString();
   105         } else {
   106             return null;
   107         }
   108         
   109     }
   110 
   111     @Path("login")
   112     @GET
   113     @Produces({ MediaType.TEXT_PLAIN })
   114     public String isLoggedIn(
   115         @QueryParam("id") String id
   116     ) {
   117         String ret = null;
   118         try {
   119             if (id != null) {
   120                 ret = loggedIn.get(UUID.fromString(id));
   121             }
   122         } catch (IllegalArgumentException ex) {
   123             // OK, happens for invalid ids
   124         }
   125         return ret == null ? "" : ret;
   126     }
   127 
   128     @Path("login")
   129     @GET
   130     @Produces({ "application/x-javascript", MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
   131     public JSONWithPadding loggedInInfo(
   132         @QueryParam("callback") String callback,
   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         if (ret == null) {
   144             throw new WebApplicationException(Status.UNAUTHORIZED);
   145         } else {
   146             return getUsers().getUserInfo(callback, id, ret);
   147         }
   148     }
   149 
   150     //
   151     // start the server
   152     //
   153 
   154     public static void main(String[] args) throws IOException, InterruptedException {
   155         int port = 9222;
   156         try {
   157             port = Integer.parseInt(args[0]);
   158         } catch (Exception ex) {
   159             // OK
   160         }
   161         HttpServer s = start(port);
   162         System.out.println(
   163             "Quoridor started at port " + port + "\n" + "Hit enter to stop it..."
   164         );
   165         if (args.length < 2 || !args[args.length - 1].equals("--kill")) {
   166             System.out.println("Hit enter to stop it...");
   167             System.in.read();
   168         } else {
   169             synchronized (Quoridor.class) {
   170                 Quoridor.class.wait();
   171             }
   172         }
   173         System.in.read();
   174         s.stop(0);
   175         System.exit(0);
   176     }
   177 
   178     public static HttpServer start(int port) throws IOException {
   179         if (port == -1) {
   180             ServerSocket ss = new ServerSocket(0);
   181             port =ss.getLocalPort();
   182             ss.close();
   183         }
   184         final String baseUri = "http://localhost:" + port + "/";
   185 
   186         if (System.getProperty("quoridor.dir") == null) {
   187             File home = new File(System.getProperty("user.home"));
   188             File quoridor = new File(home, ".quoridor");
   189             System.setProperty("quoridor.dir", quoridor.getPath());
   190         }
   191 
   192         ResourceConfig rc = new PackagesResourceConfig("cz.xelfi.quoridor.webidor");
   193         HttpServer server = HttpServerFactory.create(baseUri, rc);
   194         server.start();
   195         return server;
   196     }
   197 
   198 }