Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.cooksys.httpserver; import com.cooksys.postmaster.PostmasterModelSingleton; import java.io.IOException; import javafx.concurrent.Service; import javafx.concurrent.Task; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.UriHttpRequestHandlerMapper; /** * * @author Tim Davidson * Wrapper for simple http server for javafx concurrency compatibility. * Extends javafx.concurrent.Service - allows javafx to manage background task * of accepting and handling incoming connections. */ public class HttpServerStarter extends Service { PostmasterModelSingleton postmasterModel = PostmasterModelSingleton.getInstance(); private RequestListenerThread serverThread; public void stop() { //cleanly stop the server thread serverThread.stopServer(); this.cancel(); } @Override protected Task createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("PostMaster/1.1")).add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handlers UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(); registry.register("*", new IncomingHttpHandler()); // Set up the HTTP service that listens for incoming requests HttpService httpService = new HttpService(httpproc, registry); //RequestListenerThread extends the Thread class, but since we are //letting the concurrency handle background tasks, it would not //make sense to spawn another thread inside this task, so we //will just call run() method instead of start() System.out.println("creating serverThread..."); try { serverThread = new RequestListenerThread(postmasterModel.getPort(), httpService); } catch (IOException e) { System.out.println("Caught IOException:" + e.getMessage()); //end the server task this.updateMessage(e.getMessage()); throw e; } System.out.println("serverThread created: " + serverThread); serverThread.run(); //the compiler will warn here, but we did this on purpose return null; } @Override protected void failed() { } }; } }