serverside/src/main/java/org/apidesign/bck2brwsr/demo/serverside/ChatServerResource.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sun, 05 May 2013 18:04:13 +0200
changeset 11 40fce839ac01
parent 10 80715a1dd72e
permissions -rw-r--r--
Chat is functional (based on GET)
     1 /**
     2  * The MIT License (MIT)
     3  *
     4  * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     5  *
     6  * Permission is hereby granted, free of charge, to any person obtaining a copy
     7  * of this software and associated documentation files (the "Software"), to deal
     8  * in the Software without restriction, including without limitation the rights
     9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    10  * copies of the Software, and to permit persons to whom the Software is
    11  * furnished to do so, subject to the following conditions:
    12  *
    13  * The above copyright notice and this permission notice shall be included in
    14  * all copies or substantial portions of the Software.
    15  *
    16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    22  * THE SOFTWARE.
    23  */
    24 package org.apidesign.bck2brwsr.demo.serverside;
    25 
    26 import java.io.Closeable;
    27 import java.lang.reflect.Field;
    28 import java.util.ArrayList;
    29 import java.util.IdentityHashMap;
    30 import java.util.List;
    31 import java.util.Map;
    32 import java.util.concurrent.Callable;
    33 import java.util.logging.Level;
    34 import java.util.logging.Logger;
    35 import javax.inject.Singleton;
    36 import javax.ws.rs.Consumes;
    37 import javax.ws.rs.DefaultValue;
    38 import javax.ws.rs.GET;
    39 import javax.ws.rs.PUT;
    40 import javax.ws.rs.Path;
    41 import javax.ws.rs.Produces;
    42 import javax.ws.rs.QueryParam;
    43 import javax.ws.rs.container.AsyncResponse;
    44 import javax.ws.rs.container.Suspended;
    45 import javax.ws.rs.core.MediaType;
    46 import net.java.html.json.Context;
    47 import org.apidesign.bck2brwsr.launcher.Launcher;
    48 import org.glassfish.grizzly.http.server.HttpServer;
    49 import org.glassfish.grizzly.http.server.ServerConfiguration;
    50 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer;
    51 import org.glassfish.jersey.server.ContainerFactory;
    52 import org.glassfish.jersey.server.ResourceConfig;
    53 
    54 /** Server side of the chat application.*/
    55 @Path("/") @Singleton
    56 public final class ChatServerResource {
    57     private static final Logger LOG = Logger.getLogger(ChatServerResource.class.getName());
    58  
    59     public static void main(String... args) throws Exception {
    60         ResourceConfig rc = new ResourceConfig(ChatServerResource.class);
    61         GrizzlyHttpContainer c = ContainerFactory.createContainer(GrizzlyHttpContainer.class, rc);
    62         Closeable s = Launcher.showURL(
    63             "bck2brwsr", ChatClient.class.getClassLoader(),
    64             "/org/apidesign/bck2brwsr/demo/serverside/chat.html"
    65         );
    66         Launcher l = (Launcher) s;
    67         Callable<?> f = (Callable<?>) l;
    68         HttpServer server = (HttpServer) f.call();
    69         ServerConfiguration conf = server.getServerConfiguration();
    70         conf.addHttpHandler(c, "/chat");
    71         System.in.read();
    72         s.close();
    73     }
    74     
    75     private List<Message> msgs = new ArrayList<>();
    76     {
    77         Message welcome = new Message(Context.findDefault(Message.class));
    78         welcome.setUser("system");
    79         welcome.setComment("Welcome and enjoy!");
    80         welcome.setWhen(System.currentTimeMillis());
    81         msgs.add(welcome);
    82     }
    83     
    84     private final Map<AsyncResponse, Long> awaiting = new IdentityHashMap<>();
    85     
    86     @Produces(MediaType.APPLICATION_JSON)
    87     @GET public synchronized void getResources(
    88         @QueryParam("since") @DefaultValue("0") long since,
    89         @Suspended AsyncResponse ar
    90     ) {
    91         Query q = new Query(Context.findDefault(ChatServerResource.class));
    92         for (Message m : msgs) {
    93             if (m.getWhen() >= since) {
    94                 q.getMessages().add(m);
    95             }
    96         }
    97         if (!q.getMessages().isEmpty()) {
    98             ar.resume(q);
    99         } else {
   100             awaiting.put(ar, since);
   101         }
   102     }
   103     
   104     private void handleAwaiting(long newest) {
   105         assert Thread.holdsLock(this);
   106         AGAIN: for (;;) {
   107             for (Map.Entry<AsyncResponse, Long> entry : awaiting.entrySet()) {
   108                 AsyncResponse ar = entry.getKey();
   109                 Long since = entry.getValue();
   110                 if (since <= newest) {
   111                     awaiting.remove(ar);
   112                     getResources(since, ar);
   113                     continue AGAIN;
   114                 }
   115             }
   116             return;
   117         }
   118     }
   119     
   120     @Path("addComment") @GET 
   121     public synchronized Message publish(
   122         @QueryParam("user") String user,
   123         @QueryParam("comment") String comment
   124     ) {
   125         Message msg = new Message(Context.findDefault(ChatServerResource.class));
   126         msg.setUser(user);
   127         msg.setComment(comment);
   128         msg.setWhen(System.currentTimeMillis());
   129         msgs.add(msg);
   130         handleAwaiting(msg.getWhen());
   131         return msg;
   132     }
   133 }