Ein minimalistischer HTTP-Server
ulrich
2021-03-27 6d3836e41493f89c5b8700cca34111319e9fa41a
commit | author | age
9c7249 1 /*
678b07 2   mini-server - Ein minimalistischer HTTP-Server
U 3   Copyright (C) 2021  Ulrich Hilger
9c7249 4
678b07 5   This program is free software: you can redistribute it and/or modify
U 6   it under the terms of the GNU Affero General Public License as
7   published by the Free Software Foundation, either version 3 of the
8   License, or (at your option) any later version.
9c7249 9
678b07 10   This program is distributed in the hope that it will be useful,
U 11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU Affero General Public License for more details.
9c7249 14
678b07 15   You should have received a copy of the GNU Affero General Public License
U 16   along with this program.  If not, see <https://www.gnu.org/licenses/>.
ee6a3e 17  */
9c7249 18 package de.uhilger.minsrv.handler;
U 19
20 import com.sun.net.httpserver.HttpExchange;
21 import com.sun.net.httpserver.HttpHandler;
22 import de.uhilger.minsrv.App;
23 import java.io.IOException;
24 import java.io.OutputStream;
ee6a3e 25 import java.util.Timer;
U 26 import java.util.TimerTask;
9c7249 27 import java.util.logging.Logger;
U 28
29 /**
d0bb21 30  * Ein HTTP-Handler zum Stoppen der Anwendung
ee6a3e 31  *
8abbcf 32  * @author Ulrich Hilger
9c7249 33  */
U 34 public class StopServerHandler implements HttpHandler {
35
6d3836 36   /**
U 37    * Den Server geordnet herunterfahren und 
38    * dann die Anwendung beenden.
39    * 
40    * @param e das Objekt mit Methoden zur Untersuchung der Anfrage sowie zum
41    * Anfertigen und Senden der Antwort
42    * @throws IOException falls etwas schief geht entsteht dieser Fehler
43    */
9c7249 44   @Override
ee6a3e 45   public void handle(HttpExchange e) throws IOException {
U 46     Logger.getLogger(StopServerHandler.class.getName()).info(e.getRequestURI().toString());
9c7249 47     String response = "Server stopped";
ee6a3e 48     e.sendResponseHeaders(200, response.length());
U 49     OutputStream os = e.getResponseBody();
9c7249 50     os.write(response.getBytes());
U 51     os.flush();
52     os.close();
ee6a3e 53     Logger.getLogger(StopServerHandler.class.getName()).info("stopping server.");
U 54     e.getHttpContext().getServer().stop(1);
55     Timer timer = new Timer();
56     timer.schedule(new AppStopper(), 2000);
9c7249 57   }
ee6a3e 58
6d3836 59   /**
U 60    * Die Klasse AppStopper erm&ouml;glicht das asnychrone bzw. 
61    * zeitgesteuerte Stoppen der Anwendung.
62    */
ee6a3e 63   class AppStopper extends TimerTask {
U 64
65     @Override
66     public void run() {
67       Logger.getLogger(StopServerHandler.class.getName()).info("Mini-Server beendet.");
68       App.stop();
69     }
70   }
71
9c7249 72 }