All Packages  Class Hierarchy  This Package  Previous  Next  Index


Class Acme.Utils

java.lang.Object
   |
   +----Acme.Utils

public class Utils
extends Object
Assorted static utility routines.

Whenever I come up with a static routine that might be of general use, I put it here. So far the class includes:

and lots more.

Fetch the software.
Fetch the entire Acme package.


Variable Index

 o INT_DAY
 o INT_DECADE
 o INT_HOUR
 o INT_MINUTE
 o INT_MONTH
 o INT_SECOND
 o INT_WEEK
 o INT_YEAR

Constructor Index

 o Utils()

Method Index

 o absoluteUrlStr(String, URL)
 o arraycontains(Object[], Object)
Check if an array contains a given element.
 o arrayToString(Object)
An array-to-String routine.
 o base64Encode(byte[])
A base-64 encoder, necessary for doing the client side of Basic Authentication.
 o base64Encode(String)
A base-64 encoder that takes a String, for convenience.
 o baseUrlStr(String)
Figure out the base URL for a given URL.
 o charCount(String, char)
Returns the number of times the given character appears in the string.
 o copyStream(InputStream, OutputStream)
Copy the input to the output until EOF.
 o copyStream(InputStream, Writer)
Copy the input to the output until EOF.
 o copyStream(Reader, OutputStream)
Copy the input to the output until EOF.
 o copyStream(Reader, Writer)
Copy the input to the output until EOF.
 o countOnes(byte)
Count the number of 1-bits in a byte.
 o countOnes(int)
Count the number of 1-bits in an int.
 o countOnes(long)
Count the number of 1-bits in a long.
 o dumpStack()
Dump out the current call stack onto System.err.
 o dumpStack(PrintStream)
Dump out the current call stack.
 o equalsStrings(String[], String[])
Compares two arrays of Strings for equality.
 o even(long)
Test is a number is even.
 o fixDirUrlStr(String)
Makes sure if a URL is a directory, it ends with a slash.
 o flattenStrarr(String[])
Turns an array of Strings into a single String, with the components separated by spaces.
 o indexOfString(String[], String)
Locates a String in an array of Strings.
 o indexOfStringIgnoreCase(String[], String)
Locates a String in an array of Strings, ignoring case.
 o instanceOf(Object, Class)
Check if an object extends a given class or one of its superclasses.
 o intervalStr(long)
Returns a string approximately describing a given time interval.
 o lsDateStr(Date)
Returns a date string formatted in Unix ls style - if it's within six months of now, Mmm dd hh:ss, else Mmm dd yyyy.
 o match(String, String)
Checks whether a string matches a given wildcard pattern.
 o odd(long)
Test is a number is odd.
 o parseInt(String, int)
Parse an integer, returning a default value on errors.
 o parseLong(String, long)
Parse a long, returning a default value on errors.
 o plainUrl(String)
Make a URL with no ref part and no query string.
 o plainUrl(URL, String)
Make a URL with no ref part and no query string.
 o pluralStr(long)
Returns "s" for numbers other than one, and "" for one.
 o popenr(String)
Run a program on the host system, and capture the output.
 o popenw(String)
Run a program on the host system, and send it some input.
 o pow(long, long)
Returns the number a raised to the power of b.
 o read(InputStream, byte[], int, int)
A fixed version of java.io.InputStream.read(byte[], int, int).
 o readFully(InputStream, byte[], int, int)
A version of read that reads the entire requested block, instead of sometimes terminating early.
 o runCommand(String)
Run a program on the host system.
 o sameSpan(String, String)
Returns the length of the initial segment of str1 that equals str2.
 o sortStrings(String[])
Sorts an array of Strings.
 o splitStr(String)
Turns a String into an array of Strings, by using StringTokenizer to split it up at whitespace.
 o splitStr(String, char)
Turns a String into an array of Strings, by splitting it at the specified character.
 o strCSpan(String, String)
Returns the length of the initial segment of str which consists entirely of characters NOT from charSet.
 o strCSpan(String, String, int)
Returns the length of the initial segment of str which consists entirely of characters NOT from charSet, starting at the given index.
 o strSpan(String, String)
Returns the length of the initial segment of str which consists entirely of characters from charSet.
 o strSpan(String, String, int)
Returns the length of the initial segment of str which consists entirely of characters from charSet, starting at the given index.
 o system(String)
Run a program on the host system.
 o urlDecoder(String)
URLDecoder to go along with java.net.URLEncoder.
 o urlStrIsAbsolute(String)
 o urlStrIsDir(String)
Figures out whether a URL points to a directory or not.

