/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: WSCTextStreamEncoderServer.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.util.concurrent.ExecutionException;

import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.SendResult;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.sun.ts.tests.websocket.common.impl.WaitingSendHandler;
import com.sun.ts.tests.websocket.common.stringbean.StringBean;
import com.sun.ts.tests.websocket.ee.javax.websocket.throwingcoder.ThrowingTextDecoder;
import com.sun.ts.tests.websocket.ee.javax.websocket.throwingcoder.ThrowingTextStreamEncoder;

@ServerEndpoint(value = "/textstreamencoder", encoders = { ThrowingTextStreamEncoder.class })
public class WSCTextStreamEncoderServer {

	@OnMessage
	public void echo(String data, Session session) throws InterruptedException,
			ExecutionException {
		WaitingSendHandler handler = new WaitingSendHandler();
		session.getAsyncRemote().sendObject(new StringBean(data), handler);
		SendResult result = handler.waitForResult(4);
		if (result.getException() != null)
			throw new RuntimeException(result.getException());
	}

	@OnError
	public void onError(Session session, Throwable t) throws IOException {
		String message = ThrowingTextDecoder.getCauseMessage(t);
		session.getBasicRemote().sendText(message);
	}

}
