I want to use Restlet to create a local server. This server should receive exaclty one request (besides favicon), and after that request is handled it should shut down. I don't want to use System.exit
, I want it to shut down properly.
As you can see in my code I commented the line when I assume the request is handled properly. But I can't tell the server to stop there.
How can I tell the server to stop waiting for requests at this point? I got it working but with 2 issues I'd like to solve.
The response
sent to the client will not be shown if I stop the server within the request
public class Main {
public static void main(String[] args){
Server serv = null;
Restlet restlet = new Restlet() {
@Override
public void handle(Request request, Response response) {
if(!request.toString().contains("favicon")){
System.out.println("do stuff");
response.setEntity("Request will be handled", MediaType.TEXT_PLAIN);
//stop server after the first request is handled.
//so the program should shut down here
//if I use serv.stop() here (besides it's currently not final)
//I'd get exceptions and the user wouldn't see the response
}
}
};
// Avoid conflicts with other Java containers listening on 8080!
try {
serv = new Server(Protocol.HTTP, 8182, restlet);
serv.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I figured out a way to do it. Add a OnSent
event to the response, and shut down the server here.
public class Main {
private Server serv;
public Main(){
run();
}
public void run(){
Restlet restlet = new Restlet() {
@Override
public void handle(Request request, Response response) {
response.setEntity("Request will be handled", MediaType.TEXT_PLAIN);
if(!request.toString().contains("favicon")){
System.out.println("do stuff");
response.setOnSent(new Uniform() {
@Override
public void handle(Request req, Response res) {
try {
serv.stop();//stop the server
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
};
// Avoid conflicts with other Java containers listening on 8080!
try {
serv = new Server(Protocol.HTTP, 8182, restlet);
serv.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
new Main();
}
}