1 package dolda.jsvc.scgi;
6 import java.util.logging.*;
8 import dolda.jsvc.util.*;
9 import dolda.jsvc.j2ee.PosixArgs;
11 public class DirServer extends Server {
12 private final Map<File, DSContext> contexts = new HashMap<File, DSContext>();
13 private final Environment env;
14 private final Logger logger = Logger.getLogger("dolda.jsvc.scgi.dirserver");
15 private Thread sdhook = null, main = null;
17 public DirServer(ServerSocket sk, Environment env) {
22 private DSContext context(File file) throws ThreadContext.CreateException {
23 synchronized(contexts) {
24 DSContext ctx = contexts.get(file);
25 String act = "loaded %s as %s";
27 if(ctx.mtime < file.lastModified()) {
29 contexts.remove(file);
31 act = "reloaded %s as %s";
35 ctx = new DSContext(file, env);
36 contexts.put(file, ctx);
37 logger.config(String.format(act, file, ctx.name()));
43 public void handle(Map<String, String> head, Socket sk) throws Exception {
44 String filename = head.get("SCRIPT_FILENAME");
46 throw(new Exception("Request for DirServer must contain SCRIPT_FILENAME"));
47 File file = new File(filename);
48 if(!file.exists() || !file.canRead())
49 throw(new Exception("Cannot access the requested JSvc file " + file.toString()));
50 DSContext ctx = context(file);
51 Request req = new ScgiRequest(sk, head);
52 RequestThread w = ctx.tg.respond(req);
56 private class ShutdownHandler extends Thread {
59 DirServer.this.stop();
62 } catch(InterruptedException e) {}
66 protected void shutdown() {
69 Runtime.getRuntime().removeShutdownHook(sdhook);
70 } catch(Exception e) {}
71 synchronized(contexts) {
72 for(Iterator<Map.Entry<File, DSContext>> i = contexts.entrySet().iterator(); i.hasNext();) {
73 Map.Entry<File, DSContext> e = i.next();
74 DSContext ctx = e.getValue();
82 private static void usage(PrintStream out) {
83 out.println("usage: dolda.jsvc.scgi.DirServer [-h] [-e CHARSET] [-d DATADIR] PORT");
86 public static void main(String[] args) {
87 PosixArgs opt = PosixArgs.getopt(args, "h");
92 String charset = null;
94 for(char c : opt.parsed()) {
100 datroot = new File(opt.arg);
101 if(!datroot.exists() || !datroot.isDirectory()) {
102 System.err.println(opt.arg + ": no such directory");
111 if(opt.rest.length < 1) {
115 Environment env = (datroot == null)?new Environment():new Environment(datroot);
117 int port = Integer.parseInt(opt.rest[0]);
120 sk = new ServerSocket(port);
121 } catch(IOException e) {
122 System.err.println("could not bind to port " + port + ": " + e.getMessage());
124 return; /* Because javac is stupid. :-/ */
126 DirServer s = new DirServer(sk, env);
130 Runtime.getRuntime().addShutdownHook(s.sdhook = s.new ShutdownHandler());
131 s.main = new Thread(s, "SCGI server thread");