001/*
002 * Copyright 2013 Atteo.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.atteo.moonshine.websocket.jsonmessages;
018
019import javax.inject.Provider;
020import javax.xml.bind.annotation.XmlElement;
021import javax.xml.bind.annotation.XmlIDREF;
022import javax.xml.bind.annotation.XmlRootElement;
023
024import org.atteo.moonshine.TopLevelService;
025import org.atteo.moonshine.services.ImportService;
026import org.atteo.moonshine.websocket.WebSocketContainerService;
027
028import com.google.inject.Module;
029import com.google.inject.PrivateModule;
030
031/**
032 * JSON WebSocket messages dispatcher.
033 */
034@XmlRootElement(name = "json-messages")
035public class JsonMessagesService extends TopLevelService {
036    @ImportService
037    @XmlIDREF
038    @XmlElement
039    private WebSocketContainerService webSocketContainer;
040
041    @XmlElement
042    private String pattern = "/json-messages";
043
044    private final HandlerDispatcher dispatcher = new HandlerDispatcher();
045
046    public <T> void addHandler(Class<T> klass, Provider<? extends T> handler) {
047        dispatcher.addHandler(klass, handler);
048    }
049
050    public <T> SenderProvider<T> addSender(Class<T> klass) {
051        return dispatcher.addSender(klass);
052    }
053
054    @Override
055    public Module configure() {
056        return new PrivateModule() {
057            @Override
058            protected void configure() {
059                bind(JsonMessagesEndpoint.class).toInstance(new JsonMessagesEndpoint(dispatcher));
060
061                webSocketContainer.addEndpoint(JsonMessagesEndpoint.class)
062                        .provider(getProvider(JsonMessagesEndpoint.class))
063                        .pattern(pattern);
064            }
065        };
066    }
067}