libmatthew-java-0.8.1/0000755000175000017500000000000013273415356013260 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/0000755000175000017500000000000012536305505013665 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/0000755000175000017500000000000012536305505014441 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/0000755000175000017500000000000012536305505016112 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/debug/0000755000175000017500000000000013273414417017202 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/debug/Debug.java0000644000175000017500000005236213273415260021100 0ustar mjj29mjj29/* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include or any other header that includes because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 . */ /* * Java Debug Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.debug; import cx.ath.matthew.utils.Hexdump; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; /** Add debugging to your program, has support for large projects with multiple classes and debug levels per class. Supports optional enabling of debug per-level per-class and debug targets of files, Streams or stderr. Also supports timing between debug outputs, printing of stack traces for Throwables and files/line numbers on each message.

Debug now automatically figures out which class it was called from, so all methods passing in the calling class are deprecated.

The defaults are to print all messages to stderr with class and method name.

Should be called like this:

   if (Debug.debug) Debug.print(Debug.INFO, "Debug Message");
  
*/ public class Debug { /** This interface can be used to provide custom printing filters for certain classes. */ public static interface FilterCommand { /** Called to print debug messages with a custom filter. @param output The PrintStream to output to. @param level The debug level of this message. @param location The textual location of the message. @param extra Extra information such as timing details. @param message The debug message. @param lines Other lines of a multiple-line debug message. */ public void filter(PrintStream output, int level, String location, String extra, String message, String[] lines); } /** Highest priority messages */ public static final int CRIT = 1; /** Error messages */ public static final int ERR = 2; /** Warnings */ public static final int WARN = 3; /** Information */ public static final int INFO = 4; /** Debug messages */ public static final int DEBUG = 5; /** Verbose debug messages */ public static final int VERBOSE = 6; /** Set this to false to disable compilation of Debug statements */ public static final boolean debug = false; /** The current output stream (defaults to System.err) */ public static PrintStream debugout = System.err; private static Properties prop = null; private static boolean timing = false; private static boolean ttrace = false; private static boolean lines = false; private static boolean hexdump = false; private static long last = 0; private static int balen = 36; private static int bawidth = 80; private static Class saveclass = null; //TODO: 1.5 private static Map, FilterCommand> filterMap = new HashMap, FilterCommand>(); private static Map filterMap = new HashMap(); /** Set properties to configure debugging. Format of properties is class => level, e.g.
      cx.ath.matthew.io.TeeOutputStream = INFO
      cx.ath.matthew.io.DOMPrinter = DEBUG
     
The debug level can be one of CRIT, ERR, WARN, INFO, DEBUG or VERBOSE which correspond to all messages up to that level. The special words YES, ALL and TRUE cause all messages to be printed regardless of level. All other terms disable messages for that class. CRIT and ERR messages are always printed if debugging is enabled unless explicitly disabled. The special class name ALL can be used to set the default level for all classes. @param prop Properties object to use. */ public static void setProperties(Properties prop) { Debug.prop = prop; } /** Read which class to debug on at which level from the given File. Syntax the same as Java Properties files:
     <class> = <debuglevel>
     
E.G.
      cx.ath.matthew.io.TeeOutputStream = INFO
      cx.ath.matthew.io.DOMPrinter = DEBUG
     
The debug level can be one of CRIT, ERR, WARN, INFO, DEBUG or VERBOSE which correspond to all messages up to that level. The special words YES, ALL and TRUE cause all messages to be printed regardless of level. All other terms disable messages for that class. CRIT and ERR messages are always printed if debugging is enabled unless explicitly disabled. The special class name ALL can be used to set the default level for all classes. @param f File to read from. */ public static void loadConfig(File f) throws IOException { prop = new Properties(); prop.load(new FileInputStream(f)); } /** @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static boolean debugging(Class c, int loglevel) { if (debug) { if (null == c) return true; return debugging(c.getName(), loglevel); } return false; } public static boolean debugging(String s, int loglevel) { if (debug) { try { if (null == s) return true; if (null == prop) return loglevel <= DEBUG; String d = prop.getProperty(s); if (null == d || "".equals(d)) d = prop.getProperty("ALL"); if (null == d) return loglevel <= ERR; if ("".equals(d)) return loglevel <= ERR; d = d.toLowerCase(); if ("true".equals(d)) return true; if ("yes".equals(d)) return true; if ("all".equals(d)) return true; if ("verbose".equals(d)) return loglevel <= VERBOSE; if ("debug".equals(d)) return loglevel <= DEBUG; if ("info".equals(d)) return loglevel <= INFO; if ("warn".equals(d)) return loglevel <= WARN; if ("err".equals(d)) return loglevel <= ERR; if ("crit".equals(d)) return loglevel <= CRIT; int i = Integer.parseInt(d); return i >= loglevel; } catch (Exception e) { return false; } } return false; } /** Output to the given Stream */ public static void setOutput(PrintStream p) throws IOException { debugout = p; } /** Output to the given file */ public static void setOutput(String filename) throws IOException { debugout = new PrintStream(new FileOutputStream(filename, true)); } /** Output to the default debug.log */ public static void setOutput() throws IOException { setOutput("./debug.log"); } /** Log at DEBUG @param d The object to log */ public static void print(Object d) { if (debug) { if (d instanceof String) print(DEBUG, (String) d); else if (d instanceof Throwable) print(DEBUG, (Throwable) d); else if (d instanceof byte[]) print(DEBUG, (byte[]) d); else if (d instanceof Map) printMap(DEBUG, (Map) d); else print(DEBUG, d); } } /** Log at DEBUG @param o The object doing the logging @param d The object to log @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, Object d) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(d); } } /** Log an Object @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param d The object to log with d.toString() @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, int loglevel, Object d) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(loglevel, d); } } /** Log a String @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param s The log message @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, int loglevel, String s) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(loglevel, s); } } /** Log a Throwable @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param t The throwable to log with .toString and .printStackTrace @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, int loglevel, Throwable t) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(loglevel, t); } } /** Log a Throwable @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param t The throwable to log with .toString and .printStackTrace @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Class c, int loglevel, Throwable t) { if (debug) { saveclass = c; print(loglevel, t); } } /** Log a Throwable @param loglevel The level to log at (DEBUG, WARN, etc) @param t The throwable to log with .toString and .printStackTrace @see #setThrowableTraces to turn on stack traces. */ public static void print(int loglevel, Throwable t) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } String[] lines = null; if (ttrace) { StackTraceElement[] ste = t.getStackTrace(); lines = new String[ste.length]; for (int i = 0; i < ste.length; i++) lines[i] = "\tat "+ste[i].toString(); } _print(t.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, t.toString(), lines); } } } /** Log a byte array @param loglevel The level to log at (DEBUG, WARN, etc) @param b The byte array to print. @see #setHexDump to enable hex dumping. @see #setByteArrayCount to change how many bytes are printed. @see #setByteArrayWidth to change the formatting width of hex. */ public static void print(int loglevel, byte[] b) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } String[] lines = null; if (hexdump) { if (balen >= b.length) lines = Hexdump.format(b, bawidth).split("\n"); else { byte[] buf = new byte[balen]; System.arraycopy(b, 0, buf, 0, balen); lines = Hexdump.format(buf, bawidth).split("\n"); } } _print(b.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, b.length+" bytes", lines); } } } /** Log a String @param loglevel The level to log at (DEBUG, WARN, etc) @param s The string to log with d.toString() */ public static void print(int loglevel, String s) { if (debug) print(loglevel, (Object) s); } /** Log an Object @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param d The object to log with d.toString() @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Class c, int loglevel, Object d) { if (debug) { saveclass = c; print(loglevel, d); } } /** Log a String @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param s The log message @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Class c, int loglevel, String s) { if (debug) { saveclass = c; print(loglevel, s); } } private static String[] getTraceElements() { String[] data = new String[] { "", "", "" }; try { Method m = Thread.class.getMethod("getStackTrace", new Class[0]); StackTraceElement[] stes = (StackTraceElement[]) m.invoke(Thread.currentThread(), new Object[0]); for (StackTraceElement ste: stes) { if (Debug.class.getName().equals(ste.getClassName())) continue; if (Thread.class.getName().equals(ste.getClassName())) continue; if (Method.class.getName().equals(ste.getClassName())) continue; if (ste.getClassName().startsWith("sun.reflect")) continue; data[0] = ste.getClassName(); data[1] = ste.getMethodName(); if (lines) data[2] = " "+ste.getFileName()+":"+ste.getLineNumber(); break; } } catch (NoSuchMethodException NSMe) { if (null != saveclass) data[0] = saveclass.getName(); } catch (IllegalAccessException IAe) { } catch (InvocationTargetException ITe) { } return data; } /** Log an Object @param loglevel The level to log at (DEBUG, WARN, etc) @param o The object to log */ public static void print(int loglevel, Object o) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } _print(o.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, o.toString(), null); } } } /** Log a Map @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param m The Map to print out @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void printMap(Object o, int loglevel, Map m) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); printMap(loglevel, m); } } /** Log a Map @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param m The Map to print out @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void printMap(Class c, int loglevel, Map m) { if (debug) { saveclass = c; printMap(loglevel, m); } } /** Log a Map at DEBUG log level @param m The Map to print out */ public static void printMap(Map m) { printMap(DEBUG, m); } /** Log a Map @param loglevel The level to log at (DEBUG, WARN, etc) @param m The Map to print out */ public static void printMap(int loglevel, Map m) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } Iterator i = m.keySet().iterator(); String[] lines = new String[m.size()]; int j = 0; while (i.hasNext()) { Object key = i.next(); lines[j++] = "\t\t- "+key+" => "+m.get(key); } _print(m.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, "Map:", lines); } } } /** Enable or disable stack traces in Debuging throwables. */ public static void setThrowableTraces(boolean ttrace) { Debug.ttrace = ttrace; } /** Enable or disable timing in Debug messages. */ public static void setTiming(boolean timing) { Debug.timing = timing; } /** Enable or disable line numbers. */ public static void setLineNos(boolean lines) { Debug.lines = lines; } /** Enable or disable hexdumps. */ public static void setHexDump(boolean hexdump) { Debug.hexdump = hexdump; } /** Set the size of hexdumps. (Default: 36) */ public static void setByteArrayCount(int count) { Debug.balen = count; } /** Set the formatted width of hexdumps. (Default: 80 chars) */ public static void setByteArrayWidth(int width) { Debug.bawidth = width; } /** Add a filter command for a specific type. This command will be called with the output stream and the text to be sent. It should perform any changes necessary to the text and then print the result to the output stream. */ public static void addFilterCommand(Class c, FilterCommand f) //TODO 1.5: public static void addFilterCommand(Class c, FilterCommand f) { filterMap.put(c, f); } private static void _print(Class c, int level, String loc, String extra, String message, String[] lines) { //TODO 1.5: FilterCommand f = filterMap.get(c); FilterCommand f = (FilterCommand) filterMap.get(c); if (null == f) { debugout.println("["+loc+"] " +extra + message); if (null != lines) for (String s: lines) debugout.println(s); } else f.filter(debugout, level, loc, extra, message, lines); } } libmatthew-java-0.8.1/cx/ath/matthew/debug/Debug.jpp0000644000175000017500000004710213273414417020747 0ustar mjj29mjj29/* * Java Debug Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.debug; import cx.ath.matthew.utils.Hexdump; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; /** Add debugging to your program, has support for large projects with multiple classes and debug levels per class. Supports optional enabling of debug per-level per-class and debug targets of files, Streams or stderr. Also supports timing between debug outputs, printing of stack traces for Throwables and files/line numbers on each message.

Debug now automatically figures out which class it was called from, so all methods passing in the calling class are deprecated.

The defaults are to print all messages to stderr with class and method name.

Should be called like this:

   if (Debug.debug) Debug.print(Debug.INFO, "Debug Message");
  