Variables

 o INT_SECOND
 public static final long INT_SECOND
 o INT_MINUTE
 public static final long INT_MINUTE
 o INT_HOUR
 public static final long INT_HOUR
 o INT_DAY
 public static final long INT_DAY
 o INT_WEEK
 public static final long INT_WEEK
 o INT_MONTH
 public static final long INT_MONTH
 o INT_YEAR
 public static final long INT_YEAR
 o INT_DECADE
 public static final long INT_DECADE

Constructors

 o Utils
 public Utils()

Methods

 o lsDateStr
 public static String lsDateStr(Date date)
Returns a date string formatted in Unix ls style - if it's within six months of now, Mmm dd hh:ss, else Mmm dd yyyy.

 o pluralStr
 public static String pluralStr(long n)
Returns "s" for numbers other than one, and "" for one.

 o intervalStr
 public static String intervalStr(long interval)
Returns a string approximately describing a given time interval.

Parameters:
interval - the interval, in milliseconds
 o strSpan
 public static int strSpan(String str,
                           String charSet)
Returns the length of the initial segment of str which consists entirely of characters from charSet.

 o strSpan
 public static int strSpan(String str,
                           String charSet,
                           int fromIdx)
Returns the length of the initial segment of str which consists entirely of characters from charSet, starting at the given index.

 o strCSpan
 public static int strCSpan(String str,
                            String charSet)
Returns the length of the initial segment of str which consists entirely of characters NOT from charSet.

 o strCSpan
 public static int strCSpan(String str,
                            String charSet,
                            int fromIdx)
Returns the length of the initial segment of str which consists entirely of characters NOT from charSet, starting at the given index.

 o match
 public static boolean match(String pattern,
                             String string)
Checks whether a string matches a given wildcard pattern. Only does ? and *, and multiple patterns separated by |.

 o sameSpan
 public static int sameSpan(String str1,
                            String str2)
Returns the length of the initial segment of str1 that equals str2.

 o charCount
 public static int charCount(String str,
                             char c)
Returns the number of times the given character appears in the string.

 o splitStr
 public static String[] splitStr(String str)
Turns a String into an array of Strings, by using StringTokenizer to split it up at whitespace.

 o splitStr
 public static String[] splitStr(String str,
                                 char delim)
Turns a String into an array of Strings, by splitting it at the specified character. This does not use StringTokenizer, and therefore can handle empty fields.

 o flattenStrarr
 public static String flattenStrarr(String strs[])
Turns an array of Strings into a single String, with the components separated by spaces.

 o sortStrings
 public static void sortStrings(String strings[])
Sorts an array of Strings. Java currently has no general sort function. Sorting Strings is common enough that it's worth making a special case.

 o indexOfString
 public static int indexOfString(String strings[],
                                 String string)
Locates a String in an array of Strings. Returns -1 if the String is not found.

 o indexOfStringIgnoreCase
 public static int indexOfStringIgnoreCase(String strings[],
                                           String string)
Locates a String in an array of Strings, ignoring case. Returns -1 if the String is not found.

 o equalsStrings
 public static boolean equalsStrings(String strings1[],
                                     String strings2[])
Compares two arrays of Strings for equality.

 o pow
 public static long pow(long a,
                        long b) throws ArithmeticException
Returns the number a raised to the power of b. Long version of Math.pow(). Throws ArithmeticException if b is negative.

 o parseInt
 public static int parseInt(String str,
                            int def)
Parse an integer, returning a default value on errors.

 o parseLong
 public static long parseLong(String str,
                              long def)
Parse a long, returning a default value on errors.

 o arrayToString
 public static String arrayToString(Object o)
An array-to-String routine. Handles arrays of arbitrary type, including nested arrays. Sample output:
 byte[]:    { (byte)0, (byte)1, (byte)2 }
 char[]:    { '0', '1', '2' }
 short[]:   { (short)0, (short)1, (short)2 }
 int[]:     { 0, 1, 2 }
 long[]:    { 0L, 1L, 2L }
 float[]:   { 0F, 1F, 2F }
 double[]:  { 0D, 1D, 2D }
 String[]:  { "0", "1", "2" }
 int[][]:   { { 0, 1, 2 }, { 3, 4, 5 } }
 

 o instanceOf
 public static boolean instanceOf(Object o,
                                  Class cl)
Check if an object extends a given class or one of its superclasses. An instanceof that works on Class objects at runtime, instead of type descriptors at compile time.

 o even
 public static boolean even(long n)
Test is a number is even.

 o odd
 public static boolean odd(long n)
Test is a number is odd.

 o countOnes
 public static int countOnes(byte n)
Count the number of 1-bits in a byte.

 o countOnes
 public static int countOnes(int n)
Count the number of 1-bits in an int.

 o countOnes
 public static int countOnes(long n)
Count the number of 1-bits in a long.

 o read
 public static int read(InputStream in,
                        byte b[],
                        int off,
                        int len) throws IOException
