/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: WSCSimpleEchoServer.java 72876 2013-09-17 12:05:52Z supol $
 */

package com.sun.ts.tests.websocket.ee.javax.websocket.throwingcoder.annotated;

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("/simpleecho")
public class WSCSimpleEchoServer {

	@OnOpen
	public void onOpen(final Session session) {
		session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {
			@Override
			public void onMessage(ByteBuffer message) {
				String ret = echo(IOUtil.byteBufferToString(message));
				try {
					session.getBasicRemote().sendText(ret);
				} catch (IOException e) {
					try {
						onError(session, e);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		});
	}

	@OnMessage
	public String echo(String echo) {
		return echo;
	}

	@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 = IOUtil.printStackTrace(t);
		session.getBasicRemote().sendText(message);
	}

}
