moved to better jinetd setup
[org.ibex.jinetd.git] / src / org / ibex / jinetd / Main.java
1 package org.ibex.jinetd;
2 import org.ibex.util.*;
3 import java.io.*;
4 import java.net.*;
5 import java.util.*;
6 import java.util.zip.*;
7
8 public class Main {
9
10     public static String ROOT;
11     public static String LOGFILE;
12     public static PrintStream LOGSTREAM;
13
14     private static void configureRoot() throws Exception {
15         ROOT = System.getProperty("jinetd.root", null);
16         if (ROOT == null) {
17             ROOT = autoDetectRoot();
18             System.setProperty("jinetd.root", ROOT);
19         }
20     }
21
22     private static void configureLogging() throws Exception {
23         LOGFILE  = System.getProperty("jinetd.logfile", ROOT + File.separatorChar+"log.txt");
24         LOGSTREAM = new PrintStream(new FileOutputStream(LOGFILE, true));
25         System.setErr(LOGSTREAM);
26         System.setOut(LOGSTREAM);
27     }
28
29     private static String autoDetectRoot() throws Exception {
30         if (!(Main.class.getClassLoader() instanceof URLClassLoader))
31             throw new Error("unable to detect jinetd.root because my ClassLoader is not an instanceof URLClassLoader");
32         URL[] urls = ((URLClassLoader)Main.class.getClassLoader()).getURLs();
33         for(int i=0; i<urls.length; i++) {
34             if (!urls[i].getProtocol().equals("file")) continue;
35             File file = new File(urls[i].getPath());
36             if (file.isDirectory()) {
37                 if (new File(file.getAbsolutePath() +
38                              File.separatorChar + 
39                              Main.class.getName().replace('.', File.separatorChar)+".class").exists())
40                     return file.getAbsolutePath();
41             } else if (file.getAbsolutePath().endsWith(".jar")) {
42                 ZipFile zf = new ZipFile(file);
43                 if (zf.getEntry(Main.class.getName().replace('.', File.separatorChar)+".class") != null)
44                     return new File(file.getParent()).getAbsolutePath();
45             }
46         }
47         throw new Error("unable to detect jinetd.root because " +
48                         Main.class.getName() +
49                         " was not in any of the ClassLoader URLs");
50     }
51
52     static {
53         try {
54             configureRoot();
55             configureLogging();
56         } catch (Throwable e) {
57             throw new Error(e);
58         }
59     }
60
61     public static void main(String[] s) throws Exception {
62         Log.color = true;
63         Root root = new Root(Root.root);
64         while(true) try {
65             Thread.sleep(1000);
66             if (root != null) root.scan();
67         } catch (Exception e) { Log.error(Main.class, e); }
68     }
69
70 }