*/ public class Debug { /** This interface can be used to provide custom printing filters for certain classes. */ public static interface FilterCommand { /** Called to print debug messages with a custom filter. @param output The PrintStream to output to. @param level The debug level of this message. @param location The textual location of the message. @param extra Extra information such as timing details. @param message The debug message. @param lines Other lines of a multiple-line debug message. */ public void filter(PrintStream output, int level, String location, String extra, String message, String[] lines); } /** Highest priority messages */ public static final int CRIT = 1; /** Error messages */ public static final int ERR = 2; /** Warnings */ public static final int WARN = 3; /** Information */ public static final int INFO = 4; /** Debug messages */ public static final int DEBUG = 5; /** Verbose debug messages */ public static final int VERBOSE = 6; /** Set this to false to disable compilation of Debug statements */ public static final boolean debug = DEBUGSETTING; /** The current output stream (defaults to System.err) */ public static PrintStream debugout = System.err; private static Properties prop = null; private static boolean timing = false; private static boolean ttrace = false; private static boolean lines = false; private static boolean hexdump = false; private static long last = 0; private static int balen = 36; private static int bawidth = 80; private static Class saveclass = null; //TODO: 1.5 private static Map, FilterCommand> filterMap = new HashMap, FilterCommand>(); private static Map filterMap = new HashMap(); /** Set properties to configure debugging. Format of properties is class => level, e.g.
      cx.ath.matthew.io.TeeOutputStream = INFO
      cx.ath.matthew.io.DOMPrinter = DEBUG
     
The debug level can be one of CRIT, ERR, WARN, INFO, DEBUG or VERBOSE which correspond to all messages up to that level. The special words YES, ALL and TRUE cause all messages to be printed regardless of level. All other terms disable messages for that class. CRIT and ERR messages are always printed if debugging is enabled unless explicitly disabled. The special class name ALL can be used to set the default level for all classes. @param prop Properties object to use. */ public static void setProperties(Properties prop) { Debug.prop = prop; } /** Read which class to debug on at which level from the given File. Syntax the same as Java Properties files:
     <class> = <debuglevel>
     
E.G.
      cx.ath.matthew.io.TeeOutputStream = INFO
      cx.ath.matthew.io.DOMPrinter = DEBUG
     
The debug level can be one of CRIT, ERR, WARN, INFO, DEBUG or VERBOSE which correspond to all messages up to that level. The special words YES, ALL and TRUE cause all messages to be printed regardless of level. All other terms disable messages for that class. CRIT and ERR messages are always printed if debugging is enabled unless explicitly disabled. The special class name ALL can be used to set the default level for all classes. @param f File to read from. */ public static void loadConfig(File f) throws IOException { prop = new Properties(); prop.load(new FileInputStream(f)); } /** @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static boolean debugging(Class c, int loglevel) { if (debug) { if (null == c) return true; return debugging(c.getName(), loglevel); } return false; } public static boolean debugging(String s, int loglevel) { if (debug) { try { if (null == s) return true; if (null == prop) return loglevel <= DEBUG; String d = prop.getProperty(s); if (null == d || "".equals(d)) d = prop.getProperty("ALL"); if (null == d) return loglevel <= ERR; if ("".equals(d)) return loglevel <= ERR; d = d.toLowerCase(); if ("true".equals(d)) return true; if ("yes".equals(d)) return true; if ("all".equals(d)) return true; if ("verbose".equals(d)) return loglevel <= VERBOSE; if ("debug".equals(d)) return loglevel <= DEBUG; if ("info".equals(d)) return loglevel <= INFO; if ("warn".equals(d)) return loglevel <= WARN; if ("err".equals(d)) return loglevel <= ERR; if ("crit".equals(d)) return loglevel <= CRIT; int i = Integer.parseInt(d); return i >= loglevel; } catch (Exception e) { return false; } } return false; } /** Output to the given Stream */ public static void setOutput(PrintStream p) throws IOException { debugout = p; } /** Output to the given file */ public static void setOutput(String filename) throws IOException { debugout = new PrintStream(new FileOutputStream(filename, true)); } /** Output to the default debug.log */ public static void setOutput() throws IOException { setOutput("./debug.log"); } /** Log at DEBUG @param d The object to log */ public static void print(Object d) { if (debug) { if (d instanceof String) print(DEBUG, (String) d); else if (d instanceof Throwable) print(DEBUG, (Throwable) d); else if (d instanceof byte[]) print(DEBUG, (byte[]) d); else if (d instanceof Map) printMap(DEBUG, (Map) d); else print(DEBUG, d); } } /** Log at DEBUG @param o The object doing the logging @param d The object to log @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, Object d) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(d); } } /** Log an Object @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param d The object to log with d.toString() @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, int loglevel, Object d) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(loglevel, d); } } /** Log a String @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param s The log message @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, int loglevel, String s) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(loglevel, s); } } /** Log a Throwable @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param t The throwable to log with .toString and .printStackTrace @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Object o, int loglevel, Throwable t) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); print(loglevel, t); } } /** Log a Throwable @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param t The throwable to log with .toString and .printStackTrace @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Class c, int loglevel, Throwable t) { if (debug) { saveclass = c; print(loglevel, t); } } /** Log a Throwable @param loglevel The level to log at (DEBUG, WARN, etc) @param t The throwable to log with .toString and .printStackTrace @see #setThrowableTraces to turn on stack traces. */ public static void print(int loglevel, Throwable t) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } String[] lines = null; if (ttrace) { StackTraceElement[] ste = t.getStackTrace(); lines = new String[ste.length]; for (int i = 0; i < ste.length; i++) lines[i] = "\tat "+ste[i].toString(); } _print(t.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, t.toString(), lines); } } } /** Log a byte array @param loglevel The level to log at (DEBUG, WARN, etc) @param b The byte array to print. @see #setHexDump to enable hex dumping. @see #setByteArrayCount to change how many bytes are printed. @see #setByteArrayWidth to change the formatting width of hex. */ public static void print(int loglevel, byte[] b) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } String[] lines = null; if (hexdump) { if (balen >= b.length) lines = Hexdump.format(b, bawidth).split("\n"); else { byte[] buf = new byte[balen]; System.arraycopy(b, 0, buf, 0, balen); lines = Hexdump.format(buf, bawidth).split("\n"); } } _print(b.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, b.length+" bytes", lines); } } } /** Log a String @param loglevel The level to log at (DEBUG, WARN, etc) @param s The string to log with d.toString() */ public static void print(int loglevel, String s) { if (debug) print(loglevel, (Object) s); } /** Log an Object @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param d The object to log with d.toString() @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Class c, int loglevel, Object d) { if (debug) { saveclass = c; print(loglevel, d); } } /** Log a String @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param s The log message @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void print(Class c, int loglevel, String s) { if (debug) { saveclass = c; print(loglevel, s); } } private static String[] getTraceElements() { String[] data = new String[] { "", "", "" }; try { Method m = Thread.class.getMethod("getStackTrace", new Class[0]); StackTraceElement[] stes = (StackTraceElement[]) m.invoke(Thread.currentThread(), new Object[0]); for (StackTraceElement ste: stes) { if (Debug.class.getName().equals(ste.getClassName())) continue; if (Thread.class.getName().equals(ste.getClassName())) continue; if (Method.class.getName().equals(ste.getClassName())) continue; if (ste.getClassName().startsWith("sun.reflect")) continue; data[0] = ste.getClassName(); data[1] = ste.getMethodName(); if (lines) data[2] = " "+ste.getFileName()+":"+ste.getLineNumber(); break; } } catch (NoSuchMethodException NSMe) { if (null != saveclass) data[0] = saveclass.getName(); } catch (IllegalAccessException IAe) { } catch (InvocationTargetException ITe) { } return data; } /** Log an Object @param loglevel The level to log at (DEBUG, WARN, etc) @param o The object to log */ public static void print(int loglevel, Object o) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } _print(o.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, o.toString(), null); } } } /** Log a Map @param o The object doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param m The Map to print out @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void printMap(Object o, int loglevel, Map m) { if (debug) { if (o instanceof Class) saveclass = (Class) o; else saveclass = o.getClass(); printMap(loglevel, m); } } /** Log a Map @param c The class doing the logging @param loglevel The level to log at (DEBUG, WARN, etc) @param m The Map to print out @deprecated In Java 1.5 calling class is automatically identified, no need to pass it in. */ //TODO: 1.5 @Deprecated() public static void printMap(Class c, int loglevel, Map m) { if (debug) { saveclass = c; printMap(loglevel, m); } } /** Log a Map at DEBUG log level @param m The Map to print out */ public static void printMap(Map m) { printMap(DEBUG, m); } /** Log a Map @param loglevel The level to log at (DEBUG, WARN, etc) @param m The Map to print out */ public static void printMap(int loglevel, Map m) { if (debug) { String timestr = ""; String[] data = getTraceElements(); if (debugging(data[0], loglevel)) { if (timing) { long now = System.currentTimeMillis(); timestr = "{" + (now-last) + "} "; last = now; } Iterator i = m.keySet().iterator(); String[] lines = new String[m.size()]; int j = 0; while (i.hasNext()) { Object key = i.next(); lines[j++] = "\t\t- "+key+" => "+m.get(key); } _print(m.getClass(), loglevel, data[0]+"."+data[1]+"()" + data[2], timestr, "Map:", lines); } } } /** Enable or disable stack traces in Debuging throwables. */ public static void setThrowableTraces(boolean ttrace) { Debug.ttrace = ttrace; } /** Enable or disable timing in Debug messages. */ public static void setTiming(boolean timing) { Debug.timing = timing; } /** Enable or disable line numbers. */ public static void setLineNos(boolean lines) { Debug.lines = lines; } /** Enable or disable hexdumps. */ public static void setHexDump(boolean hexdump) { Debug.hexdump = hexdump; } /** Set the size of hexdumps. (Default: 36) */ public static void setByteArrayCount(int count) { Debug.balen = count; } /** Set the formatted width of hexdumps. (Default: 80 chars) */ public static void setByteArrayWidth(int width) { Debug.bawidth = width; } /** Add a filter command for a specific type. This command will be called with the output stream and the text to be sent. It should perform any changes necessary to the text and then print the result to the output stream. */ public static void addFilterCommand(Class c, FilterCommand f) //TODO 1.5: public static void addFilterCommand(Class c, FilterCommand f) { filterMap.put(c, f); } private static void _print(Class c, int level, String loc, String extra, String message, String[] lines) { //TODO 1.5: FilterCommand f = filterMap.get(c); FilterCommand f = (FilterCommand) filterMap.get(c); if (null == f) { debugout.println("["+loc+"] " +extra + message); if (null != lines) for (String s: lines) debugout.println(s); } else f.filter(debugout, level, loc, extra, message, lines); } } libmatthew-java-0.8.1/cx/ath/matthew/utils/0000755000175000017500000000000013273414417017254 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/utils/Hexdump.java0000644000175000017500000001115413273414417021533 0ustar mjj29mjj29/* * Java Hexdump Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.utils; import java.io.PrintStream; public class Hexdump { public static final char[] hexchars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String toHex(byte[] buf) { return toHex(buf, 0, buf.length); } public static String toHex(byte[] buf, int ofs, int len) { StringBuffer sb = new StringBuffer(); int j = ofs+len; for (int i = ofs; i < j; i++) { if (i < buf.length) { sb.append(hexchars[(buf[i] & 0xF0) >> 4]); sb.append(hexchars[buf[i] & 0x0F]); sb.append(' '); } else { sb.append(' '); sb.append(' '); sb.append(' '); } } return sb.toString(); } public static String toAscii(byte[] buf) { return toAscii(buf, 0, buf.length); } public static String toAscii(byte[] buf, int ofs, int len) { StringBuffer sb = new StringBuffer(); int j = ofs+len; for (int i = ofs; i < j ; i++) { if (i < buf.length) { if (20 <= buf[i] && 126 >= buf[i]) sb.append((char) buf[i]); else sb.append('.'); } else sb.append(' '); } return sb.toString(); } public static String format(byte[] buf) { return format(buf, 80); } public static String format(byte[] buf, int width) { int bs = (width - 8) / 4; int i = 0; StringBuffer sb = new StringBuffer(); do { for (int j = 0; j < 6; j++) { sb.append(hexchars[(i << (j*4) & 0xF00000) >> 20]); } sb.append('\t'); sb.append(toHex(buf, i, bs)); sb.append(' '); sb.append(toAscii(buf, i, bs)); sb.append('\n'); i += bs; } while (i < buf.length); return sb.toString(); } public static void print(byte[] buf) { print(buf, System.err); } public static void print(byte[] buf, int width) { print(buf, width, System.err); } public static void print(byte[] buf, int width, PrintStream out) { out.print(format(buf, width)); } public static void print(byte[] buf, PrintStream out) { out.print(format(buf)); } /** * Returns a string which can be written to a Java source file as part * of a static initializer for a byte array. * Returns data in the format 0xAB, 0xCD, .... * use like: * javafile.print("byte[] data = {") * javafile.print(Hexdump.toByteArray(data)); * javafile.println("};"); */ public static String toByteArray(byte[] buf) { return toByteArray(buf, 0, buf.length); } /** * Returns a string which can be written to a Java source file as part * of a static initializer for a byte array. * Returns data in the format 0xAB, 0xCD, .... * use like: * javafile.print("byte[] data = {") * javafile.print(Hexdump.toByteArray(data)); * javafile.println("};"); */ public static String toByteArray(byte[] buf, int ofs, int len) { StringBuffer sb = new StringBuffer(); for (int i = ofs; i < len && i < buf.length; i++) { sb.append('0'); sb.append('x'); sb.append(hexchars[(buf[i] & 0xF0) >> 4]); sb.append(hexchars[buf[i] & 0x0F]); if ((i+1) < len && (i+1) < buf.length) sb.append(','); } return sb.toString(); } } libmatthew-java-0.8.1/cx/ath/matthew/io/0000755000175000017500000000000013273414417016523 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/io/test2.java0000644000175000017500000000307013273414417020427 0ustar mjj29mjj29/* * Java IO Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.BufferedReader; import java.io.InputStreamReader; class test2 { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(new ExecInputStream(System.in, "xsltproc mcr.xsl -"))); String s; while (null != (s = in.readLine())) System.out.println(s); } } libmatthew-java-0.8.1/cx/ath/matthew/io/TeeOutputStream.java0000644000175000017500000001021413273414417022476 0ustar mjj29mjj29/* * Java Tee Stream Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.OutputStream; import java.io.IOException; /** * Class to copy a stream to another stream or file as it is being sent through a stream pipe * E.g. *
 *    PrintWriter r = new PrintWriter(new TeeOutputStream(new FileOutputStream("file"), new File("otherfile")));
 * 
