moved to better jinetd setup
[org.ibex.jinetd.git] / src / org / ibex / jinetd / Main.java
index a8ae366..c2cb324 100644 (file)
@@ -1,10 +1,63 @@
 package org.ibex.jinetd;
 import org.ibex.util.*;
 import java.io.*;
+import java.net.*;
 import java.util.*;
+import java.util.zip.*;
 
 public class Main {
 
+    public static String ROOT;
+    public static String LOGFILE;
+    public static PrintStream LOGSTREAM;
+
+    private static void configureRoot() throws Exception {
+        ROOT = System.getProperty("jinetd.root", null);
+        if (ROOT == null) {
+            ROOT = autoDetectRoot();
+            System.setProperty("jinetd.root", ROOT);
+        }
+    }
+
+    private static void configureLogging() throws Exception {
+        LOGFILE  = System.getProperty("jinetd.logfile", ROOT + File.separatorChar+"log.txt");
+        LOGSTREAM = new PrintStream(new FileOutputStream(LOGFILE, true));
+        System.setErr(LOGSTREAM);
+        System.setOut(LOGSTREAM);
+    }
+
+    private static String autoDetectRoot() throws Exception {
+        if (!(Main.class.getClassLoader() instanceof URLClassLoader))
+            throw new Error("unable to detect jinetd.root because my ClassLoader is not an instanceof URLClassLoader");
+        URL[] urls = ((URLClassLoader)Main.class.getClassLoader()).getURLs();
+        for(int i=0; i<urls.length; i++) {
+            if (!urls[i].getProtocol().equals("file")) continue;
+            File file = new File(urls[i].getPath());
+            if (file.isDirectory()) {
+                if (new File(file.getAbsolutePath() +
+                             File.separatorChar + 
+                             Main.class.getName().replace('.', File.separatorChar)+".class").exists())
+                    return file.getAbsolutePath();
+            } else if (file.getAbsolutePath().endsWith(".jar")) {
+                ZipFile zf = new ZipFile(file);
+                if (zf.getEntry(Main.class.getName().replace('.', File.separatorChar)+".class") != null)
+                    return new File(file.getParent()).getAbsolutePath();
+            }
+        }
+        throw new Error("unable to detect jinetd.root because " +
+                        Main.class.getName() +
+                        " was not in any of the ClassLoader URLs");
+    }
+
+    static {
+        try {
+            configureRoot();
+            configureLogging();
+        } catch (Throwable e) {
+            throw new Error(e);
+        }
+    }
+
     public static void main(String[] s) throws Exception {
         Log.color = true;
         Root root = new Root(Root.root);