java euler.Codd
*
* @param args
* [--port port]
*/
public static void main(String[] args) {
try {
for (int i = 0; i < args.length; i++) {
if (args[i].endsWith("-port"))
port = Integer.parseInt(args[++i]);
else if (args[i].endsWith("-chatty"))
chatty = Integer.parseInt(args[++i]);
else if (args[i].endsWith("-properties"))
properties = args[++i];
}
if (new File(properties).exists()) {
Properties sys = System.getProperties();
Properties p = new Properties();
FileInputStream fip = new FileInputStream(properties);
p.load(fip);
fip.close();
Enumeration en = p.keys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
if (!sys.containsKey(key))
sys.put(key, p.get(key));
}
System.setProperties(sys);
}
new Codd();
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* constructs a web server
*/
public Codd() {
if (server != null)
return;
try {
server = new ServerSocket(port);
server.setSoTimeout(10000);
host = System.getProperty("process.host");
if (host == null)
host = InetAddress.getLocalHost().getCanonicalHostName();
lock = null;
Thread rst = new Thread(this, "Codd");
rst.start();
while (lock == null)
Thread.currentThread().sleep(10);
Thread.currentThread().setName("http://" + host + ":" + port + "/");
System.err.println(new java.util.Date().toGMTString() + " " + Thread.currentThread().getName() + " "
+ version);
} catch (Throwable t) {
t.printStackTrace();
}
}
public void run() {
if (lock == null) {
lock = new Object();
while (true) {
try {
Socket socket = null;
socket = ((ServerSocket) server).accept();
socket.setTcpNoDelay(true);
socket.setSoTimeout(60000);
while (lock == null)
Thread.currentThread().sleep(10);
synchronized (lock) {
if (pool == 0) {
Thread rt = new Thread(new Codd(), "Codd" + span);
rt.start();
span++;
}
handle = socket;
lock.notify();
while (handle != null)
lock.wait(10);
}
} catch (Throwable t) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException exc) {
break;
} catch (Throwable tr) {
tr.printStackTrace();
}
}
}
} else {
while (true) {
try {
nr++;
int fr = nr;
Socket socket = null;
synchronized (lock) {
pool++;
while (handle == null)
lock.wait();
socket = (Socket) handle;
handle = null;
lock.notify();
pool--;
}
Thread.currentThread().setName(socket.getInetAddress().getHostAddress());
InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "UTF8");
BufferedReader br = new BufferedReader(isr);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos, "UTF8"), true);
FileInputStream fis = null;
show(fr + " ========================================================");
String s = scan(br, null, fr);
if (chatty == 0)
System.err.println(new java.util.Date().toGMTString() + " " + Thread.currentThread().getName() + " " + fr
+ " " + (s.length() > 320 ? s.substring(0, 320) + "... (" + (s.length()-320) + " more)" : s));
StringTokenizer st = new StringTokenizer(s);
String m = st.nextToken();
String ff = st.nextToken();
String f = urlDecode(ff);
String ct = null;
String ce = "";
int g = -1;
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.ROOT);
sdf.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("GMT")));
java.util.Date ims = null;
while (!(s = scan(br, null, fr)).equals("")) {
st = new StringTokenizer(s);
String nt = st.nextToken().toLowerCase();
if (nt.equals("content-length:"))
g = Integer.parseInt(st.nextToken());
else if (nt.equals("if-modified-since:"))
ims = sdf.parse(s, new ParsePosition(19));
}
try {
Properties cp = new Properties();
if (new File(properties).exists()) {
FileInputStream fip = new FileInputStream(properties);
cp.load(fip);
fip.close();
}
long ttl = 5000;
if (cp.getProperty("process.ttl") != null)
ttl = Long.parseLong(cp.getProperty("process.ttl"));
long tb = System.nanoTime();
if (m.toLowerCase().equals("get") || m.toLowerCase().equals("head")) {
boolean get = m.toLowerCase().equals("get");
if (g != -1) {
if (ce.toLowerCase().startsWith("unicode"))
g = g / 2;
char[] b = new char[g];
int n = 0, count = 0;
while (n < g) {
count = br.read(b, n, g - n);
if (count < 0)
throw new EOFException();
n += count;
}
scan(null, new String(b), fr);
}
if (ff.indexOf('?') != -1)
f = f.substring(0, f.indexOf('?'));
String fp = f;
String mp = f.substring(1);
if (mp.indexOf('/') != -1) {
fp = mp.substring(mp.indexOf('/'));
mp = mp.substring(0, mp.indexOf('/'));
}
if (cp.getProperty("mapping." + mp) != null)
f = '/' + cp.getProperty("mapping." + mp) + fp;
File file = new File('.' + f);
if (!file.exists() || file.isDirectory()) {
if (file.isDirectory() && new File('.' + f + "index.html").exists())
f = f + "index.html";
else if (new File('.' + f + ".html").exists())
f = f + ".html";
else if (new File('.' + f + ".gif").exists())
f = f + ".gif";
else if (new File('.' + f + ".png").exists())
f = f + ".png";
else if (new File('.' + f + ".rdf").exists())
f = f + ".rdf";
else if (new File('.' + f + ".owl").exists())
f = f + ".owl";
else if (new File('.' + f + ".nt").exists())
f = f + ".nt";
else if (new File('.' + f + ".ttl").exists())
f = f + ".ttl";
else if (new File('.' + f + ".n3").exists())
f = f + ".n3";
}
file = new File('.' + f);
String db = f.substring(1);
if (db.indexOf('/') != -1)
db = db.substring(0, db.indexOf('/'));
else if (db.indexOf('.') != -1)
db = db.substring(0, db.indexOf('.'));
if (cp.getProperty(db + ".driver") != null) {
Class.forName(cp.getProperty(db + ".driver")).newInstance();
int len = db.length();
DriverManager.setLoginTimeout(5);
Connection con = DriverManager.getConnection(cp.getProperty(db + ".uri"), cp.getProperty(db
+ ".user"), cp.getProperty(db + ".password"));
print(pw, "HTTP/1.0 200 OK", fr);
pw.print("\r\n");
print(pw, "Server: " + version, fr);
pw.print("\r\n");
//print(pw, "Content-Type: text/n3", fr);
//pw.print("\r\n");
print(pw, "Expires: -1", fr);
pw.print("\r\n");
pw.print("\r\n");
pw.flush();
if (get && (ff.length() == len + 1 || ff.length() == len + 2 && ff.charAt(len + 1) == '/')) {
ResultSet rs = null;
try {
DatabaseMetaData md = con.getMetaData();
String[] names = { "TABLE" };
rs = md.getTables(db, "%", "%", names);
while (rs.next()) {
ResultSet rt = null;
try {
String table = rs.getString(3);
pw.println("### " + table + " table columns");
rt = md.getColumns(db, "%", table, "%");
while (rt.next())
pw.println("\n"); if (s2 != null) out.append(" " + "..\n"); String[] names = new File('.' + f).list(); if (names.length > 0) sort(names, 0, names.length - 1); long size = 0; int count = 0; for (int k = 0; k < names.length; k++) { String hname = '.' + f + File.separatorChar + names[k]; File h = new File(hname); if (!h.isDirectory()) size += h.length(); if (!h.isDirectory()) count++; String hType = h.isDirectory() ? "d" : "-"; String hRead = h.canRead() ? "r" : "-"; String hWrite = h.canWrite() ? "w" : "-"; String hSize = java.lang.Long.toString(h.length()); String hSizePad = " ".substring(hSize.length()); String hDate = (new java.util.Date(h.lastModified()).toGMTString()); String hDatePad = " ".substring(hDate.length()); String hFix = (h.isDirectory() ? "/" : ""); String hPrefix = (h.isDirectory() ? "" : ""); String hSuffix = (h.isDirectory() ? "/" : ""); out.append(hType + hRead + hWrite + hSizePad + hSize + hDatePad + hDate + " " + "" + hPrefix + names[k] + hSuffix + "\n"); } out.append("" + count + " files / " + size + " bytes\n"); return out.toString(); } static String scan(BufferedReader br, Object o, int fr) throws IOException { String s = null; if (br != null) s = br.readLine(); else s = o.toString(); if (s == null) throw new IOException("DataInputStream was closed during readLine"); show(fr + " Rcv " + s); return s; } static void print(PrintWriter pw, Object o, int fr) { if (pw != null) pw.print(o); show(fr + " Snd " + o); } static void show(String s) { if (chatty > 0) System.err.println(new java.util.Date().toGMTString() + " " + Thread.currentThread().getName() + " " + s); } }