/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id$
 */

package com.sun.ts.tests.websocket.ee.javax.websocket.remoteendpoint.usercoder;

import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.MessageHandler;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.sun.ts.tests.websocket.common.util.IOUtil;

@ServerEndpoint("/echo")
public class WSCEchoServer implements MessageHandler.Whole<ByteBuffer> {

	Session session;

	@OnOpen
	public void onOpen(Session session) {
		session.addMessageHandler(this);
		this.session = session;
	}

	@OnMessage
	public String onMessage(String msg) {
		return msg;
	}

	@OnError
	public void onError(Session session, Throwable t) throws IOException {
		System.out.println("@OnError in " + getClass().getName());
		t.printStackTrace(); // Write to error log, too
		String message = "Exception: " + IOUtil.printStackTrace(t);
		session.getBasicRemote().sendText(message);
	}

	@Override
	public void onMessage(ByteBuffer message) {
		try {
			session.getBasicRemote().sendText(
					IOUtil.byteBufferToString(message));
		} catch (IOException e) {
			throw new RuntimeException(e); // call @OnError
		}
	}
}
