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
019
020import java.io.IOException;
021
022import javax.websocket.Endpoint;
023import javax.websocket.EndpointConfig;
024import javax.websocket.MessageHandler;
025import javax.websocket.Session;
026
027public class JsonMessagesEndpoint extends Endpoint {
028    private final HandlerDispatcher dispatcher;
029
030    public JsonMessagesEndpoint(HandlerDispatcher handlers) {
031        this.dispatcher = handlers;
032    }
033
034    @Override
035    public void onOpen(final Session session, EndpointConfig config) {
036        session.addMessageHandler(new MessageHandler.Whole<String>() {
037            @Override
038            public void onMessage(String message) {
039                try {
040                    String result = dispatcher.callOnMessage(message);
041                    session.getBasicRemote().sendText(result);
042                } catch (IOException ex) {
043                    throw new RuntimeException(ex);
044                }
045            }
046        });
047    }
048}