package geniusweb.runserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import javax.websocket.ClientEndpoint; import javax.websocket.CloseReason; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import com.fasterxml.jackson.databind.ObjectMapper; import geniusweb.actions.Action; import geniusweb.actions.PartyId; import geniusweb.party.inform.Inform; import geniusweb.protocol.partyconnection.ConnectionWithParty; import geniusweb.references.Reference; import tudelft.utilities.listener.DefaultListenable; import tudelft.utilities.logging.ReportToLogger; import tudelft.utilities.logging.Reporter; /** * A websocket based {@link ConnectionWithParty}. Must be public so that it can * be accessed as ClientEndpoint by apache tomcat */ @ClientEndpoint public class PartyConnection extends DefaultListenable implements ConnectionWithParty { private final static ObjectMapper jackson = new ObjectMapper(); private final Reporter log; private final Reference reference; private WebSocketContainer container; private Session session = null; private URI partyuri; private Throwable error = null; /** * Constructor that uses default {@link Reporter} * * @param reference the address to to a http GET to get a websocket to a new * running party. */ public PartyConnection(Reference reference) { this(reference, new ReportToLogger("runserver")); } /** * * @param reference the address to to a http GET to get a websocket to a new * running party. * @param reporter the {@link Reporter} used for logging important * events/issues * @throws IOException if the party does not start properly. */ public PartyConnection(Reference reference, Reporter reporter) { this.reference = reference; this.log = reporter; } public PartyConnection init() throws IOException { log.log(Level.INFO, "Trying to start up party " + reference); URI partyuri = startParty(reference); container = ContainerProvider.getWebSocketContainer(); log.log(Level.INFO, "Trying to make websocket connection to running party " + partyuri); try { container.connectToServer(this, partyuri); } catch (DeploymentException e) { throw new IOException( "Failed to connect with running party at " + partyuri, e); } log.log(Level.INFO, "Created websocket connection at " + partyuri); return this; } /** * * @param reference the address to to a http GET to get a websocket to a new * running party. * @return URI of websocket behind which is a running party * @throws IOException if party did not start correctly */ private URI startParty(Reference reference) throws IOException { HttpURLConnection conn = (HttpURLConnection) reference.getURI().toURL() .openConnection(); // if this throws, the IOException seems to contain the "retry later" // message // already conn.setRequestMethod("GET"); // TODO timeout BufferedReader rd; try { rd = new BufferedReader( new InputStreamReader(conn.getInputStream())); } catch (IOException e) { // read the detail message from the error stream rd = new BufferedReader( new InputStreamReader(conn.getErrorStream())); throw new IOException(rd.readLine(), e); } String partysocketaddress = rd.readLine(); log.log(Level.INFO, "startparty returned " + partysocketaddress); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException( "Something went wrong connecting to the party:" + conn.getResponseCode()); } try { this.partyuri = new URI(partysocketaddress); } catch (URISyntaxException e1) { throw new IOException("Failed to start party at " + reference, e1); } return partyuri; } /************* implements {@link ConnectionWithParty} ***************/ @Override public void send(Inform info) throws IOException { if (session == null) return; session.getBasicRemote().sendText(jackson.writeValueAsString(info)); } @Override public Reference getReference() { return this.reference; } @Override public PartyId getParty() { String name = partyuri.getPath(); return new PartyId(name.substring(name.lastIndexOf('/') + 1)); } @Override public void close() { log.log(Level.INFO, "Party close called"); setError(new SocketException("socket is closed")); try { session.close(); this.session = null; } catch (IOException e) { log.log(Level.SEVERE, "failed to close websocket", e); } } /************* implements ClientEndpoint ***************/ @OnOpen public void onOpen(Session session) { log.log(Level.INFO, "Party is being connected: " + session); this.session = session; } @OnClose public void onClose(Session userSession, CloseReason reason) { log.log(Level.INFO, "closing websocket " + reference + ":" + reason); setError(new SocketException("socket has been closed")); } @OnMessage public void processMessage(String message) { try { Action act = jackson.readValue(message, Action.class); notifyChange(act); } catch (IOException e) { log.log(Level.WARNING, "received bad message from client " + reference, e); setError(e); close(); } } @OnError public void processError(Throwable t) { log.log(Level.SEVERE, "Something went wrong internally!", t); setError(t); } @Override public URI getRemoteURI() { return partyuri; } @Override public Throwable getError() { return error; } /** * Sets the connection to final error state and report null to listeners. * Only the first error is reported, the rest is ignored. * * @param err the error that occurred. */ private void setError(Throwable err) { boolean isSet = false; synchronized (this) { if (this.error == null) { this.error = err; isSet = true; } } if (isSet) { notifyChange(null); } } }