*/ public class TeeOutputStream extends FilterOutputStream { private File f; private OutputStream out; private OutputStream fos; /** * Create a new TeeOutputStream on the given OutputStream * and copy the stream to the other OuputStream. * @param os Writes to this OutputStream * @param tos Write to this OutputStream */ public TeeOutputStream(OutputStream os, OutputStream tos) throws IOException { super(os); this.out = os; this.fos = tos; } /** * Create a new TeeOutputStream on the given OutputStream * and copy the stream to the given File. * @param os Writes to this OutputStream * @param f Write to this File * @param append Append to file not overwrite */ public TeeOutputStream(OutputStream os, File f, boolean append) throws IOException { super(os); this.out = os; this.fos = new FileOutputStream(f, append); } /** * Create a new TeeOutputStream on the given OutputStream * and copy the stream to the given File. * @param os Writes to this OutputStream * @param f Write to this File */ public TeeOutputStream(OutputStream os, File f) throws IOException { super(os); this.out = os; this.fos = new FileOutputStream(f); } /** * Create a new TeeOutputStream on the given OutputStream * and copy the stream to the given File. * @param os Writes to this OutputStream * @param f Write to this File * @param append Append to file not overwrite */ public TeeOutputStream(OutputStream os, String f, boolean append) throws IOException { this(os, new File(f), append); } /** * Create a new TeeOutputStream on the given OutputStream * and copy the stream to the given File. * @param os Writes to this OutputStream * @param f Write to this File */ public TeeOutputStream(OutputStream os, String f) throws IOException { this(os, new File(f)); } public void close() throws IOException { out.close(); fos.close(); } public void flush() throws IOException { fos.flush(); out.flush(); } public void write(int b) throws IOException { fos.write(b); out.write(b); } public void write(byte[] b) throws IOException { fos.write(b); out.write(b); } public void write(byte[] b, int off, int len) throws IOException { fos.write(b, off, len); out.write(b, off, len); } public void finalize() { try { close(); } catch (Exception e) {} } } libmatthew-java-0.8.1/cx/ath/matthew/io/test3.java0000644000175000017500000000326413273414417020435 0ustar mjj29mjj29/* * Java IO Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; class test3 { public static void main(String[] args) throws Exception { String file = args[0]; PrintWriter p = new PrintWriter(new TeeOutputStream(System.out, file)); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String s; while (null != (s = r.readLine())) p.println(s); p.close(); r.close(); } } libmatthew-java-0.8.1/cx/ath/matthew/io/ExecInputStream.java0000644000175000017500000001146413273414417022454 0ustar mjj29mjj29/* * Java Exec Pipe Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; /** * Class to pipe an InputStream through a command using stdin/stdout. * E.g. *
 *    Reader r = new InputStreamReader(new ExecInputStream(new FileInputStream("file"), "command"));
 * 
*/ public class ExecInputStream extends FilterInputStream { private Process proc; private InputStream stdout; private OutputStream stdin; private InOutCopier copy; /** * Create a new ExecInputStream on the given InputStream * using the process to filter the stream. * @param is Reads from this InputStream * @param p Filters data through stdin/out on this Process */ public ExecInputStream(InputStream is, Process p) throws IOException { super(is); proc = p; stdin = p.getOutputStream(); stdout = p.getInputStream(); copy = new InOutCopier(in, stdin); copy.start(); } /** * Create a new ExecInputStream on the given InputStream * using the process to filter the stream. * @param is Reads from this InputStream * @param cmd Creates a Process from this string to filter data through stdin/out */ public ExecInputStream(InputStream is, String cmd) throws IOException { this(is, Runtime.getRuntime().exec(cmd)); } /** * Create a new ExecInputStream on the given InputStream * using the process to filter the stream. * @param is Reads from this InputStream * @param cmd Creates a Process from this string array (command, arg, ...) to filter data through stdin/out */ public ExecInputStream(InputStream is, String[] cmd) throws IOException { this(is, Runtime.getRuntime().exec(cmd)); } /** * Create a new ExecInputStream on the given InputStream * using the process to filter the stream. * @param is Reads from this InputStream * @param cmd Creates a Process from this string to filter data through stdin/out * @param env Setup the environment for the command */ public ExecInputStream(InputStream is, String cmd, String[] env) throws IOException { this(is, Runtime.getRuntime().exec(cmd, env)); } /** * Create a new ExecInputStream on the given InputStream * using the process to filter the stream. * @param is Reads from this InputStream * @param cmd Creates a Process from this string array (command, arg, ...) to filter data through stdin/out * @param env Setup the environment for the command */ public ExecInputStream(InputStream is, String[] cmd, String[] env) throws IOException { this(is, Runtime.getRuntime().exec(cmd, env)); } public void close() throws IOException { try { proc.waitFor(); } catch (InterruptedException Ie) {} //copy.close(); try { copy.join(); } catch (InterruptedException Ie) {} stdin.close(); in.close(); stdout.close(); } public void flush() throws IOException { copy.flush(); } public int available() throws IOException { return stdout.available(); } public int read() throws IOException { return stdout.read(); } public int read(byte[] b) throws IOException { return stdout.read(b); } public int read(byte[] b, int off, int len) throws IOException { return stdout.read(b, off, len); } public long skip(long n) throws IOException { return stdout.skip(n); } public void mark(int readlimit) {} public boolean markSupported() { return false; } public void reset() {} public void finalize() { try { close(); } catch (Exception e) {} } } libmatthew-java-0.8.1/cx/ath/matthew/io/TeeInputStream.java0000644000175000017500000001077313273414417022307 0ustar mjj29mjj29/* * Java Tee Stream Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.File; import java.io.FileOutputStream; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; /** * Class to copy a stream to a file or another stream as it is being sent through a stream pipe * E.g. *
 *    Reader r = new InputStreamReader(new TeeInputStream(new FileInputStream("file"), new File("otherfile")));
 * 
*/ public class TeeInputStream extends FilterInputStream { private InputStream in; private OutputStream fos; /** * Create a new TeeInputStream on the given InputStream * and copy the stream to the given File. * @param is Reads from this InputStream * @param tos Write to this OutputStream */ public TeeInputStream(InputStream is, OutputStream tos) throws IOException { super(is); this.in = is; this.fos = tos; } /** * Create a new TeeInputStream on the given InputStream * and copy the stream to the given File. * @param is Reads from this InputStream * @param f Write to this File * @param append Append to file not overwrite */ public TeeInputStream(InputStream is, File f, boolean append) throws IOException { super(is); this.in = is; this.fos = new FileOutputStream(f, append); } /** * Create a new TeeInputStream on the given InputStream * and copy the stream to the given File. * @param is Reads from this InputStream * @param f Write to this File */ public TeeInputStream(InputStream is, File f) throws IOException { super(is); this.in = is; this.fos = new FileOutputStream(f); } /** * Create a new TeeInputStream on the given InputStream * and copy the stream to the given File. * @param is Reads from this InputStream * @param f Write to this File * @param append Append to file not overwrite */ public TeeInputStream(InputStream is, String f, boolean append) throws IOException { this(is, new File(f), append); } /** * Create a new TeeInputStream on the given InputStream * and copy the stream to the given File. * @param is Reads from this InputStream * @param f Write to this File */ public TeeInputStream(InputStream is, String f) throws IOException { this(is, new File(f)); } public void close() throws IOException { in.close(); fos.close(); } public void flush() throws IOException { fos.flush(); } public int available() throws IOException { return in.available(); } public int read() throws IOException { int i = in.read(); if (-1 != i) fos.write(i); return i; } public int read(byte[] b) throws IOException { int c = in.read(b); if (-1 != c) fos.write(b, 0, c); return c; } public int read(byte[] b, int off, int len) throws IOException { int c = in.read(b, off, len); if (-1 != c) fos.write(b, off, c); return c; } public long skip(long n) throws IOException { return in.skip(n); } public void mark(int readlimit) {} public boolean markSupported() { return false; } public void reset() throws IOException { in.reset(); } public void finalize() { try { close(); } catch (Exception e) {} } } libmatthew-java-0.8.1/cx/ath/matthew/io/InOutCopier.java0000644000175000017500000000644113273414417021573 0ustar mjj29mjj29/* * Java Exec Pipe Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Copies from an input stream to an output stream using a Thread. * example: * *
 * InputStream a = getInputStream();
 * OutputStream b = getOutputStream();
 * InOutCopier copier = new InOutCopier(a, b);
 * copier.start();
 * <do stuff that writes to the inputstream>
 * 
*/ public class InOutCopier extends Thread { private static final int BUFSIZE=1024; private static final int POLLTIME=100; private BufferedInputStream is; private OutputStream os; private boolean enable; /** * Create a copier from an inputstream to an outputstream * @param is The stream to copy from * @param os the stream to copy to */ public InOutCopier(InputStream is, OutputStream os) throws IOException { this.is = new BufferedInputStream(is); this.os = os; this.enable = true; } /** * Force close the stream without waiting for EOF on the source */ public void close() { enable = false; interrupt(); } /** * Flush the outputstream */ public void flush() throws IOException { os.flush(); } /** Start the thread and wait to make sure its really started */ public synchronized void start() { super.start(); try { wait(); } catch (InterruptedException Ie) {} } /** * Copies from the inputstream to the outputstream * until EOF on the inputstream or explicitly closed * @see #close() */ public void run() { byte[] buf = new byte[BUFSIZE]; synchronized (this) { notifyAll(); } while (enable) try { int n = is.read(buf); if (0 > n) break; if (0 < n) { os.write(buf, 0, (n> BUFSIZE? BUFSIZE:n)); os.flush(); } } catch (IOException IOe) { break; } try { os.close(); } catch (IOException IOe) {} } } libmatthew-java-0.8.1/cx/ath/matthew/io/ExecOutputStream.java0000644000175000017500000001115613273414417022653 0ustar mjj29mjj29/* * Java Exec Pipe Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.FilterOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; /** * Class to pipe an OutputStream through a command using stdin/stdout. * E.g. *
 *    Writer w = new OutputStreamWriter(new ExecOutputStream(new FileOutputStream("file"), "command"));
 * 
*/ public class ExecOutputStream extends FilterOutputStream { private Process proc; private InputStream stdout; private OutputStream stdin; private InOutCopier copy; /** * Create a new ExecOutputStream on the given OutputStream * using the process to filter the stream. * @param os Writes to this OutputStream * @param p Filters data through stdin/out on this Process */ public ExecOutputStream(OutputStream os, Process p) throws IOException { super(os); proc = p; stdin = p.getOutputStream(); stdout = p.getInputStream(); copy = new InOutCopier(stdout, out); copy.start(); } /** * Create a new ExecOutputStream on the given OutputStream * using the process to filter the stream. * @param os Writes to this OutputStream * @param cmd Creates a Process from this string to filter data through stdin/out */ public ExecOutputStream(OutputStream os, String cmd) throws IOException { this(os, Runtime.getRuntime().exec(cmd)); } /** * Create a new ExecOutputStream on the given OutputStream * using the process to filter the stream. * @param os Writes to this OutputStream * @param cmd Creates a Process from this string array (command, arg, ...) to filter data through stdin/out */ public ExecOutputStream(OutputStream os, String[] cmd) throws IOException { this(os, Runtime.getRuntime().exec(cmd)); } /** * Create a new ExecOutputStream on the given OutputStream * using the process to filter the stream. * @param os Writes to this OutputStream * @param cmd Creates a Process from this string to filter data through stdin/out * @param env Setup the environment for the command */ public ExecOutputStream(OutputStream os, String cmd, String[] env) throws IOException { this(os, Runtime.getRuntime().exec(cmd, env)); } /** * Create a new ExecOutputStream on the given OutputStream * using the process to filter the stream. * @param os Writes to this OutputStream * @param cmd Creates a Process from this string array (command, arg, ...) to filter data through stdin/out * @param env Setup the environment for the command */ public ExecOutputStream(OutputStream os, String[] cmd, String[] env) throws IOException { this(os, Runtime.getRuntime().exec(cmd, env)); } public void close() throws IOException { stdin.close(); try { proc.waitFor(); } catch (InterruptedException Ie) {} //copy.close(); try { copy.join(); } catch (InterruptedException Ie) {} stdout.close(); out.close(); } public void flush() throws IOException { stdin.flush(); copy.flush(); out.flush(); } public void write(byte[] b) throws IOException { stdin.write(b); } public void write(byte[] b, int off, int len) throws IOException { stdin.write(b, off, len); } public void write(int b) throws IOException { stdin.write(b); } public void finalize() { try { close(); } catch (Exception e) {} } } libmatthew-java-0.8.1/cx/ath/matthew/io/test.java0000644000175000017500000000401213273414417020342 0ustar mjj29mjj29/* * Java IO Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.PrintWriter; import java.io.OutputStreamWriter; class test { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new OutputStreamWriter(new ExecOutputStream(System.out, "xsltproc mcr.xsl -")));///java cx.ath.matthew.io.findeof"))); out.println(""); out.println(" "); out.println(" "); out.println(" TEST"); out.println(" "); out.println("hello, he is helping tie up helen's lemmings"); out.println("we are being followed and we break out"); out.println(" "); out.println(" "); out.close(); } } libmatthew-java-0.8.1/cx/ath/matthew/io/DOMPrinter.java0000644000175000017500000000715413273414417021360 0ustar mjj29mjj29/* * Java DOM Printing Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.io; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Print a DOM tree to the given OutputStream */ public class DOMPrinter { /** * Print the given node and all its children. * @param n The Node to print. * @param os The Stream to print to. */ public static void printNode(Node n, OutputStream os) { PrintStream p = new PrintStream(os); printNode(n, p); } /** * Print the given node and all its children. * @param n The Node to print. * @param p The Stream to print to. */ public static void printNode(Node n, PrintStream p) { if (null != n.getNodeValue()) p.print(n.getNodeValue()); else { p.print("<"+n.getNodeName()); if (n.hasAttributes()) { NamedNodeMap nnm = n.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node attr = nnm.item(i); p.print(" "+attr.getNodeName()+"='"+attr.getNodeValue()+"'"); } } if (n.hasChildNodes()) { p.print(">"); NodeList nl = n.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) printNode(nl.item(i), p); p.print(""); } else { p.print("/>"); } } } /** * Print the given document and all its children. * @param d The Document to print. * @param p The Stream to print to. */ public static void printDOM(Document d, PrintStream p) { DocumentType dt = d.getDoctype(); if (null != dt) { p.print(""); } Element e = d.getDocumentElement(); printNode(e, p); } /** * Print the given document and all its children. * @param d The Document to print. * @param os The Stream to print to. */ public static void printDOM(Document d, OutputStream os) { PrintStream p = new PrintStream(os); printDOM(d, p); } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/0000755000175000017500000000000013273414417016656 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/cgi/TextArea.java0000644000175000017500000000350113273414417021235 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class TextArea extends Field { String defval; int cols; int rows; public TextArea(String name, String label, String defval) { this(name, label, defval, 30, 4); } public TextArea(String name, String label, String defval, int cols, int rows) { this.name = name; this.label = label; if (null == defval) this.defval = ""; else this.defval = defval; this.cols = cols; this.rows = rows; } protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/NewTable.java0000644000175000017500000000274513273414417021232 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class NewTable extends Field { private String name; private String cssClass; public NewTable (String name, String css) { this.name = name; this.cssClass = css; } protected String print() { return "\n"; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/CGIInvalidContentFormatException.java0000644000175000017500000000271513273414417026022 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; /** * Thrown if both raw and text data are set in the same page. */ public class CGIInvalidContentFormatException extends Exception { public CGIInvalidContentFormatException() { super("Cannot send both raw and text data"); } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/TextField.java0000644000175000017500000000415113273414417021412 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class TextField extends Field { String defval; int length; public TextField(String name, String label) { this.name = name; this.label = label; this.defval = ""; this.length = 0; } public TextField(String name, String label, String defval) { this.name = name; this.label = label; if (null == defval) this.defval = ""; else this.defval = defval; this.length = 0; } public TextField(String name, String label, String defval, int length) { this.name = name; this.label = label; if (null == defval) this.defval = ""; else this.defval = defval; this.length = length; } protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/CGI.java0000644000175000017500000004501613273414417020131 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.Vector; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * This is the main class you have to extend with your CGI program. * You should implement the cgi() method. * * @author Matthew Johnson <src@matthew.ath.cx> */ abstract public class CGI { private CGIErrorHandler errorhandler = new DefaultErrorHandler(); private boolean headers_sent = false; private HashMap headers = new HashMap(); private Vector cookies = new Vector(); private LinkedList pagedata = new LinkedList(); private LinkedList rawdata = new LinkedList(); private native String getenv(String var); /** MUST pass String.class and ALWAYS returns a String[] */ private native Object[] getfullenv(Class c); private native void setenv(String var, String value); { System.loadLibrary("cgi-java"); } /** * Called by CGIs to send a header to the output * * @param variable The header variable to set. * @param value The value of the variable. * * @throws CGIHeaderSentException if the headers have already been sent. * * @see #flush */ public final void header(String variable, String value) throws CGIHeaderSentException { // only send headers once if (headers_sent) throw new CGIHeaderSentException(); // buffer the variable (Map so that each header is only set once) headers.put(variable.toLowerCase(), value); } /** * Sets a Cookie in the web browser, with extended attributes. * Calls header() so must be called before sending any output. * * A parameter will not be sent if it is null. * * @param variable The cookie variable to set. * @param value The value of the variable. * @param path The path that the cookie will be returned for. * @param domain The domain that the cookie will be returned for. * @param expires The expiry date of the cookie. * @param secure Will only send the cookie over HTTPS if this is true. * * @throws CGIHeaderSentException if the headers have already been sent. * * @see #flush * @see #header */ public final void setcookie(String variable, String value, String path, String domain, Date expires, boolean secure) throws CGIHeaderSentException { if (headers_sent) throw new CGIHeaderSentException(); //Set-Cookie: NAME=VALUE; expires=DATE; //path=PATH; domain=DOMAIN_NAME; secure //Wdy, DD-Mon-YYYY HH:MM:SS GMT DateFormat df = new SimpleDateFormat("E, dd-MMM-yyyy HH:mm:ss zzz"); String cookie = variable+"="+value; if (null != path) cookie += "; path="+path; if (null != domain) cookie += "; domain="+domain; if (null != expires) cookie += "; expires="+df.format(expires); if (secure) cookie += "; secure"; cookies.add("Set-Cookie: "+ cookie); } /** * Sets a Cookie in the web browser. * Calls header() so must be called before sending any output. * * @param variable The cookie variable to set. * @param value The value of the variable. * * @throws CGIHeaderSentException if the headers have already been sent. * * @see #flush * @see #header */ public final void setcookie(String variable, String value) throws CGIHeaderSentException { if (headers_sent) throw new CGIHeaderSentException(); //Set-Cookie: NAME=VALUE; expires=DATE; //path=PATH; domain=DOMAIN_NAME; secure cookies.add("Set-Cookie: "+ variable+"="+value); } /** * Called by CGIs to send byte data to the output. * The data is buffered until the CGI exits, or a call of flush. * * @param data The page data. * @throws CGIInvalidContentFormatException if text data has already been sent. * * @see #flush */ public final void out(byte[] data) throws CGIInvalidContentFormatException { if (pagedata.size() > 0) throw new CGIInvalidContentFormatException(); rawdata.add(data); } /** * Called by CGIs to send a string to the output. * The data is buffered until the CGI exits, or a call of flush. * * @param data The page data. * @throws CGIInvalidContentFormatException if raw data has already been sent. * * @see #flush */ public final void out(String data) throws CGIInvalidContentFormatException { if (rawdata.size() > 0) throw new CGIInvalidContentFormatException(); pagedata.add(data); } /** * This will return an OutputStream that you can write data * directly to. Calling this method will cause the output to be * flushed and the Headers sent. At the moment this is not buffered * and will be sent directly to the client. Subsequent calls * to out() will appear after data written to the output stream. * * @see #out * @return an OutputStream */ public final OutputStream getOutputStream() throws IOException { flush(); return System.out; } /** * Flushes the output. * Note that you cannot send a header after a flush. * If you want to send both text and binary data in a page * you may do so either side of a flush. * * @see #header */ public final void flush() throws IOException { if (!headers_sent) { // don't send headers again headers_sent = true; // send headers Iterator i = headers.keySet().iterator(); while (i.hasNext()) { String key = (String) i.next(); String value = (String) headers.get(key); System.out.println(key + ": " + value); } // send cookies i = cookies.iterator(); while (i.hasNext()) { System.out.println((String) i.next()); } System.out.println(); } // send data if (pagedata.size() >0) { Iterator j = pagedata.iterator(); while (j.hasNext()) { System.out.println((String) j.next()); } pagedata.clear(); } else if (rawdata.size() > 0) { Iterator j = rawdata.iterator(); while (j.hasNext()) { System.out.write((byte[]) j.next()); } pagedata.clear(); } System.out.flush(); } /** * Sets a custom exception handler. * Gets called when an exception is thrown. * The default error handler prints the error nicely in HTML * and then exits gracefully. * * @param handler The new exception handler */ protected final void setErrorHandler(CGIErrorHandler handler) { errorhandler = handler; } /** * Override this method in your CGI program. * * @param POST A Map of variable =$gt; value for the POST variables. * @param GET A Map of variable =$gt; value for the GET variables. * @param ENV A Map of variable =$gt; value for the Webserver environment variables. * @param COOKIES A Map of variable =$gt; value for the browser-sent cookies. * @param params An array of parameters passed to the CGI (GET with no variable assignments) * * @throws Exception You can throw anything, it will be caught by the error handler. */ abstract protected void cgi(Map POST, Map GET, Map ENV, Map COOKIES, String[] params) throws Exception; /** * Reads variables from a String like a=b&c=d to a Map {a => b, c => d}. * * @param s String to read from. * @param seperator seperator character between variables (eg &) * @param values whether or not this string has values for variables * * @return a Map with values, a Vector without */ private Object readVariables(String s, char seperator, boolean values) { HashMap vars = new HashMap(); Vector varv = new Vector(); String temp = ""; String variable = null; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == seperator) { // new variable if (null != temp) temp = temp.trim(); if (values) { if (variable == null) {variable = temp; temp = "";} else variable.trim(); if (!variable.equals("")) { Object o = vars.get(variable); if (o == null) vars.put(variable.trim(), temp); else if (o instanceof String) { LinkedList l = new LinkedList(); l.add(o); l.add(temp); vars.put(variable.trim(), l); } else if (o instanceof LinkedList) ((LinkedList) o).add(temp); } temp = ""; } else { varv.add(temp); temp = ""; } variable = null; continue; } if (values && c == '=') { variable = temp; temp = ""; continue; } switch (c) { case '%': // escaped character try { char a = s.charAt(++i); char b = s.charAt(++i); int ch = 0; switch (a) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ch += 0x10 * (a - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': ch += 0x10 * (a - 'a' + 0xa); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': ch += 0x10 * (a - 'A' + 0xA); break; } switch (b) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ch += (b - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': ch += (b - 'a' + 0xa); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': ch += (b - 'A' + 0xA); break; } temp += (char) ch; } catch (StringIndexOutOfBoundsException SIOOBe) { // this means someone has included an invalid escape sequence. // Invalid URIs can just be thrown on the floor. } break; // + is a space case '+': temp += ' '; break; default: temp += c; } } if (values) { if (variable == null) {variable = temp; temp = "";} else variable.trim(); //out("DEBUG variable read: "+variable+"/"+temp); if (!variable.equals("")) { Object o = vars.get(variable); if (o == null) vars.put(variable.trim(), temp); else if (o instanceof String) { LinkedList l = new LinkedList(); l.add(o); l.add(temp); vars.put(variable.trim(), l); } else if (o instanceof LinkedList) ((LinkedList) o).add(temp); } return vars; } else { varv.add(temp); return varv; } } /** * Sets up the POST variables */ private Map getPOST() { try { String s = ""; while(System.in.available() > 0) s += (char) System.in.read(); //out("DEBUG: POST STRING: "+s); return (Map) readVariables(s, '&', true); } catch (IOException IOe) { try { out("ERROR: IOException: "+IOe); } catch (CGIInvalidContentFormatException CGIICFe) { System.err.println("ERROR: IOException: "+IOe); } return new HashMap(); } } /** * Sets up the COOKIEs */ private Map getCOOKIE() { String s = getenv("HTTP_COOKIE"); if (null == s) return new HashMap(); else return (Map) readVariables(s, ';', true); } /** * Sets up the GET variables */ private Map getGET() { String s = getenv("QUERY_STRING"); if (null == s) return new HashMap(); else return (Map) readVariables(s, '&', true); } /** * Sets up the ENV variables */ private Map getENV() { Map m = new HashMap(); String[] env = (String[]) getfullenv(String.class); for (int i = 0; i < env.length; i++){ if (null == env[i]) continue; String[] e = env[i].split("="); if (1 == e.length) m.put(e[0], ""); else m.put(e[0], e[1]); } /* m.put("SERVER_SOFTWARE", getenv("SERVER_SOFTWARE")); m.put("SERVER_NAME", getenv("SERVER_NAME")); m.put("GATEWAY_INTERFACE", getenv("GATEWAY_INTERFACE")); m.put("SERVER_PROTOCOL", getenv("SERVER_PROTOCOL")); m.put("SERVER_PORT", getenv("SERVER_PORT")); m.put("REQUEST_METHOD", getenv("REQUEST_METHOD")); m.put("PATH_INFO", getenv("PATH_INFO")); m.put("PATH_TRANSLATED", getenv("PATH_TRANSLATED")); m.put("SCRIPT_NAME", getenv("SCRIPT_NAME")); m.put("QUERY_STRING", getenv("QUERY_STRING")); m.put("REMOTE_HOST", getenv("REMOTE_HOST")); m.put("REMOTE_ADDR", getenv("REMOTE_ADDR")); m.put("AUTH_TYPE", getenv("AUTH_TYPE")); m.put("REMOTE_USER", getenv("REMOTE_USER")); m.put("REMOTE_IDENT", getenv("REMOTE_IDENT")); m.put("CONTENT_TYPE", getenv("CONTENT_TYPE")); m.put("CONTENT_LENGTH", getenv("CONTENT_LENGTH")); m.put("HTTP_ACCEPT", getenv("HTTP_ACCEPT")); m.put("HTTP_USER_AGENT", getenv("HTTP_USER_AGENT")); m.put("HTTP_COOKIE", getenv("HTTP_COOKIE")); m.put("HTTP_ACCEPT_CHARSET", getenv("HTTP_ACCEPT_CHARSET")); m.put("HTTP_ACCEPT_ENCODING", getenv("HTTP_ACCEPT_ENCODING")); m.put("HTTP_CACHE_CONTROL", getenv("HTTP_CACHE_CONTROL")); m.put("HTTP_REFERER", getenv("HTTP_REFERER")); m.put("HTTP_X_FORWARDED_FOR", getenv("HTTP_X_FORWARDED_FOR")); m.put("HTTP_HOST", getenv("HTTP_HOST")); m.put("REQUEST_URI", getenv("REQUEST_URI")); m.put("DOCUMENT_ROOT", getenv("DOCUMENT_ROOT")); m.put("PATH", getenv("PATH")); m.put("SERVER_ADDR", getenv("SERVER_ADDR")); m.put("SCRIPT_FILENAME", getenv("SCRIPT_FILENAME")); m.put("HTTP_COOKIE2", getenv("HTTP_COOKIE2")); m.put("HTTP_CONNECTION", getenv("HTTP_CONNECTION")); m.put("LANG", getenv("LANG")); m.put("REDIRECT_LANG", getenv("REDIRECT_LANG")); */ return m; } /** * Sets up the param variables */ private String[] getParams(String args) { Vector v = (Vector) readVariables(args, ',', false); String[] params = new String[v.size()]; Iterator i = v.iterator(); for (int j = 0; j < params.length; j++) params[j] = (String) i.next(); return params; } /** * This method sets up all the CGI variables and calls the cgi() method, then writes out the page data. */ public final void doCGI(String[] args) { CGI cgiclass = null; // wrap everything in a try, we need to handle all our own errors. try { // setup the CGI variables Map POST = getPOST(); Map GET = getGET(); Map ENV = getENV(); Map COOKIE = getCOOKIE(); String[] params = new String[] {}; if (args.length >= 1) params = getParams(args[0]); // instantiate CGI class /* Class c = Class.forName(args[0]); cgiclass = (CGI) c.newInstance(); */ // set default headers /*cgiclass.*/header("Content-type", "text/html"); // execute the CGI /*cgiclass.*/cgi(POST, GET, ENV, COOKIE, params); // send the output / remaining output /*cgiclass.*/flush(); } // yes, we really want to do this. CGI programs can't send errors. Print nicely to the screen. catch (Exception e) { errorhandler.print(/*null == cgiclass ? false : cgiclass.*/headers_sent, e); } catch (Throwable t) { t.printStackTrace(); // this is bad enough to produce stderr errors errorhandler.print(/*null == cgiclass ? false : cgiclass.*/headers_sent, new Exception(t.toString())); } } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/Password.java0000644000175000017500000000307113273414417021324 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class Password extends Field { String defval; public Password(String name, String label, String defval) { this.name = name; this.label = label; this.defval = defval; } protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/MultipleDropDown.java0000644000175000017500000000636113273414417022777 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ /* * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package cx.ath.matthew.cgi; import java.util.List; /** * @author Agent * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class MultipleDropDown extends DropDown { /** * @param name * @param label * @param values * @param defval * @param indexed */ public MultipleDropDown(String name, String label, String[] values, String defval, boolean indexed) { super(name, label, values, defval, indexed); // TODO Auto-generated constructor stub } /** * @param name * @param label * @param values * @param defval * @param indexed */ public MultipleDropDown(String name, String label, String[] values, int defval, boolean indexed) { super(name, label, values, defval, indexed); // TODO Auto-generated constructor stub } /** * @param name * @param label * @param values * @param defval * @param indexed */ public MultipleDropDown(String name, String label, List values, String defval, boolean indexed) { super(name, label, values, defval, indexed); // TODO Auto-generated constructor stub } /** * @param name * @param label * @param values * @param defval * @param indexed */ public MultipleDropDown(String name, String label, List values, int defval, boolean indexed) { super(name, label, values, defval, indexed); // TODO Auto-generated constructor stub } protected String print() { String s = ""; s += "\n"; return s; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/HTMLForm.java0000644000175000017500000001017513273414417021115 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; import java.util.Iterator; import java.util.Vector; /** * Class to manage drawing HTML forms */ public class HTMLForm { private String target; private String submitlabel; private String tableclass; private Vector fields; private boolean post = true; /** * @param target The module to submit to */ public HTMLForm(String target) { this(target, "Submit", null); } /** * @param target The module to submit to * @param submitlabel The string to display on the submit button */ public HTMLForm(String target, String submitlabel) { this(target, submitlabel, null); } /** * @param target The module to submit to * @param submitlabel The string to display on the submit button * @param tableclass The class= parameter for the generated table */ public HTMLForm(String target, String submitlabel, String tableclass) { this.target = target; this.submitlabel = submitlabel; this.tableclass = tableclass; fields = new Vector(); } /** * Add a field to be displayed in the form. * * @param field A Field subclass. */ public void addField(Field field) { fields.add(field); } /** * Set GET method rather than POST * @param enable Enable/Disable GET */ public void setGET(boolean enable) { post = !enable; } /** * Shows the form. * @param cgi The CGI instance that is handling output */ public void display(CGI cgi) { try { cgi.out(""); if (null == tableclass) cgi.out("
"); else cgi.out("
"); Iterator i = fields.iterator(); while (i.hasNext()) { Field f = (Field) i.next(); if (f instanceof NewTable) { cgi.out(f.print()); } if (!(f instanceof HiddenField) && !(f instanceof SubmitButton) && !(f instanceof NewTable)) { cgi.out(" "); cgi.out(" "); cgi.out(" "); cgi.out(" "); } } cgi.out(" "); cgi.out(" "); cgi.out(" "); cgi.out("
"+f.label+""+f.print()+"
"); i = fields.iterator(); while (i.hasNext()) { Field f = (Field) i.next(); if (f instanceof HiddenField || f instanceof SubmitButton) { cgi.out(" "+f.print()); } } cgi.out(" "); cgi.out("
"); cgi.out(""); } catch (CGIInvalidContentFormatException CGIICFe) {} } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/HiddenField.java0000644000175000017500000000305413273414417021662 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class HiddenField extends Field { String value; public HiddenField(String name, String value) { this.name = name; this.label = ""; this.value = value; } protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/CGIHeaderSentException.java0000644000175000017500000000267613273414417023760 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; /** * Thrown if the headers have already been sent and CGI.header is called. */ public class CGIHeaderSentException extends Exception { public CGIHeaderSentException() { super("Headers already sent by CGI"); } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/CGIErrorHandler.java0000644000175000017500000000304013273414417022430 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; /** * Interface to handle exceptions in the CGI. */ public interface CGIErrorHandler { /** * This is called if an exception is not caught in the CGI. * It should handle printing the error message nicely to the user, * and then exit gracefully. */ public void print(boolean headers_sent, Exception e); } libmatthew-java-0.8.1/cx/ath/matthew/cgi/CGITools.java0000644000175000017500000000320613273414417021145 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; abstract class CGITools { /** * Escape a character in a string. * @param in String to escape in. * @param c Character to escape. * @return in with c replaced with \c */ public static String escapeChar(String in, char c) { String out = ""; for (int i = 0; i < in.length(); i++) { if (in.charAt(i) == c) out += '\\'; out += in.charAt(i); } return out; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/DefaultErrorHandler.java0000644000175000017500000000477213273414417023427 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; /** * Interface to handle exceptions in the CGI. */ public class DefaultErrorHandler implements CGIErrorHandler { /** * This is called if an exception is not caught in the CGI. * It should handle printing the error message nicely to the user, * and then exit gracefully. */ public void print(boolean headers_sent, Exception e) { if (!headers_sent) { System.out.println("Content-type: text/html"); System.out.println(""); System.out.println(""); System.out.println(""); System.out.println("Exception in CGI"); System.out.println(""); } System.out.println("
"); System.out.println("

"+e.getClass().toString()+"

"); System.out.println("

"); System.out.println("Exception Message: "+e.getMessage()); System.out.println("

"); System.out.println("

"); System.out.println("Stack Trace:"); System.out.println("

"); System.out.println("
");
      e.printStackTrace(System.out);
      System.out.println("
"); System.out.println("
"); if (!headers_sent) { System.out.println(""); } System.exit(1); } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/DropDown.java0000644000175000017500000001064513273414417021263 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; import java.util.List; public class DropDown extends Field { Object[] values; Object defval; boolean indexed = false; /** * Create a new DropDown list. * * @param name The HTML field name. * @param label The label to display * @param values The values for the drop down list * @param defval If this parameter is set then this element will be selected by default. * @param indexed If this is set to true, then indexes will be returned, rather than values. */ public DropDown(String name, String label, Object[] values, Object defval, boolean indexed) { this.name = name; this.label = label; this.values = values; this.indexed = indexed; this.defval = defval; } /** * Create a new DropDown list. * * @param name The HTML field name. * @param label The label to display * @param values The values for the drop down list * @param defval If this parameter is set then this element will be selected by default. * @param indexed If this is set to true, then indexes will be returned, rather than values. */ public DropDown(String name, String label, Object[] values, int defval, boolean indexed) { this.name = name; this.label = label; this.values = values; if (defval < 0) this.defval = null; else this.defval = values[defval]; this.indexed = indexed; } /** * Create a new DropDown list. * * @param name The HTML field name. * @param label The label to display * @param values The values for the drop down list * @param defval If this parameter is set then this element will be selected by default. * @param indexed If this is set to true, then indexes will be returned, rather than values. */ public DropDown(String name, String label, List values, Object defval, boolean indexed) { this.name = name; this.label = label; this.values = (Object[]) values.toArray(new Object[] {}); this.defval = defval; this.indexed = indexed; } /** * Create a new DropDown list. * * @param name The HTML field name. * @param label The label to display * @param values The values for the drop down list * @param defval If this parameter is set then this element will be selected by default. * @param indexed If this is set to true, then indexes will be returned, rather than values. */ public DropDown(String name, String label, List values, int defval, boolean indexed) { this.name = name; this.label = label; this.values = (Object[]) values.toArray(new Object[] {}); if (defval < 0) this.defval = null; else this.defval = values.get(defval); this.indexed = indexed; } protected String print() { String s = ""; s += "\n"; return s; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/Field.java0000644000175000017500000000252713273414417020552 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public abstract class Field { protected String name; protected String label; protected abstract String print(); } libmatthew-java-0.8.1/cx/ath/matthew/cgi/CheckBox.java0000644000175000017500000000306613273414417021214 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class CheckBox extends Field { boolean checked; public CheckBox(String name, String label, boolean checked) { this.name = name; this.label = label; this.checked = checked; } protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/DisplayField.java0000644000175000017500000000273213273414417022076 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class DisplayField extends Field { String value; public DisplayField(String label, String value) { this.name = ""; this.label = label; this.value = value; } protected String print() { return value; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/SubmitButton.java0000644000175000017500000000351013273414417022157 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ /* * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package cx.ath.matthew.cgi; /** * @author Agent * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class SubmitButton extends Field { public SubmitButton(String name, String label) { this.name = name; this.label = label; } /* (non-Javadoc) * @see cx.ath.matthew.cgi.Field#print() */ protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/Radio.java0000644000175000017500000000305513273414417020562 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; public class Radio extends Field { boolean checked; public Radio(String name, String label, boolean checked) { this.name = name; this.label = label; this.checked = checked; } protected String print() { return ""; } } libmatthew-java-0.8.1/cx/ath/matthew/cgi/testcgi.java0000644000175000017500000000504313273414417021165 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.cgi; import java.util.Iterator; import java.util.Map; class testcgi extends CGI { protected void cgi(Map POST, Map GET, Map ENV, Map COOKIE, String[] params) throws Exception { header("Content-type", "text/plain"); setcookie("testcgi", "You have visited us already"); out("This is a test CGI program"); out("These are the params:"); for (int i=0; i < params.length; i++) out("-- "+params[i]); out("These are the POST vars:"); Iterator i = POST.keySet().iterator(); while (i.hasNext()) { String s = (String) i.next(); out("-- "+s+" => "+POST.get(s)); } out("These are the GET vars:"); i = GET.keySet().iterator(); while (i.hasNext()) { String s = (String) i.next(); out("-- "+s+" => "+GET.get(s)); } out("These are the ENV vars:"); i = ENV.keySet().iterator(); while (i.hasNext()) { String s = (String) i.next(); out("-- "+s+" => "+ENV.get(s)); } out("These are the COOKIEs:"); i = COOKIE.keySet().iterator(); while (i.hasNext()) { String s = (String) i.next(); out("-- "+s+" => "+COOKIE.get(s)); } } public static void main(String[] args) { CGI cgi = new testcgi(); cgi.doCGI(args); } } libmatthew-java-0.8.1/cx/ath/matthew/unix/0000755000175000017500000000000013273414417017077 5ustar mjj29mjj29libmatthew-java-0.8.1/cx/ath/matthew/unix/UnixServerSocket.java0000644000175000017500000000733213273414417023232 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.IOException; /** * Represents a listening UNIX Socket. */ public class UnixServerSocket { static { System.loadLibrary("unix-java"); } private native int native_bind(String address, boolean abs) throws IOException; private native void native_close(int sock) throws IOException; private native int native_accept(int sock) throws IOException; private UnixSocketAddress address = null; private boolean bound = false; private boolean closed = false; private int sock; /** * Create an un-bound server socket. */ public UnixServerSocket() { } /** * Create a server socket bound to the given address. * @param address Path to the socket. */ public UnixServerSocket(UnixSocketAddress address) throws IOException { bind(address); } /** * Create a server socket bound to the given address. * @param address Path to the socket. */ public UnixServerSocket(String address) throws IOException { this(new UnixSocketAddress(address)); } /** * Accepts a connection on the ServerSocket. * @return A UnixSocket connected to the accepted connection. */ public UnixSocket accept() throws IOException { int client_sock = native_accept(sock); return new UnixSocket(client_sock, address); } /** * Closes the ServerSocket. */ public synchronized void close() throws IOException { native_close(sock); sock = 0; closed = true; bound = false; } /** * Binds a server socket to the given address. * @param address Path to the socket. */ public void bind(UnixSocketAddress address) throws IOException { if (bound) close(); sock = native_bind(address.path, address.abs); bound = true; closed = false; this.address = address; } /** * Binds a server socket to the given address. * @param address Path to the socket. */ public void bind(String address) throws IOException { bind(new UnixSocketAddress(address)); } /** * Return the address this socket is bound to. * @return The UnixSocketAddress if bound or null if unbound. */ public UnixSocketAddress getAddress() { return address; } /** * Check the status of the socket. * @return True if closed. */ public boolean isClosed() { return closed; } /** * Check the status of the socket. * @return True if bound. */ public boolean isBound() { return bound; } } libmatthew-java-0.8.1/cx/ath/matthew/unix/testserver.java0000644000175000017500000000370213273414417022152 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; public class testserver { public static void main(String args[]) throws IOException { UnixServerSocket ss = new UnixServerSocket(new UnixSocketAddress("testsock", true)); UnixSocket s = ss.accept(); BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream())); String l; while (null != (l = r.readLine())) System.out.println(l);/* InputStream is = s.getInputStream(); int r; do { r = is.read(); System.out.print((char)r); } while (-1 != r);*/ s.close(); ss.close(); } } libmatthew-java-0.8.1/cx/ath/matthew/unix/testclient.java0000644000175000017500000000357013273414417022125 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; public class testclient { public static void main(String args[]) throws IOException { UnixSocket s = new UnixSocket(new UnixSocketAddress("testsock", true)); OutputStream os = s.getOutputStream(); PrintWriter o = new PrintWriter(os); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String l; while (null != (l = r.readLine())) { byte[] buf = (l+"\n").getBytes(); os.write(buf, 0, buf.length); } s.close(); } } libmatthew-java-0.8.1/cx/ath/matthew/unix/NotConnectedException.java0000644000175000017500000000263313273414417024210 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.net.SocketException; public class NotConnectedException extends SocketException { public NotConnectedException() { super("The Socket is Not Connected"); } } libmatthew-java-0.8.1/cx/ath/matthew/unix/java-unix.h0000644000175000017500000000560212536305505021153 0ustar mjj29mjj29/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class cx_ath_matthew_unix_UnixServerSocket */ #ifndef _Included_cx_ath_matthew_unix_UnixServerSocket #define _Included_cx_ath_matthew_unix_UnixServerSocket #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_bind * Signature: (Ljava/lang/String;Z)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1bind (JNIEnv *, jobject, jstring, jboolean); /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_close * Signature: (I)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1close (JNIEnv *, jobject, jint); /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_accept * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1accept (JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif /* Header for class cx_ath_matthew_unix_UnixSocket */ #ifndef _Included_cx_ath_matthew_unix_UnixSocket #define _Included_cx_ath_matthew_unix_UnixSocket #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_set_pass_cred * Signature: (IZ)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1set_1pass_1cred (JNIEnv *, jobject, jint, jboolean); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_connect * Signature: (Ljava/lang/String;Z)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1connect (JNIEnv *, jobject, jstring, jboolean); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_close * Signature: (I)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1close (JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif /* Header for class cx_ath_matthew_unix_USInputStream */ #ifndef _Included_cx_ath_matthew_unix_USInputStream #define _Included_cx_ath_matthew_unix_USInputStream #ifdef __cplusplus extern "C" { #endif #undef cx_ath_matthew_unix_USInputStream_SKIP_BUFFER_SIZE #define cx_ath_matthew_unix_USInputStream_SKIP_BUFFER_SIZE 2048L /* * Class: cx_ath_matthew_unix_USInputStream * Method: native_recv * Signature: (I[BII)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USInputStream_native_1recv (JNIEnv *, jobject, jint, jbyteArray, jint, jint); #ifdef __cplusplus } #endif #endif /* Header for class cx_ath_matthew_unix_USOutputStream */ #ifndef _Included_cx_ath_matthew_unix_USOutputStream #define _Included_cx_ath_matthew_unix_USOutputStream #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_unix_USOutputStream * Method: native_send * Signature: (I[BII)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USOutputStream_native_1send (JNIEnv *, jobject, jint, jbyteArray, jint, jint); #ifdef __cplusplus } #endif #endif libmatthew-java-0.8.1/cx/ath/matthew/unix/USOutputStream.java0000644000175000017500000000465013273414417022673 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.IOException; import java.io.OutputStream; public class USOutputStream extends OutputStream { private native int native_send(int sock, byte[] b, int off, int len) throws IOException; private native int native_send(int sock, byte[][] b) throws IOException; private int sock; boolean closed = false; private byte[] onebuf = new byte[1]; private UnixSocket us; public USOutputStream(int sock, UnixSocket us) { this.sock = sock; this.us = us; } public void close() throws IOException { closed = true; us.close(); } public void flush() {} // no-op, we do not buffer public void write(byte[][] b) throws IOException { if (closed) throw new NotConnectedException(); native_send(sock, b); } public void write(byte[] b, int off, int len) throws IOException { if (closed) throw new NotConnectedException(); native_send(sock, b, off, len); } public void write(int b) throws IOException { onebuf[0] = (byte) (b % 0x7F); if (1 == (b % 0x80)) onebuf[0] = (byte) -onebuf[0]; write(onebuf); } public boolean isClosed() { return closed; } public UnixSocket getSocket() { return us; } } libmatthew-java-0.8.1/cx/ath/matthew/unix/UnixSocket.java0000644000175000017500000002150213273414417022036 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import cx.ath.matthew.debug.Debug; /** * Represents a UnixSocket. */ public class UnixSocket { static { System.loadLibrary("unix-java"); } private native void native_set_pass_cred(int sock, boolean passcred) throws IOException; private native int native_connect(String address, boolean abs) throws IOException; private native void native_close(int sock) throws IOException; private native int native_getPID(int sock); private native int native_getUID(int sock); private native int native_getGID(int sock); private native void native_send_creds(int sock, byte data) throws IOException; private native byte native_recv_creds(int sock, int[] creds) throws IOException; private UnixSocketAddress address = null; private USOutputStream os = null; private USInputStream is = null; private boolean closed = false; private boolean connected = false; private boolean passcred = false; private int sock = 0; private boolean blocking = true; private int uid = -1; private int pid = -1; private int gid = -1; UnixSocket(int sock, UnixSocketAddress address) { this.sock = sock; this.address = address; this.connected = true; this.os = new USOutputStream(sock, this); this.is = new USInputStream(sock, this); } /** * Create an unconnected socket. */ public UnixSocket() { } /** * Create a socket connected to the given address. * @param address The Unix Socket address to connect to */ public UnixSocket(UnixSocketAddress address) throws IOException { connect(address); } /** * Create a socket connected to the given address. * @param address The Unix Socket address to connect to */ public UnixSocket(String address) throws IOException { this(new UnixSocketAddress(address)); } /** * Connect the socket to this address. * @param address The Unix Socket address to connect to */ public void connect(UnixSocketAddress address) throws IOException { if (connected) close(); this.sock = native_connect(address.path, address.abs); this.os = new USOutputStream(this.sock, this); this.is = new USInputStream(this.sock, this); this.address = address; this.connected = true; this.closed = false; this.is.setBlocking(blocking); } /** * Connect the socket to this address. * @param address The Unix Socket address to connect to */ public void connect(String address) throws IOException { connect(new UnixSocketAddress(address)); } public void finalize() { try { close(); } catch (IOException IOe) {} } /** * Closes the connection. */ public synchronized void close() throws IOException { if (Debug.debug) Debug.print(Debug.INFO, "Closing socket"); native_close(sock); sock = 0; this.closed = true; this.connected = false; os = null; is = null; } /** * Returns an InputStream for reading from the socket. * @return An InputStream connected to this socket. */ public InputStream getInputStream() { return is; } /** * Returns an OutputStream for writing to the socket. * @return An OutputStream connected to this socket. */ public OutputStream getOutputStream() { return os; } /** * Returns the address this socket is connected to. * Returns null if the socket is unconnected. * @return The UnixSocketAddress the socket is connected to */ public UnixSocketAddress getAddress() { return address; } /** * Send a single byte of data with credentials. * (Works on BSDs) * @param data The byte of data to send. */ public void sendCredentialByte(byte data) throws IOException { if (!connected) throw new NotConnectedException(); native_send_creds(sock, data); } /** * Receive a single byte of data, with credentials. * (Works on BSDs) * @see getPeerUID * @see getPeerPID * @see getPeerGID * @param data The byte of data to send. */ public byte recvCredentialByte() throws IOException { if (!connected) throw new NotConnectedException(); int[] creds = new int[] { -1, -1, -1 }; byte data = native_recv_creds(sock, creds); pid = creds[0]; uid = creds[1]; gid = creds[2]; return data; } /** * Get the credential passing status. * (only effective on linux) * @return The current status of credential passing. * @see setPassCred */ public boolean getPassCred() { return passcred; } /** * Return the uid of the remote process. * Some data must have been received on the socket to do this. * Either setPassCred must be called on Linux first, or recvCredentialByte * on BSD. * @return the UID or -1 if it is not available */ public int getPeerUID() { if (-1 == uid) uid = native_getUID(sock); return uid; } /** * Return the gid of the remote process. * Some data must have been received on the socket to do this. * Either setPassCred must be called on Linux first, or recvCredentialByte * on BSD. * @return the GID or -1 if it is not available */ public int getPeerGID() { if (-1 == gid) gid = native_getGID(sock); return gid; } /** * Return the pid of the remote process. * Some data must have been received on the socket to do this. * Either setPassCred must be called on Linux first, or recvCredentialByte * on BSD. * @return the PID or -1 if it is not available */ public int getPeerPID() { if (-1 == pid) pid = native_getPID(sock); return pid; } /** * Set the credential passing status. * (Only does anything on linux, for other OS, you need * to use send/recv credentials) * @param enable Set to true for credentials to be passed. */ public void setPassCred(boolean enable) throws IOException { native_set_pass_cred(sock, enable); passcred = enable; } /** * Get the blocking mode. * @return true if reads are blocking. * @see setBlocking */ public boolean getBlocking() { return blocking; } /** * Set the blocking mode. * @param enable Set to false for non-blocking reads. */ public void setBlocking(boolean enable) { blocking = enable; if (null != is) is.setBlocking(enable); } /** * Check the socket status. * @return true if closed. */ public boolean isClosed() { return closed; } /** * Check the socket status. * @return true if connected. */ public boolean isConnected() { return connected; } /** * Check the socket status. * @return true if the input stream has been shutdown */ public boolean isInputShutdown() { return is.isClosed(); } /** * Check the socket status. * @return true if the output stream has been shutdown */ public boolean isOutputShutdown() { return os.isClosed(); } /** * Shuts down the input stream. * Subsequent reads on the associated InputStream will fail. */ public void shutdownInput() { is.closed = true; } /** * Shuts down the output stream. * Subsequent writes to the associated OutputStream will fail. */ public void shutdownOutput() { os.closed = true; } /** * Set timeout of read requests. */ public void setSoTimeout(int timeout) { is.setSoTimeout(timeout); } } libmatthew-java-0.8.1/cx/ath/matthew/unix/UnixIOException.java0000644000175000017500000000304613273414417022777 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.IOException; /** * An IO Exception which occurred during UNIX Socket IO */ public class UnixIOException extends IOException { private int no; private String message; public UnixIOException(int no, String message) { super(message); this.message = message; this.no = no; } } libmatthew-java-0.8.1/cx/ath/matthew/unix/USInputStream.java0000644000175000017500000000575413273414417022500 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; import java.io.InputStream; import java.io.IOException; public class USInputStream extends InputStream { public static final int MSG_DONTWAIT = 0x40; private native int native_recv(int sock, byte[] b, int off, int len, int flags, int timeout) throws IOException; private int sock; boolean closed = false; private byte[] onebuf = new byte[1]; private UnixSocket us; private boolean blocking = true; private int flags = 0; private int timeout = 0; public USInputStream(int sock, UnixSocket us) { this.sock = sock; this.us = us; } public void close() throws IOException { closed = true; us.close(); } public boolean markSupported() { return false; } public int read() throws IOException { int rv = 0; while (0 >= rv) rv = read(onebuf); if (-1 == rv) return -1; return 0 > onebuf[0] ? -onebuf[0] : onebuf[0]; } public int read(byte[] b, int off, int len) throws IOException { if (closed) throw new NotConnectedException(); int count = native_recv(sock, b, off, len, flags, timeout); /* Yes, I really want to do this. Recv returns 0 for 'connection shut down'. * read() returns -1 for 'end of stream. * Recv returns -1 for 'EAGAIN' (all other errors cause an exception to be raised) * whereas read() returns 0 for '0 bytes read', so yes, I really want to swap them here. */ if (0 == count) return -1; else if (-1 == count) return 0; else return count; } public boolean isClosed() { return closed; } public UnixSocket getSocket() { return us; } public void setBlocking(boolean enable) { flags = enable ? 0 : MSG_DONTWAIT; } public void setSoTimeout(int timeout) { this.timeout = timeout; } } libmatthew-java-0.8.1/cx/ath/matthew/unix/UnixSocketAddress.java0000644000175000017500000000455613273414417023356 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2004 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ package cx.ath.matthew.unix; /** * Represents an address for a Unix Socket */ public class UnixSocketAddress { String path; boolean abs; /** * Create the address. * @param path The path to the Unix Socket. * @param abs True if this should be an abstract socket. */ public UnixSocketAddress(String path, boolean abs) { this.path = path; this.abs = abs; } /** * Create the address. * @param path The path to the Unix Socket. */ public UnixSocketAddress(String path) { this.path = path; this.abs = false; } /** * Return the path. */ public String getPath() { return path; } /** * Returns true if this an address for an abstract socket. */ public boolean isAbstract() { return abs; } /** * Return the Address as a String. */ public String toString() { return "unix"+(abs?":abstract":"")+":path="+path; } public boolean equals(Object o) { if (!(o instanceof UnixSocketAddress)) return false; return ((UnixSocketAddress) o).path.equals(this.path); } public int hashCode() { return path.hashCode(); } } libmatthew-java-0.8.1/Makefile0000644000175000017500000001174013273415355014722 0ustar mjj29mjj29JAVAC?=javac JAVADOC?=javadoc JAR?=jar JAVAH?=javah GCJ?=gcj CC?=gcc LD?=gcc JPPFLAGS+=-C -P CFLAGS+=-Wall -Os -pedantic -Werror CSTD?=-std=c99 CSHAREFLAG+=-fpic -fno-stack-protector GCJJNIFLAG=-fjni JVERCFLAGS+=-source 1.5 JCFLAGS+= INCLUDES+=-I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux JAVADOCFLAGS?=-quiet -author -link http://java.sun.com/j2se/1.4.2/docs/api/ LDVER?=$(shell ld -v | cut -d' ' -f1) UNAME?=$(shell uname -s) ifeq ($(LDVER),GNU) LDSHAREFLAGS+=-fpic -shared else LDSHAREFLAGS+=-lc endif PREFIX?=/usr/local JARDIR?=$(PREFIX)/share/java DOCDIR?=$(PREFIX)/share/doc/libmatthew-java/ LIBDIR?=$(PREFIX)/lib/jni MATTVER=0.8.1 DEBUGVER=1.1 UNIXVER=0.5 CGIVER=0.6 IOVER=0.1 HEXVER=0.2 SRC=$(shell find cx -name '*.java' -and -not -name 'Debug.java') DEBUG?=disable .NOPARALLEL: .NO_PARALLEL: .NOTPARALLEL: all: unix-$(UNIXVER).jar cgi-$(CGIVER).jar debug-enable-$(DEBUGVER).jar debug-disable-$(DEBUGVER).jar io-$(IOVER).jar hexdump-$(HEXVER).jar libcgi-java.so libunix-java.so dist: libmatthew-java-$(MATTVER).tar.gz classes: .classes .classes: $(SRC) mkdir -p classes $(MAKE) .$(DEBUG)debug $(JAVAC) $(JVERCFLAGS) $(JCFLAGS) -d classes -cp classes $^ touch .classes clean: rm -rf classes doc rm -f .classes .enabledebug .disabledebug *.o *.h *.so *.tar.gz *.jar *.cgi Manifest rm -rf libmatthew-java-$(MATTVER) cgi-$(CGIVER).jar: .classes (cd classes; $(JAR) cf ../$@ cx/ath/matthew/cgi/*class) io-$(IOVER).jar: .classes (cd classes; $(JAR) cf ../$@ cx/ath/matthew/io/*class) unix-$(UNIXVER).jar: .classes ifeq ($(DEBUG),enable) echo "Class-Path: $(JARDIR)/debug-$(DEBUG).jar" > Manifest else echo "Class-Path: " > Manifest endif (cd classes; $(JAR) cfm ../$@ ../Manifest cx/ath/matthew/unix/*class) hexdump-$(HEXVER).jar: .classes (cd classes; $(JAR) cf ../$@ cx/ath/matthew/utils/Hexdump.class) %.o: %.c %.h $(CC) $(CFLAGS) $(CSTD) $(CSHAREFLAG) $(INCLUDES) -c -o $@ $< lib%.so: %.o $(CC) $(LDFLAGS) $(LDSHAREFLAGS) -o $@ $< headers: .classes $(JAVAH) -classpath classes -o $@ cx.ath.matthew.unix.UnixServerSocket cx.ath.matthew.unix.UnixSocket cx.ath.matthew.unix.USInputStream cx.ath.matthew.unix.USOutputStream $(JAVAH) -classpath classes -o $@ cx.ath.matthew.cgi.CGI test.cgi: cgi-$(CGIVER).jar libcgi-java.so $(GCJ) $(GCJFLAGS) $(GCJJNIFLAG) -L. -lcgi-java -o test.cgi --main=cx.ath.matthew.cgi.testcgi cgi-$(CGIVER).jar libmatthew-java-$(MATTVER).tar.gz: Makefile cx cgi-java.c unix-java.c README INSTALL COPYING changelog unix-java.h cgi-java.h mkdir -p libmatthew-java-$(MATTVER) cp -a $^ libmatthew-java-$(MATTVER) tar zcf $@ libmatthew-java-$(MATTVER) debug-enable-$(DEBUGVER).jar: cx/ath/matthew/debug/Debug.jpp make .enabledebug echo "Class-Path: $(JARDIR)/hexdump.jar" > Manifest (cd classes;jar cfm ../$@ ../Manifest cx/ath/matthew/debug/*.class) debug-disable-$(DEBUGVER).jar: cx/ath/matthew/debug/Debug.jpp make .disabledebug echo "Class-Path: $(JARDIR)/hexdump.jar" > Manifest (cd classes;jar cfm ../$@ ../Manifest cx/ath/matthew/debug/*.class) .enabledebug: cx/ath/matthew/debug/Debug.jpp mkdir -p classes cpp $(PPFLAGS) $(JPPFLAGS) -DDEBUGSETTING=true < cx/ath/matthew/debug/Debug.jpp > cx/ath/matthew/debug/Debug.java $(JAVAC) $(JVERCFLAGS) $(JCFLAGS) -cp classes -d classes cx/ath/matthew/debug/Debug.java cx/ath/matthew/utils/Hexdump.java rm -f .disabledebug touch .enabledebug .disabledebug: cx/ath/matthew/debug/Debug.jpp mkdir -p classes cpp $(PPFLAGS) $(JPPFLAGS) -DDEBUGSETTING=false < cx/ath/matthew/debug/Debug.jpp > cx/ath/matthew/debug/Debug.java $(JAVAC) $(JVERCFLAGS) $(JCFLAGS) -cp classes -d classes cx/ath/matthew/debug/Debug.java cx/ath/matthew/utils/Hexdump.java rm -f .enabledebug touch .disabledebug cx/ath/matthew/debug/Debug.java: .disabledebug doc/index.html: $(JAVADOC) $(JAVADOCFLAGS) -d doc/ cx/ath/matthew/debug/Debug.java $(SRC) doc: doc/index.html install-doc: doc/index.html install -d $(DESTDIR)$(DOCDIR) cp -a doc $(DESTDIR)$(DOCDIR)/api install-native: libcgi-java.so libunix-java.so install -d $(DESTDIR)$(LIBDIR) install libcgi-java.so $(DESTDIR)$(LIBDIR) install libunix-java.so $(DESTDIR)$(LIBDIR) install-jar: unix-$(UNIXVER).jar cgi-$(CGIVER).jar debug-enable-$(DEBUGVER).jar debug-disable-$(DEBUGVER).jar io-$(IOVER).jar hexdump-$(HEXVER).jar install -d $(DESTDIR)$(JARDIR) install -m 644 debug-enable-$(DEBUGVER).jar $(DESTDIR)$(JARDIR) install -m 644 debug-disable-$(DEBUGVER).jar $(DESTDIR)$(JARDIR) install -m 644 unix-$(UNIXVER).jar $(DESTDIR)$(JARDIR) install -m 644 cgi-$(CGIVER).jar $(DESTDIR)$(JARDIR) install -m 644 io-$(IOVER).jar $(DESTDIR)$(JARDIR) install -m 644 hexdump-$(HEXVER).jar $(DESTDIR)$(JARDIR) ln -sf debug-disable-$(DEBUGVER).jar $(DESTDIR)$(JARDIR)/debug-disable.jar ln -sf debug-enable-$(DEBUGVER).jar $(DESTDIR)$(JARDIR)/debug-enable.jar ln -sf unix-$(UNIXVER).jar $(DESTDIR)$(JARDIR)/unix.jar ln -sf io-$(IOVER).jar $(DESTDIR)$(JARDIR)/io.jar ln -sf cgi-$(CGIVER).jar $(DESTDIR)$(JARDIR)/cgi.jar ln -sf hexdump-$(HEXVER).jar $(DESTDIR)$(JARDIR)/hexdump.jar install: install-native install-jar libmatthew-java-0.8.1/COPYING0000644000175000017500000000216513273414417014314 0ustar mjj29mjj29These Java libraries are Copyright Matthew Johnson 2006-2011 and are licenced under the terms of the Expat license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. libmatthew-java-0.8.1/unix-java.c0000644000175000017500000003145313273414417015331 0ustar mjj29mjj29/* * Java Unix Sockets Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ /* _GNU_SOURCE is required to use struct ucred in glibc 2.8 */ #define _GNU_SOURCE #include "unix-java.h" #include #include #include #include #include #include #include #include #include #include #ifndef IOV_MAX #define IOV_MAX 1024 #endif #ifdef __cplusplus extern "C" { #endif void throw(JNIEnv* env, int err, const char* msg) { jstring jmsg = (*env)->NewStringUTF(env, msg); jclass exc = (*env)->FindClass(env, "cx/ath/matthew/unix/UnixIOException"); jmethodID cons = (*env)->GetMethodID(env, exc, "", "(ILjava/lang/String;)V"); jobject exo = (*env)->NewObject(env, exc, cons, err, jmsg); (*env)->DeleteLocalRef(env, exc); (*env)->DeleteLocalRef(env, jmsg); (*env)->Throw(env, exo); (*env)->DeleteLocalRef(env, exo); } void handleerrno(JNIEnv *env) { if (0 == errno) return; int err = errno; if (EAGAIN == err) return; // we read 0 bytes due to a timeout const char* msg = strerror(err); throw(env, err, msg); } /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_bind * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1bind (JNIEnv *env, jobject o, jstring address, jboolean abstract) { int sock = socket(PF_UNIX, SOCK_STREAM, 0); if (-1 == sock) { handleerrno(env); return -1; } const char* caddr = (*env)->GetStringUTFChars(env, address, 0); int slen = (*env)->GetStringUTFLength(env, address)+1; struct sockaddr_un *sad = malloc(sizeof(sa_family_t)+slen); if (abstract) { char* shifted = sad->sun_path+1; strncpy(shifted, caddr, slen-1); sad->sun_path[0] = 0; } else strncpy(sad->sun_path, caddr, slen); (*env)->ReleaseStringUTFChars(env, address, caddr); sad->sun_family = AF_UNIX; int rv = bind(sock, (const struct sockaddr*) sad, sizeof(sa_family_t)+slen); free(sad); if (-1 == rv) { handleerrno(env); return -1; } rv = listen(sock, 10); if (-1 == rv) { handleerrno(env); return -1; } return sock; } /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_close * Signature: (I)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1close (JNIEnv * env, jobject o, jint sock) { if (0 == sock) return; int rv = shutdown(sock, SHUT_RDWR); if (-1 == rv) { handleerrno(env); } else { rv = close(sock); if (-1 == rv) { handleerrno(env); } } } /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_accept * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1accept (JNIEnv * env, jobject o, jint sock) { int newsock = accept(sock, NULL, NULL); if (-1 == newsock) handleerrno(env); return newsock; } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_set_pass_cred * Signature: (IZ)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1set_1pass_1cred (JNIEnv *env, jobject o, jint sock, jboolean enable) { #ifdef SO_PASSCRED int opt = enable; int rv = setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &opt, sizeof(int)); if (-1 == rv) { handleerrno(env);} #endif } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_connect * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1connect (JNIEnv *env, jobject o, jstring address, jboolean abstract) { int sock = socket(PF_UNIX, SOCK_STREAM, 0); if (-1 == sock) { handleerrno(env); return -1; } const char* caddr = (*env)->GetStringUTFChars(env, address, 0); int slen = (*env)->GetStringUTFLength(env, address)+1; struct sockaddr_un *sad = malloc(sizeof(sa_family_t)+slen); if (abstract) { char* shifted = sad->sun_path+1; strncpy(shifted, caddr, slen-1); sad->sun_path[0] = 0; } else strncpy(sad->sun_path, caddr, slen); (*env)->ReleaseStringUTFChars(env, address, caddr); sad->sun_family = AF_UNIX; int rv = connect(sock, (const struct sockaddr*) sad, sizeof(sa_family_t)+slen); free(sad); if (-1 == rv) { handleerrno(env); return -1; } return sock; } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_close * Signature: (I)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1close (JNIEnv *env, jobject o, jint sock) { if (0 == sock) return; int rv = shutdown(sock, SHUT_RDWR); if (-1 == rv) { handleerrno(env); } else { rv = close(sock); if (-1 == rv) { handleerrno(env); } } } /* * Class: cx_ath_matthew_unix_USInputStream * Method: native_recv * Signature: ([BII)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USInputStream_native_1recv (JNIEnv *env, jobject o, jint sock, jbyteArray buf, jint offs, jint len, jint flags, jint timeout) { fd_set rfds; struct timeval tv; jbyte* cbuf = (*env)->GetByteArrayElements(env, buf, NULL); void* recvb = cbuf + offs; int rv; if (timeout > 0) { FD_ZERO(&rfds); FD_SET(sock, &rfds); tv.tv_sec = 0; tv.tv_usec = timeout; rv = select(sock+1, &rfds, NULL, NULL, &tv); rv = recv(sock, recvb, len, flags); if (-1 == rv) { handleerrno(env); rv = -1; } (*env)->ReleaseByteArrayElements(env, buf, cbuf, 0); return rv; } else { rv = recv(sock, recvb, len, flags); (*env)->ReleaseByteArrayElements(env, buf, cbuf, 0); if (-1 == rv) { handleerrno(env); return -1; } return rv; } } /* * Class: cx_ath_matthew_unix_USOutputStream * Method: native_send * Signature: (I[BII)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USOutputStream_native_1send__I_3BII (JNIEnv *env, jobject o, jint sock, jbyteArray buf, jint offs, jint len) { jbyte* cbuf = (*env)->GetByteArrayElements(env, buf, NULL); void* sendb = cbuf + offs; int rv = send(sock, sendb, len, 0); (*env)->ReleaseByteArrayElements(env, buf, cbuf, 0); if (-1 == rv) { handleerrno(env); return -1; } return rv; } /* * Class: cx_ath_matthew_unix_USOutputStream * Method: native_send * Signature: (I[[B)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USOutputStream_native_1send__I_3_3B (JNIEnv *env, jobject o, jint sock, jobjectArray bufs) { size_t sblen = 1; socklen_t sblen_size = sizeof(sblen); getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sblen, &sblen_size); struct msghdr msg; struct iovec *iov; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_flags = 0; size_t els = (*env)->GetArrayLength(env, bufs); iov = (struct iovec*) malloc((els= 0; k--, l--) (*env)->ReleaseByteArrayElements(env, b[k], iov[l].iov_base, 0); if (-1 == rv) { handleerrno(env); return -1; } break; } b[i] = (*env)->GetObjectArrayElement(env, bufs, i); if (NULL == b[i]) { msg.msg_iovlen = j; rv = sendmsg(sock, &msg, 0); for (int k = i-1, l = j-1; l >= 0; k--, l--) (*env)->ReleaseByteArrayElements(env, b[k], iov[l].iov_base, 0); if (-1 == rv) { handleerrno(env); return -1; } break; } size_t l = (*env)->GetArrayLength(env, b[i]); if (s+l > sblen || j == IOV_MAX) { msg.msg_iovlen = j; rv = sendmsg(sock, &msg, 0); s = 0; for (int k = i-1, l = j-1; l >= 0; k--, l--) (*env)->ReleaseByteArrayElements(env, b[k], iov[l].iov_base, 0); j = 0; if (-1 == rv) { handleerrno(env); return -1; } } iov[j].iov_base = (*env)->GetByteArrayElements(env, b[i], NULL); iov[j].iov_len = l; s += l; } free(iov); free(b); return rv; } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_getPID * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1getPID (JNIEnv * env, jobject o, jint sock) { #ifdef SO_PEERCRED struct ucred cr; socklen_t cl=sizeof(cr); if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cr, &cl)==0) return cr.pid; else return -1; #else return -1; #endif } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_getUID * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1getUID (JNIEnv * env, jobject o, jint sock) { #ifdef SO_PEERCRED struct ucred cr; socklen_t cl=sizeof(cr); if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cr, &cl)==0) return cr.uid; else return -1; #else return -1; #endif } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_getGID * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1getGID (JNIEnv * env, jobject o, jint sock) { #ifdef SO_PEERCRED struct ucred cr; socklen_t cl=sizeof(cr); if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cr, &cl)==0) return cr.gid; else return -1; #else return -1; #endif } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_send_creds * Signature: (B)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1send_1creds (JNIEnv * env, jobject o, jint sock, jbyte data) { struct msghdr msg; struct iovec iov; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_flags = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = NULL; msg.msg_controllen = 0; iov.iov_base = &data; iov.iov_len = 1; #ifdef SCM_CREDENTIALS char buf[CMSG_SPACE(sizeof(struct ucred))]; msg.msg_control = buf; msg.msg_controllen = sizeof buf; struct cmsghdr *cmsg; struct ucred *creds; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_CREDENTIALS; cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred)); /* Initialize the payload: */ creds = (struct ucred *)CMSG_DATA(cmsg); creds->pid = getpid(); creds->uid = getuid(); creds->gid = getgid(); #endif int rv = sendmsg(sock, &msg, 0); if (-1 == rv) { handleerrno(env); } } /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_recv_creds * Signature: ([I)B */ JNIEXPORT jbyte JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1recv_1creds (JNIEnv *env, jobject o, jint sock, jintArray jcreds) { struct msghdr msg; char iov_buf = 0; struct iovec iov; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_flags = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = NULL; msg.msg_controllen = 0; iov.iov_base = &iov_buf; iov.iov_len = 1; #ifdef SCM_CREDENTIALS char buf[CMSG_SPACE(sizeof(struct ucred))]; msg.msg_control = buf; msg.msg_controllen = sizeof buf; struct cmsghdr *cmsg; struct ucred *creds = NULL; #endif recvmsg(sock, &msg, 0); #ifdef SCM_CREDENTIALS for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg,cmsg)) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) { creds = (struct ucred *) CMSG_DATA(cmsg); break; } } if (NULL != creds) { jint cred_array[3]; cred_array[0] = creds->pid; cred_array[1] = creds->uid; cred_array[2] = creds->gid; (*env)->SetIntArrayRegion(env, jcreds, 0, 3, &cred_array[0]); } #endif return iov_buf; } #ifdef __cplusplus } #endif libmatthew-java-0.8.1/cgi-java.c0000644000175000017500000000437613273414417015114 0ustar mjj29mjj29/* * Java CGI Library * * Copyright (c) Matthew Johnson 2005 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * To Contact the author, please email src@matthew.ath.cx * */ #include #include "cgi-java.h" #include #include #include extern char **environ; extern jobjectArray Java_cx_ath_matthew_cgi_CGI_getfullenv (JNIEnv *env, jobject obj, jclass type) { int i; for (i = 0; environ[i]; i++); jobjectArray joa = (*env)->NewObjectArray(env, i+1, type, NULL); for (i = 0; environ[i]; i++) (*env)->SetObjectArrayElement(env, joa, i, (*env)->NewStringUTF(env, environ[i])); return joa; } extern jstring Java_cx_ath_matthew_cgi_CGI_getenv (JNIEnv *env, jobject obj, jstring ename) { const char *estr = (*env)->GetStringUTFChars(env, ename, 0); char *eval = getenv(estr); (*env)->ReleaseStringUTFChars(env, ename, estr); if (NULL == eval) return NULL; else return (*env)->NewStringUTF(env, eval); } extern void Java_cx_ath_matthew_cgi_CGI_setenv (JNIEnv *env, jobject obj, jstring var, jstring val) { #ifdef setenv const char *cvar = (*env)->GetStringUTFChars(env, var, 0); const char *cval = (*env)->GetStringUTFChars(env, val, 0); setenv(cvar, cval, 1); #endif } libmatthew-java-0.8.1/changelog0000644000175000017500000000417313273415223015130 0ustar mjj29mjj29Version 0.8.1: * Commit versions of jni headers rather than relying on javah to be in new * versions of openjdk Version 0.8: * Change to expat licence * Patches to the CGI libraries from Andy Canfield Version 0.7.3: * Patch from 石頭成 to avoid a memory leak Version 0.7.2: * Also add .NO_PARALLEL and .NOTPARALLEL because I have no idea which one is correct * Apply patch from Omair Majid which make overriding CFLAGS easier * Use -source 1.5 rather than -source 5.0, the former works with more Java compilers * Add -fno-stack-protector to fix compilation issues in various distros * Fix spin-on-disconnection bug (Spotted by Christopher Armstrong ) Version 0.7.1: * Fix compiler warning on 64bit systems (spotted by serkankaba -at- gmail -dot- com) * Fix compilation with glibc 2.8 (patch from Omair Majid ) Version 0.7: * use += not ?= when setting *FLAGS * Possible SIGSEGV in native_close, possible fix * Don't include debug-disable in any manifests * Fix some compiler warnings. Setenv doesn't exist on all platforms. Version 0.6: * Add toByteArray to Hexdump for creating byte-array-literals in generated code. * UnixSocket output streams can now send multiple byte[] at once to use scatter-gather for efficiency * Add fuctions to get peer credentials * Work on BSD Version 0.5: * Add licence headers to files which are missing * fix javadoc calls so that -link is replacable with local docs * add .NOPARALLEL: to disable parallel building. Fails to get debugging right Version 0.4: * Add javadoc target * Add Manifest with Class-Path to relevant jars Version 0.2: * Fix Unix Sockets not to lose reference if IO streams are still referenced. * Add methods to Debug to set the config manually * update Debug defaults * add ALL as a class name to Debug * write installation guide * fix UnixSocket.setBlocking * add UnixSocket.setSoTimeout Version 0.1: * Initial code and packaging. libmatthew-java-0.8.1/README0000644000175000017500000000250412536305505014134 0ustar mjj29mjj29libmatthew-java v0.1 -------------------- These are a selection of libraries for Java which I have written because they are useful and not provided with normal Java. They are available for download here and are licensed under the GPL or LGPL. They all come with example applications using the libraries. The ones I consider distribution-worthy are packaged up together. Several other classes are available separately below. Unix Sockets Library This is a collection of classes and native code to allow you to read and write Unix sockets in Java. Debug Library This is a comprehensive logging and debugging solution. CGI Library This is a collection of classes and native code to allow you to write CGI applications in Java. I/O Library This provides a few much needed extensions to the Java I/O subsystem. Firstly, there is a class which will connect and InputStream with an OutputStream and copy data between them. Secondly there are two classes for inserting into an Input or OutputStream pipe a command line command, so that everything is piped through that command. Thirdly there are a pair of classes for splitting streams in two. This can either be to two OuputStreams, or to an OutputStream and a file. Equivelent to the UNIX tool tee in UNIX pipes. Hexdump This class formats byte-arrays in hex and ascii for display. libmatthew-java-0.8.1/unix-java.h0000644000175000017500000001043013273414444015326 0ustar mjj29mjj29/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class cx_ath_matthew_unix_UnixServerSocket */ #ifndef _Included_cx_ath_matthew_unix_UnixServerSocket #define _Included_cx_ath_matthew_unix_UnixServerSocket #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_bind * Signature: (Ljava/lang/String;Z)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1bind (JNIEnv *, jobject, jstring, jboolean); /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_close * Signature: (I)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1close (JNIEnv *, jobject, jint); /* * Class: cx_ath_matthew_unix_UnixServerSocket * Method: native_accept * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixServerSocket_native_1accept (JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif /* Header for class cx_ath_matthew_unix_UnixSocket */ #ifndef _Included_cx_ath_matthew_unix_UnixSocket #define _Included_cx_ath_matthew_unix_UnixSocket #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_set_pass_cred * Signature: (IZ)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1set_1pass_1cred (JNIEnv *, jobject, jint, jboolean); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_connect * Signature: (Ljava/lang/String;Z)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1connect (JNIEnv *, jobject, jstring, jboolean); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_close * Signature: (I)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1close (JNIEnv *, jobject, jint); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_getPID * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1getPID (JNIEnv *, jobject, jint); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_getUID * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1getUID (JNIEnv *, jobject, jint); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_getGID * Signature: (I)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1getGID (JNIEnv *, jobject, jint); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_send_creds * Signature: (IB)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1send_1creds (JNIEnv *, jobject, jint, jbyte); /* * Class: cx_ath_matthew_unix_UnixSocket * Method: native_recv_creds * Signature: (I[I)B */ JNIEXPORT jbyte JNICALL Java_cx_ath_matthew_unix_UnixSocket_native_1recv_1creds (JNIEnv *, jobject, jint, jintArray); #ifdef __cplusplus } #endif #endif /* Header for class cx_ath_matthew_unix_USInputStream */ #ifndef _Included_cx_ath_matthew_unix_USInputStream #define _Included_cx_ath_matthew_unix_USInputStream #ifdef __cplusplus extern "C" { #endif #undef cx_ath_matthew_unix_USInputStream_MAX_SKIP_BUFFER_SIZE #define cx_ath_matthew_unix_USInputStream_MAX_SKIP_BUFFER_SIZE 2048L #undef cx_ath_matthew_unix_USInputStream_MSG_DONTWAIT #define cx_ath_matthew_unix_USInputStream_MSG_DONTWAIT 64L /* * Class: cx_ath_matthew_unix_USInputStream * Method: native_recv * Signature: (I[BIIII)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USInputStream_native_1recv (JNIEnv *, jobject, jint, jbyteArray, jint, jint, jint, jint); #ifdef __cplusplus } #endif #endif /* Header for class cx_ath_matthew_unix_USOutputStream */ #ifndef _Included_cx_ath_matthew_unix_USOutputStream #define _Included_cx_ath_matthew_unix_USOutputStream #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_unix_USOutputStream * Method: native_send * Signature: (I[BII)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USOutputStream_native_1send__I_3BII (JNIEnv *, jobject, jint, jbyteArray, jint, jint); /* * Class: cx_ath_matthew_unix_USOutputStream * Method: native_send * Signature: (I[[B)I */ JNIEXPORT jint JNICALL Java_cx_ath_matthew_unix_USOutputStream_native_1send__I_3_3B (JNIEnv *, jobject, jint, jobjectArray); #ifdef __cplusplus } #endif #endif libmatthew-java-0.8.1/cgi-java.h0000644000175000017500000000164113273064644015114 0ustar mjj29mjj29/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class cx_ath_matthew_cgi_CGI */ #ifndef _Included_cx_ath_matthew_cgi_CGI #define _Included_cx_ath_matthew_cgi_CGI #ifdef __cplusplus extern "C" { #endif /* * Class: cx_ath_matthew_cgi_CGI * Method: getenv * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_cx_ath_matthew_cgi_CGI_getenv (JNIEnv *, jobject, jstring); /* * Class: cx_ath_matthew_cgi_CGI * Method: getfullenv * Signature: (Ljava/lang/Class;)[Ljava/lang/Object; */ JNIEXPORT jobjectArray JNICALL Java_cx_ath_matthew_cgi_CGI_getfullenv (JNIEnv *, jobject, jclass); /* * Class: cx_ath_matthew_cgi_CGI * Method: setenv * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_cx_ath_matthew_cgi_CGI_setenv (JNIEnv *, jobject, jstring, jstring); #ifdef __cplusplus } #endif #endif libmatthew-java-0.8.1/INSTALL0000644000175000017500000000071112536305505014303 0ustar mjj29mjj29libmatthew-java installation guide ----------------------------- To compile libmatthew-java you will need a Java 1.4 or better JDK, and a standard unix build environment including a C compiler. The libraries can be compiled and installed with `make' and `make install' respectively. By default they will be installed into /usr/local/share/java and /usr/local/lib/jni. This location can be configured by giving PREFIX, JARDIR and LIBDIR variables to make.