package org.openslx.dnbd3.status; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.openslx.dnbd3.status.poller.ServerPoller; import fi.iki.elonen.NanoHTTPD; public class WebServer extends NanoHTTPD { private final StatisticsGenerator imageGenerator; public WebServer( int port ) { super( port ); List pollers = new ArrayList<>(); pollers.add( new ServerPoller( "132.230.8.113", 5003 ) ); pollers.add( new ServerPoller( "132.230.4.60", 5003 ) ); pollers.add( new ServerPoller( "10.4.128.38", 5003 ) ); pollers.add( new ServerPoller( "132.230.4.2", 5003 ) ); imageGenerator = new StatisticsGenerator( pollers ); } @Override public Response serve( IHTTPSession session ) { String uri = session.getUri(); // Special/dynamic if ( uri.equals( "/image.png" ) ) return serveImage(); if ( uri.equals( "/data.json" ) ) return serveJson(); // Static files if ( uri.equals( "/" ) ) uri = "/index.html"; File f = new File( "./static/" + uri.replace( "/", "" ) ); if ( f.isFile() ) { InputStream is = null; try { is = new FileInputStream( f ); /* // TODO: Shit doesn't work return new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, URLConnection.guessContentTypeFromName( f.getName() ), is ); */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[ 10000 ]; for ( ;; ) { int ret = is.read( buffer ); if ( ret <= 0 ) break; baos.write( buffer, 0, ret ); } return new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, URLConnection.guessContentTypeFromName( f.getName() ), baos.toString( "UTF-8" ) ); } catch ( Exception e ) { return new NanoHTTPD.Response( NanoHTTPD.Response.Status.INTERNAL_ERROR, "text/plain", "Internal Server Error" ); } finally { safeClose( is ); } } return new NanoHTTPD.Response( NanoHTTPD.Response.Status.NOT_FOUND, "text/plain", "Nicht gefunden!" ); } private NanoHTTPD.Response serveImage() { InputStream is = null; byte[] imgData = imageGenerator.getImagePng(); if ( imgData != null ) is = new ByteArrayInputStream( imgData ); if ( is == null ) { return new NanoHTTPD.Response( NanoHTTPD.Response.Status.INTERNAL_ERROR, "text/plain", "Internal Server Error" ); } else { return new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, "image/png", is ); } } private NanoHTTPD.Response serveJson() { String data = imageGenerator.getJson(); if ( data == null ) { return new NanoHTTPD.Response( NanoHTTPD.Response.Status.INTERNAL_ERROR, "text/plain", "Internal Server Error" ); } else { return new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, "application/json", data ); } } }