Skip to content

Commit

Permalink
Add experimental websocket mgmt
Browse files Browse the repository at this point in the history
  • Loading branch information
msteiger committed May 11, 2016
1 parent 8a5818f commit e5f00fa
Show file tree
Hide file tree
Showing 7 changed files with 230 additions and 5 deletions.
13 changes: 9 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,19 @@ task wrapper(type: Wrapper) {
gradleVersion = '2.13'
}

def jettyVersion = '9.3.8.v20160314'
def jerseyVersion = '2.22.2'

dependencies {
compile 'org.terasology.engine:engine:1.0.0'

compile 'org.eclipse.jetty:jetty-servlet:9.3.8.v20160314'
compile 'javax.servlet:javax.servlet-api:3.1.0'
compile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: jettyVersion
compile group: 'org.eclipse.jetty.websocket', name: 'websocket-server', version: jettyVersion

compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'

compile 'org.glassfish.jersey.containers:jersey-container-jetty-servlet:2.22.2'
compile 'org.glassfish.jersey.ext:jersey-mvc-freemarker:2.22.2'
compile group: 'org.glassfish.jersey.containers', name: 'jersey-container-jetty-servlet', version: jerseyVersion
compile group: 'org.glassfish.jersey.ext', name: 'jersey-mvc-freemarker', version: jerseyVersion

testCompile 'junit:junit:4.12'
}
Expand Down
8 changes: 7 additions & 1 deletion src/main/java/org/terasology/web/ServerMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,24 @@

import java.util.Locale;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.web.io.GsonMessageBodyHandler;
import org.terasology.web.servlet.AboutServlet;
import org.terasology.web.servlet.LogServlet;
import org.terasology.web.servlet.WsEventServlet;


/**
Expand Down Expand Up @@ -62,6 +67,7 @@ public static void main(String[] args) throws Exception {
Locale.setDefault(Locale.ENGLISH);

Server server = createServer(port.intValue(),
new LogServlet(),
new AboutServlet());

server.start();
Expand Down Expand Up @@ -96,9 +102,9 @@ public static Server createServer(int port, Object... annotatedObjects) throws E
}

ServletContextHandler jerseyContext = new ServletContextHandler(ServletContextHandler.GZIP);
jerseyContext.setContextPath("/");
jerseyContext.setResourceBase("templates");
jerseyContext.addServlet(new ServletHolder(new ServletContainer(rc)), "/*");
jerseyContext.addServlet(new ServletHolder(WsEventServlet.class), "/events/*");

HandlerList handlers = new HandlerList();
handlers.addHandler(logContext);
Expand Down
64 changes: 64 additions & 0 deletions src/main/java/org/terasology/web/servlet/EventSocket.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2016 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.terasology.web.servlet;

import java.io.IOException;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Manages one websocket session
*/
public class EventSocket extends WebSocketAdapter {

private static final Logger logger = LoggerFactory.getLogger(EventSocket.class);

@Override
public void onWebSocketConnect(Session session) {
super.onWebSocketConnect(session);
logger.info("Connected: " + session.getRemoteAddress());
trySend("Connected!");
}

@Override
public void onWebSocketText(String message) {
super.onWebSocketText(message);
}

@Override
public void onWebSocketClose(int statusCode, String reason) {
super.onWebSocketClose(statusCode, reason);
logger.info("Socket Closed: [" + statusCode + "] " + reason);
}

@Override
public void onWebSocketError(Throwable cause) {
super.onWebSocketError(cause);
logger.error("Error", cause);
}

private void trySend(String message) {
try {
getSession().getRemote().sendString(message);
} catch (IOException e) {
logger.warn("Unable to send message!", e);
}
}
}
49 changes: 49 additions & 0 deletions src/main/java/org/terasology/web/servlet/LogServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2015 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.terasology.web.servlet;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.server.mvc.Viewable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.web.version.VersionInfo;

import com.google.common.collect.ImmutableMap;

/**
* Show the log html page.
*/
@Path("/")
public class LogServlet {

private static final Logger logger = LoggerFactory.getLogger(LogServlet.class);

@GET
@Path("log")
@Produces(MediaType.TEXT_HTML)
public Viewable log() {
logger.info("Requested logs as HTML");
ImmutableMap<Object, Object> dataModel = ImmutableMap.builder()
.put("version", VersionInfo.getVersion())
.build();
return new Viewable("/log.ftl", dataModel);
}
}
34 changes: 34 additions & 0 deletions src/main/java/org/terasology/web/servlet/WsEventServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright 2016 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.terasology.web.servlet;

import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

/**
* Registers the {@link EventSocket} class for all incoming connections.
*/
public class WsEventServlet extends WebSocketServlet {

private static final long serialVersionUID = -981505298711059433L;

@Override
public void configure(WebSocketServletFactory factory) {
factory.getPolicy().setIdleTimeout(10000); // set a 10 second timeout
factory.register(EventSocket.class);
}
}
63 changes: 63 additions & 0 deletions templates/log.ftl
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="en">

<#include "metainfo.ftl">

<body>

<div class="container">

<#assign tab = "log">
<#include "navigation.ftl">

<h3>Log output</h3>





<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>


<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>


<#include "footer.ftl">

</div> <!-- /container -->

</body>

<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:8080/events");
var textArea = document.getElementById('comment');
ws.onopen = function() {
ws.send("HelloWorld");
textArea.value += 'Connected..\n';
};
ws.onmessage = function(evt) {
textArea.value += evt.data;
};
ws.onclose = function() {
textArea.value += 'Closed\n';
};
}
else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>

</html>
4 changes: 4 additions & 0 deletions templates/navigation.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
<div class="header clearfix">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation"
<#if tab == "log">class="active"</#if>
><a href="/log">Logs</a>
</li>
<li role="presentation"
<#if tab == "about">class="active"</#if>
><a href="/home"><span class="glyphicon glyphicon-home" aria-hidden="true" title="Home"></span></a>
Expand Down

0 comments on commit e5f00fa

Please sign in to comment.