package de.meijr.minecraftservletwrapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class MinecraftWrapper implements HttpHandler {
private final String sep = File.separator;
private final String cmd = "java -jar %s nogui -Xms256M -Xmx512M";
private final String serverDir = "e:" + sep + "minecraft" + sep;
private final String serverJar = "minecraft_server.jar";
private Process process = null;
private volatile boolean receivePlayerList = false;
private final List<String> dataList = new ArrayList<String>();
public MinecraftWrapper() throws IOException {
startServer();
}
public void startServer() throws IOException {
process = Runtime.getRuntime().exec(
String.format(cmd, serverJar));
new StreamReaderThread(process.getErrorStream(),
new ReaderListener() {
@Override
public void dataAvailable(final String data) {
System.out.println("ERR: " + data);
if (receivePlayerList) {
dataList.add(data);
}
}
}).start();
new StreamReaderThread(process.getInputStream(),
new ReaderListener() {
@Override
public void dataAvailable(final String data) {
System.out.println("INP: " + data);
if (receivePlayerList) {
dataList.add(data);
}
}
}).start();
}
public List<String> getPlayerList() {
final List<String> playerList = new ArrayList<String>();
if (process != null) {
receivePlayerList = true;
final BufferedOutputStream out =
(BufferedOutputStream) process.getOutputStream();
try {
final String command = "list\n";
out.write(command.getBytes());
out.flush();
} catch (final IOException ex) {
ex.printStackTrace();
}
// wait some time
try {
Thread.sleep(250);
} catch (final InterruptedException ex) {
}
receivePlayerList = false;
playerList.addAll(dataList);
dataList.clear();
}
return playerList;
}
@Override
public void handle(final HttpExchange t) throws IOException {
final List<String> playerList = getPlayerList();
final StringBuilder sb = new StringBuilder();
sb.append("<html><title>Spielerliste</title>");
if (playerList.isEmpty()) {
sb.append("<body><center>Keine Spieler verbunden</center></body>");
} else {
sb.append("<body><lu>");
for (final String player : playerList) {
sb.append("<li>");
sb.append(player);
}
sb.append("</lu></body>");
}
sb.append("</html>");
t.sendResponseHeaders(200, sb.toString().length());
OutputStream os = t.getResponseBody();
os.write(sb.toString().getBytes());
os.close();
}
public void shutdown() {
process.destroy();
}
}