A fixed version of java.io.InputStream.read(byte[], int, int). The standard version catches and ignores IOExceptions from below. This version sends them on to the caller.

 o readFully
 public static int readFully(InputStream in,
                             byte b[],
                             int off,
                             int len) throws IOException
A version of read that reads the entire requested block, instead of sometimes terminating early.

Returns:
-1 on EOF, otherwise len
 o plainUrl
 public static URL plainUrl(URL context,
                            String urlStr) throws MalformedURLException
Make a URL with no ref part and no query string. Also, if it's a directory then make sure there's a trailing slash.

 o plainUrl
 public static URL plainUrl(String urlStr) throws MalformedURLException
Make a URL with no ref part and no query string. Also, if it's a directory then make sure there's a trailing slash.

 o baseUrlStr
 public static String baseUrlStr(String urlStr)
Figure out the base URL for a given URL. What this means is if the URL points to a directory, you get that directory; if the URL points to a file, you get the directory the file is in.

 o fixDirUrlStr
 public static String fixDirUrlStr(String urlStr)
Makes sure if a URL is a directory, it ends with a slash.

 o urlStrIsDir
 public static boolean urlStrIsDir(String urlStr)
Figures out whether a URL points to a directory or not. Web servers are lenient and accept directory-URLs without the trailing slash. What they actually do is return a redirect to the same URL with the trailing slash appended. Unfortunately, Java doesn't let us see that such a redirect happened. Instead we have to figure out it's a directory indirectly and heuristically.

 o urlStrIsAbsolute
 public static boolean urlStrIsAbsolute(String urlStr)
 o absoluteUrlStr
 public static String absoluteUrlStr(String urlStr,
                                     URL contextUrl) throws MalformedURLException
 o urlDecoder
 public static String urlDecoder(String encoded)
URLDecoder to go along with java.net.URLEncoder. Why there isn't already a decoder in the standard library is a mystery to me.

 o base64Encode
 public static String base64Encode(byte src[])
A base-64 encoder, necessary for doing the client side of Basic Authentication. This encodes binary data as printable ASCII characters. Three 8-bit binary bytes are turned into four 6-bit values, like so: [11111111] [22222222] [33333333] [111111] [112222] [222233] [333333] Then the 6-bit values are represented using the characters "A-Za-z0-9+/".

 o base64Encode
 public static String base64Encode(String srcString)
A base-64 encoder that takes a String, for convenience.

 o arraycontains
 public static boolean arraycontains(Object array[],
                                     Object element)
Check if an array contains a given element.

 o system
 public static int system(String cmd)
Run a program on the host system.

This routine runs the specified command, waits for it to finish, and returns the exit status. This is like the Unix system() routine. Unlike the Unix version, though, stdout and stderr get thrown away unless you redirect them.

 o popenr
 public static InputStream popenr(String cmd)
Run a program on the host system, and capture the output.

This routine runs the specified command, and returns an InputStream for reading the output of the program.

WARNING: In JDK1.0.2 there is a serious bug in the process IO routines, such that reading all the way to the end of a process's output will invariably get you an IOException( "read error" ). In some cases you will also lose the last bufferload of the output. The workaround is to add a " ; sleep 1" to the end of your command, and to ignore the "read error" IOException.

 o popenw
 public static OutputStream popenw(String cmd)
Run a program on the host system, and send it some input.

This routine runs the specified command, and returns an OutputStream for writing the program's input.

 o runCommand
 public static Process runCommand(String cmd) throws IOException
Run a program on the host system.

This routine runs the specified command, and returns a Process object so you can do what you like with it.

WARNING: In JDK1.0.2 there is a serious bug in the process IO routines, such that reading all the way to the end of a process's output will invariably get you an IOException( "read error" ). In some cases you will also lose the last bufferload of the output. The workaround is to add a " ; sleep 1" to the end of your command, and to ignore the "read error" IOException.

 o copyStream
 public static void copyStream(InputStream in,
                               OutputStream out) throws IOException
Copy the input to the output until EOF.

 o copyStream
 public static void copyStream(Reader in,
                               Writer out) throws IOException
Copy the input to the output until EOF.

 o copyStream
 public static void copyStream(InputStream in,
                               Writer out) throws IOException
Copy the input to the output until EOF.

 o copyStream
 public static void copyStream(Reader in,
                               OutputStream out) throws IOException
Copy the input to the output until EOF.

 o dumpStack
 public static void dumpStack(PrintStream p)
Dump out the current call stack.

 o dumpStack
 public static void dumpStack()
Dump out the current call stack onto System.err.


All Packages  Class Hierarchy  This Package  Previous  Next  Index

ACME Java  ACME Labs