PK =R:META-INF/MANIFEST.MFManifest-Version: 1.0 PK 4\]@y!com/myjavatools/lib/AllTests.javapackage com.myjavatools.lib; import junit.framework.*; public class AllTests extends TestCase { public AllTests(String s) { super(s); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(com.myjavatools.lib.foundation.TestCompoundCollection.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestFilter.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestFunction.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestIterators.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestMaps.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestPair.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestRestrictedFunctionEntrySet.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestRestrictedMapEntrySet.class); suite.addTestSuite(com.myjavatools.lib.TestObjects.class); suite.addTestSuite(com.myjavatools.lib.TestStrings.class); suite.addTestSuite(com.myjavatools.lib.TestFiles.class); suite.addTestSuite(com.myjavatools.lib.TestWeb.class); suite.addTestSuite(com.myjavatools.lib.TestTools.class); return suite; } } PK 8v01n) com/myjavatools/lib/Bytes.java/** *

Title: MyJavaTools: Bytes Handling

*

Description: Several methods to handle data as bytes * * Good for Java 5.0 and up.

*

Copyright: This is public domain; * The right of people to use, distribute, copy or improve the contents of the * following may not be restricted.

* * @version 5.0 * @author Vlad Patryshev */ package com.myjavatools.lib; import java.util.zip.CRC32; public abstract class Bytes { /** * Converts char array to byte array (per-element casting) * * @param from char array * @return byte array * *

Example: *
  • toBytes(new char[] {0x0123, 0x4567, 0x89ab, 0xcdef}) * returns {0x23, 0x67, (byte)0xab, (byte)0xef}.
  • */ public static final byte[] toBytes(char[] from) { byte[] result = new byte[from.length]; for (int i = 0; i < from.length; i++) { result[i] = (byte)from[i]; } return result; } /** * Converts byte array to char array (per-element casting) * @param from byte array * @return char array * *

    Example: *
  • toChars(new byte[] {0x23, 0x67, (byte)0xab, (byte)0xef}) * returns new char[] {0x23, 0x67, 0xab, 0xef}.
  • */ public static final char[] toChars(byte[] from) { char[] result = new char[from.length]; for (int i = 0; i < from.length; i++) { result[i] = (char)(0xff & from[i]); } return result; } /** * Calculates crc32 on a byte array * * @param data source bytes * @return its crc32 * *

    Example: *
  • crc32(new byte[] {1, 2, 3}) * returns 1438416925.
  • */ public static final long crc32(byte[] data) { CRC32 crc32 = new CRC32(); crc32.update(data); return crc32.getValue(); } /** * Calculates crc32 on a byte array * * @param data source bytes * @param off offset in the array * @param len length of the area to crc * @return its crc32 * *

    Example: *
  • crc32(new byte[] {0, 1, 2, 3, 4}, 1, 3) * returns 1438416925.
  • */ public static final long crc32(byte[] data, int off, int len) { CRC32 crc32 = new CRC32(); crc32.update(data, off, len); return crc32.getValue(); } /** * Converts long to byte array (lower bytes first) * * @param from the long value * @return byte array * *

    Example: *
  • toBytes(0x0123456789abcdefl) * returns {(byte)0xef, (byte)0xcd, (byte)0xab, (byte)0x89, 0x67, 0x45, 0x23, 0x01}.
  • */ public static final byte[] toBytes(long from) { java.lang.Long l; byte[] result = new byte[8]; for (int i = 0; i < 8; i++) { result[i] = (byte)from; from >>= 8; } return result; } } // 07/23/2004 - TestBytes tests cr32(2), toBytes(2), toChars. PK @Q:$""com/myjavatools/lib/Files.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Files.java 6.0 02/17/09 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib; import java.io.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import static com.myjavatools.lib.Bytes.*; import static com.myjavatools.lib.foundation.Iterators.*; import static com.myjavatools.lib.foundation.Objects.*; import static com.myjavatools.lib.Strings.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.Channels; import java.nio.MappedByteBuffer; import java.net.URL; /** * Files is a utility class that contains static methods for handling files and directories * * @version 6.0, 02/17/09 * @since 5.0 */ public abstract class Files { private static final boolean DEBUG = true; private static final char altSeparatorChar = File.separatorChar == '/' ? '\\' : '/'; /** * Calculates full path of a file * @param file * @return full path */ public static final String getFullPath(File file) { try { return file.getCanonicalPath(); } catch (IOException ex) { } return file.getAbsolutePath(); } /** * Calculates full path of a file by its path * @param path * @return full path */ public static final String getFullPath(String path) { return getFullPath(new File(path)); } /** * Calculates relative path * * @param dir directory path that is expected to start the file path * @param path file path, relativer or not * @return if path starts with dir, then the rest of the path, else path * *

    Examples: *
  • relPath("c:\\MyHome\\dev", "c:\\MyHome\\dev\\src\\java") returns "src\\java";
  • *
  • relPath("/home/zaphod", "/home/zaphod/jbuilder8/samples/welcome") returns "jbuilder8/samples/welcome";
  • *
  • relPath("/home/zaphod", "/home/ford/jbuilder8") returns "/home/ford/jbuilder8".
  • */ public static String relPath(String dir, String path) { String fullpath = getFullPath(path); String fulldir = getFullPath(dir); if (!fullpath.startsWith(fulldir + File.separatorChar)) { return path; } String result = fullpath.substring(fulldir.length() + 1); if (dir.indexOf(File.separatorChar) < 0 && path.indexOf(File.separatorChar) < 0 && (dir.indexOf(altSeparatorChar) >= 0 || path.indexOf(altSeparatorChar) >= 0)) { return result.replace(File.separatorChar, altSeparatorChar); } return result; } /** * Having a directory and file path (relative or absolute) calculates full path * * @param currentDir directory path * @param filepath file path, relative or not * @return full file path * *

    Examples: *
  • path("c:\\MyHome\\dev", "src\\java") returns "c:\\MyHome\\dev\\src\\java";
  • *
  • path("/root/inetd", "/home/zaphod/jbuilder8/samples/welcome") returns "/home/zaphod/jbuilder8/samples/welcome";
  • *
  • path("\\Program Files", "c:\\MyHome\\dev") returns "c:\\MyHome\\dev".
  • */ public static String path(String currentDir, String filepath) { return (filepath.charAt(0) == File.separatorChar || filepath.charAt(0) == altSeparatorChar || filepath.indexOf(':') > 0 || isEmpty(currentDir)) ? filepath : (currentDir + (currentDir.endsWith(File.separator) ? "" : File.separator) + filepath); } /** * Splits a path into directory name and file name * * @param path * @return String array consisting of two elements * *

    Examples: *
  • splitPath("/home/zaphod/jbuilder8/samples/welcome") returns {"/home/zaphod/jbuilder8/samples", "welcome"};
  • *
  • splitPath("src.java") returns {".", "src.java"};
  • *
  • splitPath("MyHome\\dev") returns {"MyHome", "dev"}.
  • */ public static String[] splitPath(String path) { return new String[] {dirname(path), new File(path).getName()}; } /** * Calculates directory path for a file (like in Perl) * * @param file * @return directory path * * Unlike java.io.File.getParent(), never returns null (see example 2 below). * *

    Examples: *
  • dirname(new File("/home/zaphod/jbuilder11/samples/welcome")) returns "/home/zaphod/jbuilder8/samples";
  • *
  • dirname(new File("src.java")) returns ".";
  • *
  • dirname(new File("MyHome\\dev")) returns "MyHome".
  • */ public static String dirname(File file) { String parent = file.getParent(); if (parent == null) parent = "."; if (file.getPath().indexOf(File.separatorChar) < 0 && file.getPath().indexOf(altSeparatorChar) >= 0 && parent.indexOf(File.separatorChar) >= 0) { parent = parent.replace(File.separatorChar, altSeparatorChar); } return parent; } /** * Calculates directory path by file path (like in Perl) * * @param path * @return directory path * * Unlike java.io.File.getParent(), never returns null (see example 2 below). * *

    Examples: *
  • dirname("/home/zaphod/jbuilder11/samples/welcome") returns "/home/zaphod/jbuilder8/samples";
  • *
  • dirname("src.java") returns ".";
  • *
  • dirname("MyHome\\dev") returns "MyHome".
  • */ public static String dirname(String path) { String dirname = dirname(new File(path)); if (path.indexOf(altSeparatorChar) >= 0 && path.indexOf(File.separatorChar) < 0) { return dirname.replace(File.separatorChar, altSeparatorChar); } return dirname; } /** * Calculates filename by file path (like in Perl) * * @param path * @return file name * *

    Example: *
  • filename("/home/zaphod/jbuilder11/samples/welcome") returns "welcome".
  • */ public static String filename(String path) { return new File(path).getName(); } /** * Lists recursively files and directories with name matching a regexp * * @param subdir where to look * @param pattern to match * @return List<String> of absolute filepaths * *

    Example: *
  • find(new File("."), Pattern.compile(".*les\\.java$"))) returns * Arrays.asList(new String[] {new File("Files.java").getCanonicalPath()}).
  • */ public static List find(File subdir, Pattern pattern) { List resultSet = new ArrayList(); File contents[] = subdir.listFiles(); for (File file : contents) { String path = getFullPath(file); if (file.isDirectory()) { resultSet.addAll(find(file, pattern)); } else if (pattern.matcher(path).find()) { resultSet.add(path); } else { path = path.replace(File.separatorChar, '/'); if (pattern.matcher(path).find()) { resultSet.add(path); } } } return resultSet; } /** * Lists recursively files and directories with name matching a regexp * * @param subdir where to look * @param pattern to match * @return List<String> of absolute filepaths * *

    Example: *
  • find(".", Pattern.compile(".*les\\.java$"))) returns * Arrays.asList(new String[] {"Files.java"}).
  • */ public static List find(String subdir, Pattern pattern) { return find(new File(subdir), pattern); } /** * Lists recursively files and directories with name matching a regexp * * @param subdir where to look * @param pattern to match * @return List<String> of absolute filepaths * *

    Example: *
  • find(".", ".*les\\.java$") returns * Arrays.asList(new String[] {"Files.java"}).
  • */ public static List find(String subdir, String pattern) { try { return find(subdir, Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } catch (Exception e) { return new ArrayList(); } } public final static int FIND_FILE = 1; public final static int FIND_DIRECTORY = 2; public final static int FIND_ALL = 3; /** * Finds latest file or directory or one of these which name matches a pattern * * @param subdir where to look * @param pattern to match * @param whatExactly can be FIND_FILE or FIND_DIRECTORY or FIND_ALL * @return the path found */ public static String findLatest(String subdir, String pattern, int whatExactly) { String currentFile = null; long currentTime = 0; for (String path : find(subdir, pattern)) { File candidate = new File(path); boolean isGood = ((candidate.isDirectory() ? FIND_DIRECTORY : candidate.isFile() ? FIND_FILE : 0) & whatExactly) != 0; if (currentTime < candidate.lastModified() && isGood) { try { currentTime = candidate.lastModified(); currentFile = candidate.getCanonicalPath(); } catch (Exception e) {} } } return currentFile; } /** * Finds latest file or directory which name matches a pattern * * @param subdir where to look * @param pattern to match * @return the path found */ public static String findLatest(String subdir, String pattern) { return findLatest(subdir, pattern, FIND_ALL); } /** * Finds latest file which name matches a pattern * * @param subdir where to look * @param pattern to match * @return the path found */ public static String findLatestFile(String subdir, String pattern) { return findLatest(subdir, pattern, FIND_FILE); } /** * Finds latest directory which name matches a pattern * * @param subdir where to look * @param pattern to match * @return the path found */ public static String findLatestDirectory(String subdir, String pattern) { return findLatest(subdir, pattern, FIND_DIRECTORY); } /** * directoryFilter is a FileFilter that accepts directories only */ static public FileFilter DIRECTORY_FILTER = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; /** * fileFilter is a FileFilter that accepts files only */ static public FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isFile(); } }; /** * Lists subdirectories of a directory * @param dir directory name * @return an array of subdirectores */ public static final File[] listSubdirectories(File dir) { return dir.isDirectory() ? dir.listFiles(DIRECTORY_FILTER) : null; } /** * Lists files in a directory * @param dir directory name * @return an array of files */ public static final File[] listFiles(File dir) { return dir.isDirectory() ? dir.listFiles(fileFilter) : null; } /** * Gets file modification date/time as a string * @param file * @return file modification time as a string * *

    Example: *
  • lastModified(new File("src/com/javatools/util/Objects.java")) returns * "something".
  • */ public static final String lastModified(File file) { return (new Date(file.lastModified())).toString(); } /** * Gets current directory path * * @return the current directory path */ public static String getcwd() { File here = new File("."); try { return here.getCanonicalPath(); } catch (Exception e) {}; return here.getAbsolutePath(); // return System.getProperty("user.dir"); } // /** // * Changes current directory // * // * @param dir to chdir // * @return previous current directory // */ // public static String chdir(String dir) { // String cwd = System.getProperty("user.dir"); // // if (dir != null) System.setProperty("user.dir", dir); // return cwd; // } /** * Deletes a file or a directory (with all its contents, they say it is dangerous) * @param filename * @return true if successful * *

    Bad Example: *
  • deleteFile("/etc") returns true if the program runs as root.
  • */ public static boolean deleteFile(String filename) { return deleteFile(new File(filename)); } /** * Deletes a file or a directory (with all its contents, they say it is dangerous) * @param file to delete * @return true if successful * */ public static boolean deleteFile(File file) { try { if (file.isDirectory()) { String fullpath = file.getCanonicalPath(); for (String filename : file.list()) { deleteFile(new File(fullpath, filename)); } } return !file.exists() || file.delete(); } catch (Exception e) {} return false; } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten, unless append is true. * append determines whether to open in append mode * * @param dirname file location * @param filename the name of the file * @param append true if open in append mode * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(String dirname, String filename, boolean append) throws IOException { if (isEmpty(dirname)) { return new FileOutputStream(new File(filename), append); } else { File dir = new File(dirname); if (!dir.isDirectory()) { if (dir.exists()) dir.delete(); dir.mkdirs(); } return new FileOutputStream(new File(dirname, filename), append); } } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten. * * @param dir file location * @param filename the name of the file * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(String dir, String filename) throws IOException { return makeFile(dir, filename, false); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten, unless append is true. * append determines whether to open in append mode * * @param path [0] is directory name, [1] is file name * @param append true if open in append mode * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(String[] path, boolean append) throws IOException { return makeFile(path[0], path[1], append); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten. * * @param path String[] - a compound file path, ending with file name * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(String... path) throws IOException { return path.length < 1 ? null : path.length < 2 ? makeFile(path[0]) : path.length < 3 ? makeFile(path[0], path[1]) : makeFile(join(File.separator, path)); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten, unless append is true. * append determines whether to open in append mode * * @param path file path * @param append true if open in append mode * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(String path, boolean append) throws IOException { return makeFile(splitPath(path), append); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten. * * @param path file path * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(String path) throws IOException { return makeFile(splitPath(path)); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten, unless append is true. * append determines whether to open in append mode * * @param file the file to open * @param append true if open in append mode * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(File file, boolean append) throws IOException { return makeFile(file.getCanonicalPath(), append); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten. * * @param file the file to open * @return file output stream * @throws IOException */ public static FileOutputStream makeFile(File file) throws IOException { return makeFile(file.getCanonicalPath()); } /** * Creates or opens a file for output. * If subdirectories in the path do not exist, they are created too. * If the file exists, it is overwritten. * * @param path the file to open * @param encoding the encoding to use * @return output stream writer * @throws IOException */ public static final OutputStreamWriter makeFileWriter(String path, String encoding) throws IOException { return new OutputStreamWriter(makeFile(path), encoding); } /** * Adjusts buffer size according to Moore's law * @param size int original buffer size * @param thisYear int the year this specific size was chosen * @return int buffer size adjusted by Moore's law: "double it every three years" */ public static final int adjustSizeByMooreLaw(int size, int thisYear) { double milli = System.currentTimeMillis(); double aYear = (double)1000 * 60 * 60 * 24 * (365 * 4 + 1) / 4; double q = Math.exp((milli / aYear + 1970 - thisYear) / 3 * Math.log(2)); return (int)(size * q); } /** * Reads the whole reader contents into a string * * @param reader the reader to read * @return contents as a string, or null if error occurred * */ private final static int MAX_BUFFER_SIZE = Files.adjustSizeByMooreLaw(65536, 2004); public static final String readString(Reader reader) { try { StringBuffer buf = new StringBuffer(); char[] chars = new char[MAX_BUFFER_SIZE]; int l; while ((l = reader.read(chars)) > 0) { buf.append(chars, 0, l); } return buf.toString(); } catch (Exception e) { } return null; } /** * Reads the whole file into a string * * @param file the file to read * @return file contents as a string, or null if error occurred * *

    Example: *
  • readStringFromFile("../src/com/myjavatools/utils/Files.java") * returns a string starting with "/**\r\n * <p>Title: MyJavaTools: Files handling Tools</p>\r\n*".
  • */ public static final String readStringFromFile(File file) { try { return readString(new FileReader(file)); } catch (Exception e) { if (DEBUG) System.out.println(e); } return null; } /** * Reads the whole file into a string * * @param file the file to read * @param encoding the expected encoding * @return file contents as a string, or null if error occurred * */ public static final String readStringFromFile(File file, String encoding) { try { return readString(new InputStreamReader(new FileInputStream(file), encoding)); } catch (Exception e) { } return null; } /** * Reads the whole file into a string * * @param filename the file to read * @return file contents as a string, or null if error occurred * *

    Example: *
  • readStringFromFile("../src/com/myjavatools/utils/Files.java") * returns a string starting with "/**\r\n * <p>Title: MyJavaTools: Files handling Tools</p>\r\n*".
  • */ public static final String readStringFromFile(String filename) { return readStringFromFile(new File(filename)); } /** * Reads the whole input stream into a byte array * * @param is input stream to read * @return file contents as byte array, or null if error occurred * *

    Example: *
  • readBytesFromStream(new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5})) * returns new byte[] {1, 2, 3, 4, 5}.
  • */ public static final byte[] readBytesFromStream(InputStream is) { try { ArrayList chunkList = new ArrayList(); int total = 0; int l; while ((l = is.available()) > 0) { byte[] chunk = new byte[l]; is.read(chunk); chunkList.add(chunk); total += l; } byte[] buffer = new byte[total]; int pos = 0; for (byte[] chunk : chunkList) { java.lang.System.arraycopy(chunk, 0, buffer, pos, chunk.length); } return buffer; } catch (Exception e) { } return null; } /** * Reads the whole input stream into a byte array * * @param filename file to read * @return file contents as byte array, or null if error occurred * *

    Example: *
  • readBytesFromFile("../src/com/myjavatools/utils/Files.java") * returns a byte array starting with {51, 50, 50, 13, 10, 32, 50}.
  • */ public static final byte[] readBytesFromFile(String filename) { try { File file = new File(filename); long fullsize = file.length(); if (fullsize > Integer.MAX_VALUE) { throw new IOException("File too large"); } FileChannel channel = new FileInputStream(file).getChannel(); MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); byte[] result = new byte[(int)fullsize]; buffer.get(result); return result; // return readBytesFromStream(); } catch (Exception e) { } return null; } /** * Creates a file and writes a char sequence into it * * @param data the char sequence to write to file * @param fileTo file path * @return file */ public static final File writeToFile(CharSequence data, String fileTo) { try { File file = new File(fileTo); OutputStreamWriter sw = new OutputStreamWriter(makeFile(file)); write(sw, data); sw.close(); return file; } catch (Exception e) { } return null; } /** * Creates a file and writes chars into it * * @param data array of characters to write to file * @param fileTo file path * @return file */ public static final File writeToFile(char[] data, String fileTo) { try { File file = new File(fileTo); OutputStreamWriter sw = new OutputStreamWriter(makeFile(file)); sw.write(data); sw.close(); return file; } catch (Exception e) { } return null; } /** * Creates a file and writes bytes into it * * @param data array of bytes to append to the end of file * @param fileTo file path * @return file */ public static final File writeToFile(byte[] data, String fileTo) { try { File file = new File(fileTo); OutputStream os = makeFile(file); os.write(data); os.close(); return file; } catch (Exception e) { } return null; } /** * Writes bytes to a file * * @see #writeToFile(byte[],String) * @return file */ public static final File writeBytesToFile(byte[] data, String fileTo) { return writeToFile(data, fileTo); } /** * Creates a file and copies into it bytes from an input stream * * @param is input stream * @param fileTo file path * @throws IOException * @return file */ public static final File writeToFile(InputStream is, String fileTo) throws IOException { File file = new File(fileTo); OutputStream os = makeFile(file); pipe(is, os, false); os.close(); return file; } /** * Appends a char sequence to the end of a file * * @param data char sequence to append to the end of file * @param fileTo file path * @return file */ public static final File appendToFile(CharSequence data, String fileTo) { try { File file = new File(fileTo); OutputStreamWriter sw = new OutputStreamWriter(makeFile(file, true)); write(sw, data); sw.close(); return file; } catch (Exception e) { } return null; } /** * Appends chars to the end of a file * * @param data array of characters to append to the end of file * @param fileTo file path * @return file */ public static final File appendToFile(char[] data, String fileTo) { try { File file = new File(fileTo); OutputStreamWriter sw = new OutputStreamWriter(makeFile(file, true)); sw.write(data); sw.close(); return file; } catch (Exception e) { } return null; } /** * Appends bytes to the end of a file * * @param data array of characters to append to the end of file * @param fileTo file path * @return file */ public static final File appendToFile(byte[] data, String fileTo) { try { File file = new File(fileTo); OutputStream os = makeFile(file, true); os.write(data); os.close(); return file; } catch (Exception e) { } return null; } /** * Appends bytes to the end of a file * * @param data chars to append are converted to bytes * @param fileTo * @return file */ public static final File appendBytesToFile(char[] data, String fileTo) { return appendBytesToFile(toBytes((char[])data), fileTo); } /** * Appends bytes to a file * @see #appendToFile(byte[],String) */ public static final File appendBytesToFile(byte[] data, String fileTo) { return appendToFile(data, fileTo); } /** * Calculates a java package name by directory name and base directory name * * @param basePath the base path for code source * @param currentPath the path of current directory * @return package name * *

    Examples: *
  • getPackageName("c:\\home\\myjavatools\\src", "c:\\home\\myjavatools\\src\\com\\myjavatools\\util") * returns "com.myjavatools.util".
  • *
  • getPackageName("c:\\home\\myjavatools\\src\\java", "c:\\home\\myjavatools\\src\\com\\myjavatools\\util") * returns null.
  • * */ public static final String getPackageName(String basePath, String currentPath) { String path = relPath(basePath, currentPath); return path == null ? null : path.equals(currentPath) ? null : path.replace(File.separatorChar, '.'); } /** *

    Description: The interface is used to define filters for * filtering data in pipes. Filters, similar to those in JSPs, can modify * the bytes going from one end of the pipe to another, or just sniff them * and act based on results - e.g. count bytes, calculate crc, you name it.

    */ public interface ByteFilter { /** * filters data coming from input * @param input byte[] input data * @param length int number of meaningful bytes * @return byte[] result of filtering */ byte[] filter(byte[] input, int length); } /** *

    Description: Buffering filter stores some data, and these data can be * retrieved later. * @see #ByteFilter */ public interface BufferingFilter extends ByteFilter { /** * gets data stored as a result of filtering; no assumption regarding the nature of the data. * @return byte[] */ byte[] getBuffer(); /** * clears the filter buffer */ void clear(); } /** * pipes data from input stream to output stream, possibly pumping them through * the filter (if any) * @param in InputStream the source of data * @param out OutputStream where the output goes, filtered if filter is present, or unfiltered otherwise * @param isBlocking boolean whether input is blocking (in this case the maximum amount is read in one operation; for nonblocking in.available() determines how many bytes can be read) * @param filter ByteFilter the filter that applies to data; can be null * @throws IOException when input or output fails * * see the test for examples */ public static void pipe(InputStream in, OutputStream out, boolean isBlocking, ByteFilter filter) throws IOException { byte[] buf = new byte[MAX_BUFFER_SIZE]; int nread; int navailable; int total = 0; synchronized (in) { while((navailable = isBlocking ? buf.length : in.available()) > 0 && (nread = in.read(buf, 0, Math.min(buf.length, navailable))) >= 0) { if (filter == null) { out.write(buf, 0, nread); } else { byte[] filtered = filter.filter(buf, nread); out.write(filtered); } total += nread; } } out.flush(); buf = null; } /** * pipes data from input stream to output stream * * @param in InputStream the source of data * @param out OutputStream where the output goes, filtered if filter is present, or unfiltered otherwise * @param isBlocking boolean whether input is blocking (in this case the maximum amount is read in one operation; for nonblocking in.available() determines how many bytes can be read) * @throws IOException when input or output fails * * see the test for examples */ public static void pipe(InputStream in, OutputStream out, boolean isBlocking) throws IOException { pipe(in, out, isBlocking, null); } /** * pipes data from input stream to output stream * * @param in Reader the source of data * @param out Writer where the output goes, filtered if filter is present, or unfiltered otherwise * @return boolean true if successful, false otherwise * * see the test for examples */ public static boolean pipe(Reader in, Writer out) { if (in == null) { return false; } if (out == null) { return false; } try { int c; synchronized (in) { while(in.ready() && (c = in.read()) > 0) { // have to have in.ready() here, otherwise it will hang! out.write(c); } } out.flush(); } catch(Exception e) { return false; } return true; } private static boolean COPY_DEBUG = false; /** * copies a file or a directory from one directory to another * @param from directory from where to copy * @param to directory where to copy * @param what what to copy (file or directory, recursively) * @return true if successful * *

    Example: *

  • copy("c:\\home\\vlad\\dev", "c:\\home\\vlad\\rtm", "contents.xml")
  • */ public static boolean copy(String from, String to, String what) { return copy(new File(from, what), new File(to, what)); } /** * copy copies a file or a directory from one directory to another * @param from directory from where to copy * @param to directory where to copy * @param what what to copy (file or directory, recursively) * @return true if successful * *

    Example: *
  • copy(new File(myHomeDir, "dev"), new File(myHomeDir, "rtm"), "contents.xml")
  • */ public static boolean copy(File from, File to, String what) { return copy(new File(from, what), new File(to, what)); } /** * copy copies a file or a directory to another * @param from * @param to * @return true if successful * *

    Example: *
  • copy("c:\\home\\vlad\\dev\\contents.xml", "c:\\home\\vlad\\rtm\\contents.rss")
  • */ public static boolean copy(String from, String to) { return copy(new File(from), new File(to)); } /** * copy copies a file or a directory to another * @param from * @param to * @return true if successful * *

    Example: *
  • copy(new File(myHomeDir, "contents.xml"), new File(mySite, "contents.rss")
  • */ public static boolean USE_NIO = true; public static boolean copy(File from, File to) { if (from.isDirectory()) { if (!to.exists()) { to.mkdirs(); if (!to.exists()) { if (COPY_DEBUG) System.out.println("Could not create directory " + to); return false; } } else if (!to.isDirectory()) { if (COPY_DEBUG) System.out.println("File " + to + " should be a directory"); return false; } for (String name : Arrays.asList(from.list())) { if (!copy(from, to, name)){ if (COPY_DEBUG) System.out.println("Failed to copy " + name + " from " + from + " to " + to); return false; } } } else { try { FileInputStream is = new FileInputStream(from); FileChannel ifc = is.getChannel(); FileOutputStream os = makeFile(to); if (USE_NIO) { FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (IOException ex) { if (COPY_DEBUG) System.out.println("Failed to copy " + from + " to " + to + ": " + ex); return false; } } long time = from.lastModified(); setLastModified(to, time); long newtime = to.lastModified(); if (COPY_DEBUG) { if (newtime != time) { System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime)); to.setLastModified(time); long morenewtime = to.lastModified(); return false; } else { System.out.println("Timestamp for " + to + " set successfully."); } } return time == newtime; } /** * Sets the last-modified time of the file or directory named by this * abstract pathname. * * The reason for this specific method is Java bug 4243868: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4243868 * It does not always work without the trick... * * @see java.io.File#setLastModified * * @param file File * @param time long * * @return true if and only if the operation succeeded; * false otherwise * * @throws IllegalArgumentException If the argument is negative * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the named file * * @since 5.0 */ public static boolean setLastModified(File file, long time) { if (file.setLastModified(time)) { return true; } System.gc(); return file.setLastModified(time); } private static final boolean EQUAL_DEBUG = DEBUG; /** * compares two files or directories, recursively * @param left File * @param right File * @return boolean */ public static boolean equal(File left, File right) { if (left.isDirectory() && right.isDirectory()) { Set leftSet = new HashSet(Arrays.asList(left.list())); Set rightSet = new HashSet(Arrays.asList(right.list())); if (leftSet.size() != rightSet.size()) { if (EQUAL_DEBUG) { System.out.println(left.getPath() + " has " + leftSet.size() + " while " + right.getPath() + " has " + rightSet.size()); } return false; } for (String name : leftSet) { if (rightSet.contains(name)) { if (!equal(new File(left, name), new File(right, name))) { if (EQUAL_DEBUG) { System.out.println(left.getPath() + File.separator + name + " is different from " + right.getPath() + File.separator + name); } return false; } } else { if (EQUAL_DEBUG) { System.out.println(right.getPath() + " does not contain " + name); } return false; } } return true; } else if (left.isFile() && right.isFile()) { try { return compare(left, right) == 0; } catch (IOException e) { if (EQUAL_DEBUG) { System.out.println(e.getMessage() + " while comparing " + left.getPath() + " and " + right.getPath()); } return false; } } else { return false; } } /** * Compare two files * @param left * @param right * @return -1 if left file is older or shorter or "smaller" than right * 0 if files are equal * 1 if right file is older or shorter or "smaller" than left * * *

    Example: *
  • copy(new File(myHomeDir, "contents.xml"), new File(mySite, "contents.rss");
    * compare(new File(myHomeDir, "contents.xml"), new File(mySite, "contents.rss")
    returns -1 *
  • */ public static int compare(File left, File right) throws IOException { long lm = left.lastModified() / 1000; long rm = right.lastModified() / 1000; if (lm < rm) return -1; if (lm > rm) return 1; long ll = left.length(); long rl = right.length(); if (ll < rl) return -1; if (ll > rl) return 1; InputStream is1 = new BufferedInputStream(new FileInputStream(left)); InputStream is2 = new BufferedInputStream(new FileInputStream(right)); for (long i = 0; i < ll; i++) { int b1 = is1.read(); int b2 = is2.read(); if (b1 < 0) return -1; if (b2 < 0) return 1; if (b1 != b2) return b1 < b2 ? -1 : 1; } return 0; } /** * synchronizes two directories, left/what and right/what * @param left File first directory that contains directory what * @param right File second directory that contains directory what * @param what String name of directory which contents is being synchronized * @return boolean true if success * *

    Example: *
  • synchronize(new File(myHomeDir), new File(mySite), "myjavatools.com") * will leave subdirectories named myjavatools.com in these two directories absolutely identical.
  • */ public static boolean synchronize(File left, File right, String what) { return synchronize(new File(left, what), new File(right, what)); } /** * synchronizes two directories * @param left File first directory * @param right File second directory * @return boolean true if success * *

    Example: *
  • synchronize(new File(myHomeDir), new File(myBackupDir)) * will leave the contents of directories myHomeDIr and myBackupDir absolutely identical.
  • */ public static boolean synchronize(File left, File right) { if (left.isDirectory() || right.isDirectory()) { String [] leftContents = left.list(); Set contents = leftContents == null ? new LinkedHashSet() : new LinkedHashSet(Arrays.asList(leftContents)); String[] rightContents = right.list(); if (rightContents != null) { contents.addAll(Arrays.asList(rightContents)); } for (String name : contents) { if (!synchronize(left, right, name)) return false; } } else { long leftTime = left.lastModified(); long rightTime = right.lastModified(); if (left.exists() && (!right.exists() || leftTime < rightTime)) { return copy(left, right); } else if (right.exists() && (!left.exists() || leftTime > rightTime)) { return copy(right, left); } } return true; } /** * unzips an input stream to a specified folder * @param zis ZipInputStream the source of zipped files * @param location File the folder (directory) where to unzip the files * @throws IOException when something went wrong * @return boolean true if success, false otherwise * * *

    Example: *
  • unzip(Web.getUrlInputStream(new URL(synchronize(new File(myHomeDir), new File(myBackupDir)) * will leave the contents of directories myHomeDIr and myBackupDir absolutely identical.
  • */ static public boolean unzip(ZipInputStream zis, File location) throws IOException { if (!location.exists()) { location.mkdirs(); } ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { File output = new File(location, ze.getName()); if (ze.isDirectory()) { output.mkdirs(); } else { File dir = output.getParentFile(); if (!dir.isDirectory()) dir.delete(); dir.mkdirs(); if (!dir.exists()) { System.err.println("Could not create directory " + dir.getCanonicalPath()); return false; } OutputStream os = new FileOutputStream(output); pipe(zis, os, true); os.close(); } } zis.close(); return true; } /** * installs files from a resource archive * Reads a specified resource for aspecified class, unzips it to a specified directory * @param clazz Class the class whose package contains the archive as a resource * @param resourceArchiveName String the name of resource containing the archive * @param location File directory where the archive is unzipped * @throws IOException if something goes wrong * @return boolean true if success, false if failed */ public static boolean install(Class clazz, String resourceArchiveName, File location) throws IOException { ZipInputStream zis = new ZipInputStream(clazz.getResourceAsStream(resourceArchiveName)); return unzip(zis, location); } /** * installs files from a URL * Reads the contents of the specified URL, unzips it to a specified directory * @param URL url the url containing an archive to install * @param location File directory where the archive is unzipped * @throws IOException if something goes wrong * @return boolean true if success, false if failed */ public static boolean install(URL url, File location) throws IOException { return unzip(new ZipInputStream(url.openStream()), location); } /** * installs files from a URL * Reads the contents of the specified URL, unzips it to a specified directory * @param String urlString the string with the url containing an archive to install * @param location File directory where the archive is unzipped * @throws IOException if something goes wrong * @return boolean true if success, false if failed */ public static boolean install(String urlString, String directoryName) throws IOException { return unzip(new ZipInputStream(new URL(urlString).openStream()), new File(directoryName)); } /** * installs files from a resource archive * Reads a specified resource for aspecified class, unzips it to a specified directory * @param clazz Class the class whose package contains the archive as a resource * @param resourceArchiveName String the name of resource containing the archive * @param folderName String name of directory where the archive is unzipped * @throws IOException if something goes wrong * @return boolean true if success, false if failed */ public static boolean install(Class clazz, String resourceArchiveName, String folderName) throws IOException { return install(clazz, resourceArchiveName, new File(folderName)); } private static class ByteIterator implements Iterator { IOException exception = null; byte next; boolean have = false; InputStream is = null; private ByteIterator(InputStream is) { this.is = is; } public boolean hasNext() { if (have) { return true; } else if (is == null) { return false; } else { try { int input = is.read(); if (input < 0) { close(); } else { have = true; next = (byte)input; } } catch (IOException ex) { exception = ex; close(); } } return is != null; } public Byte next() { if (!hasNext()) { throw exception == null ? new NoSuchElementException() : new NoSuchElementException(exception.getMessage()); } have = false; return next; } public void remove() { throw new UnsupportedOperationException(); } private void close() { if (is != null) { try { is.close(); } catch (Exception e) {} } is = null; } protected void finalize() { close(); } } /** * returns an Iterable<Byte> enclosure that scans over the bytes returned by InputStream * @param is InputStream the stream to scan * @return Iterable<Byte> the enclosure * * The Iterator returned by the Iterable is a singleton; * you cannot expect to get a fresh Iterator by calling * iterator() several times. * *

    Example:

    * * for(byte b : bytes(new java.net.URL("http://yahoo.com").openSream())) { * System.out.println(b); * } * */ public static Iterable bytes(final InputStream is) { return new Iterable() { private final Iterator iterator = new ByteIterator(is); public Iterator iterator() { return iterator; } }; } /** * returns an Iterable<Byte> that scans over the bytes in a File * @param file File the file to scan * @return Iterable<Byte> the Iterable * *

    Example:

    * *
       *    for(byte b : bytes(new File("notepad.exe"))) {
       *      System.out.println(b);
       *    }
       * 
    */ public static Iterable bytes(final File file) { return new Iterable() { public Iterator iterator() { try { return new ByteIterator(new FileInputStream(file)); } catch (IOException e) { return new EmptyIterator(e.getMessage()); } } }; } private static class CharIterator implements Iterator { IOException exception = null; Reader reader; char next; boolean have = false; private CharIterator(Reader reader) { this.reader = reader; } public boolean hasNext() { if (have) { return true; } else if (reader == null) { return false; } else { try { int input = reader.read(); if (input < 0) { close(); } else { have = true; next = (char)input; return true; } } catch (IOException ex) { exception = ex; close(); } return reader != null; } } public Character next() { if (!hasNext()) { throw exception == null ? new NoSuchElementException() : new NoSuchElementException(exception.getMessage()); } have = false; return next; } public void remove() { throw new UnsupportedOperationException(); } private void close() { if (reader != null) { try { reader.close(); } catch (Exception e) {} } reader = null; } protected void finalize() { close(); } } /** * returns an Iterable<Character> enclosure that scans over the characters returned by Reader * @param reader Reader the reader to scan * @return Iterable<Character> the Iterable enclosure * * The Iterator returned by the Iterable is a singleton; * you cannot expect to get a fresh Iterator by calling * iterator() several times. *
    * Usage example:

    * * * for(char c : chars(new InputStreamReader(new java.net.URL("http://yahoo.com").openSream()))) { * System.out.println("[" + c + "]"); * } * */ public static Iterable chars(final Reader reader) { return new Iterable() { private final Iterator iterator = new CharIterator(reader); public Iterator iterator() { return iterator; } }; } /** * returns an Iterable<Character> that scans over the characters in a File * @param file File the file to scan * @return Iterable<Character> the Iterable *
    * Usage example:

    * * * for(char c : bytes(new File("readme.html"))) { * System.out.println("[" + c + "]"); * } * */ public static Iterable chars(final File file) { return new Iterable() { public Iterator iterator() { try { return new CharIterator(new FileReader(file)); } catch (IOException e) { return new EmptyIterator(e.getMessage()); } } }; } private static class LineIterator implements Iterator { LineNumberReader lr; IOException exception = null; String next; boolean have = false; private LineIterator(Reader reader) { lr = new LineNumberReader(reader); } public boolean hasNext() { if (have) { return true; } else if (lr == null) { return false; } else { try { next = lr.readLine(); if (next == null) { close(); } else { have = true; return true; } } catch (IOException ex) { exception = ex; close(); } return false; } } public String next() { if (!hasNext()) { throw exception == null ? new NoSuchElementException() : new NoSuchElementException(exception.getMessage()); } have = false; return next; } public void remove() { throw new UnsupportedOperationException(); } private void close() { if (lr != null) { try { lr.close(); } catch (Exception e) {} } lr = null; } protected void finalize() { close(); } } /** * returns an Iterable<String> enclosure that scans over the lines returned by Reader * @param reader Reader the reader to scan * @return Iterable<String> the Iterable enclosure * * The Iterator returned by the Iterable is a singleton; * you cannot expect to get a fresh Iterator by calling * iterator() several times. *
    * Usage example:

    * * * for(String line : chars(new LineNumberReader(new java.net.URL("http://yahoo.com").openSream()))) { * System.out.println(">" + line); * } * */ public static Iterable lines(final Reader reader) { return new Iterable() { private final Iterator iterator = new LineIterator(reader); public Iterator iterator() { return iterator; } }; } /** * returns an Iterable<String> that scans over the lines in a File * @param file File the file to scan * @return Iterable<String> the Iterable * * Usage example: * * * for(String line : lines(new File("readme.txt"))) { * System.out.println(">" + line); * } * */ public static Iterable lines(final File file) { return new Iterable() { public Iterator iterator() { try { return new LineIterator(new FileReader(file)); } catch (IOException e) { return new EmptyIterator(e.getMessage()); } } }; } /** * Returns an Iterable<File> that scans, recursively, through * the directory structure. * Traversal order is depth-first, preorder * * @param folder File starting directory * @return Iterable<File> the tree scanner * * Usage examples: * * * for(File subfolder : tree(new File("."))) { * System.out.println(subfolder.getCanonicalPath()); * } * * for(File folder : tree(new File("."))) { * System.out.println(file.getCanonicalPath()); * * for (File file : files(folder)) { * System.out.println(" " + file.getName()); * } * } * */ public static Iterable tree(final File folder) { return new Iterable() { public Iterator iterator() { return FolderIterator.preorder(folder); } }; } /** * Returns an Iterable<File> that scans, recursively, through * the directory structure. * Traversal order is depth-first, preorder * * @param folder File starting directory * @return Iterable<File> the tree scanner * * Usage examples: * * * for(File subfolder : tree(new File("."))) { * System.out.println(subfolder.getCanonicalPath()); * } * * for(File folder : tree(new File("."))) { * System.out.println(file.getCanonicalPath()); * * for (File file : files(folder)) { * System.out.println(" " + file.getName()); * } * } * */ public static Iterable tree(final File folder, final FileFilter filter) { return new Iterable() { public Iterator iterator() { return FolderIterator.preorder(folder, filter); } }; } /** * Returns an Iterable<File> that scans, recursively, * through the directory structure. * * Traversal order is depth-first, postorder * * @param folder File starting directory * @return Iterable<File> the tree scanner * * Usage examples: * * * for(File subfolder : treePostorder(new File("."))) { * System.out.println(subfolder.getCanonicalPath()); * } * * for(File folder : treePostorder(new File("."))) { * System.out.println(file.getCanonicalPath()); * * for (File file : files(folder)) { * System.out.println(" " + file.getName()); * } * } * */ public static Iterable treePostorder(final File folder) { return new Iterable() { public Iterator iterator() { return FolderIterator.postorder(folder); } }; } /** * Returns an Iterable<File> that scans all files in the folder * @param folder File directory to scan * @return Iterable<File> the scanner *
    * Usage example:

    * * * for (File file : files(new File(".")) { * System.out.println(file.getName()); * } * */ public static Iterable files(final File folder) { return Arrays.asList(listFiles(folder)); } } PK \>K2.9'com/myjavatools/lib/FolderIterator.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)FileIterator.java 5.0 02/09/05 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib; import java.util.*; import java.io.File; import java.io.FileFilter; /** * FolderIterator is an Iterator that walks over the tree of * subfolders in a folder * Traversal order is depth-first; can be preorder or postorder. * To do breadth-first, we would need a queue; you are welcome to * implement it - I do not remember ever requiring breadth-first * traversal order for file folders since the time I learned about * file folders, which was long ago. * * @version 5.0, 02/10/05 * * @see java.util.Iterator * @see java.util.File * @see Iterators * @since 5.0 */ final class FolderIterator implements Iterator { private File self; private final Iterator outerIterator; private Iterator current = null; private FileFilter filter; private final boolean preorder; private FolderIterator(final File folder, boolean preorder) { this(folder, Files.DIRECTORY_FILTER, preorder); } private FolderIterator(final File folder, FileFilter filter, boolean preorder) { this.self = folder; this.filter = filter; this.preorder = preorder; this.outerIterator = Arrays.asList(folder.listFiles(filter)). iterator(); } private static FileFilter makeDirectoryFilter(final FileFilter filter) { return new FileFilter() { public boolean accept(File file) { return file.isDirectory() && filter.accept(file); } }; } /** * returns a FolderIterator to walk through directory tree, * depth-first, preorder * * @param folder File * @return FolderIterator */ public static FolderIterator preorder(File folder) { return new FolderIterator(folder, true); } /** * returns a FolderIterator to walk through directory tree, * depth-first, preorder, accepting only files that * FileFilter filter accepts. * * @param folder File * @param FileFilter filter * @return FolderIterator */ public static FolderIterator preorder(File folder, FileFilter filter) { return new FolderIterator(folder, makeDirectoryFilter(filter), true); } /** * returns a FolderIterator to walk through directory tree, * depth-first, postorder * * @param folder File * @return FolderIterator */ public static FolderIterator postorder(File folder) { return new FolderIterator(folder, false); } /** * returns a FolderIterator to walk through directory tree, * depth-first, postorder, accepting only files that * FileFilter filter accepts. * * @param folder File * @param FileFilter filter * @return FolderIterator */ public static FolderIterator postorder(File folder, FileFilter filter) { return new FolderIterator(folder, makeDirectoryFilter(filter), false); } /** * Returns true if the iterator has more elements to scan. * * @return true if the iterator has more elements. */ public boolean hasNext() { if (preorder && self != null) { return true; } return haveSubtree() || self != null; } private boolean haveSubtree() { while (current == null || !current.hasNext()) { if (outerIterator.hasNext()) { current = new FolderIterator(outerIterator.next(), filter, preorder); } else { return false; } } return true; } /** * Returns the next element in the iteration. * * @return the next element in the iteration. * @todo Implement this java.util.Iterator method */ public File next() { if (preorder && self != null) { return self(); } else if (haveSubtree()) { return current.next(); } else if (!preorder) { return self(); } throw new NoSuchElementException(); } private File self() { File result = self; self = null; return result; } /** * Removes from the underlying collection the last element returned by the * iterator (optional operation). */ public void remove() { throw new UnsupportedOperationException(); } } PK 0`(com/myjavatools/lib/FormattedWriter.java/** *

    Title: MyJavaTools: Formatted File Output

    *

    Description: A typical formatted file consists of head, body and tail. * Body typicaly consists of repeating entries. This class does the output of this kind of files. * * Good for Java 5.0 and up.

    *

    Copyright: This is public domain; * The right of people to use, distribute, copy or improve the contents of the * following may not be restricted.

    * * @version 5.0 * @author Vlad Patryshev */ package com.myjavatools.lib; import java.io.*; import java.text.MessageFormat; public class FormattedWriter { MessageFormat head = null; MessageFormat body = null; MessageFormat tail = null; Writer writer = null; /** * Creates a writer that formats its output according to the format specified * * @see #FormattedWriter(Writer,String,String,String) * * @param writer the writer that outputs the formatted contents * @param format head format string * *

    Example
    * * String format = "Copyright (c) {0} {1}\r\n\r\n" +
    *         "{2}\r\n";
    *
    * FileFormat ff = new FileFormat(new FileWriter("readme.txt"), format);
    * ff.write("George Rasputin", "" + new Date().getYear(), "This is a stub for future readme text");
    *
    *

    This code will produce something like this:
    * Copyright (c) George Rasputin 2004
    *
    * This is a stub for future readme text
    *
    */ public FormattedWriter(Writer writer, String format) { this.writer = writer; head = format == null ? null : new MessageFormat(format); } /** * Creates a writer that formats its output according to head, body and tail formats specified * * @param writer the writer that outputs the formatted contents * @param head format string for the file head * @param body format string for (repeating) entries of the file body * @param tail format strings for the file tail * *

    Example
    * * String head = "/*\r\n Resource Data for package {0} in project {1}\r\n/*\r\n" +
    *         "class ResourceData {\r\n";
    * String body = " public String {0} = \"{1}\";\r\n";
    * String tail = "}\r\n";
    *
    * FileFormat ff = new FileFormat(new FileWriter("resource.java", head, body, tail);
    * ff.open(packageName, "My Cool Project");
    * Properties p = ...;
    * for (Enumeration i = p.keys(); i.hasMoreElements();) {
    *   String key = i.nextElement().toString();
    *   ff.write(new String[] {key, p.getProperty(key, "undef"});
    * }
    * ff.close();
    *

    This code will produce something like this:
    * /*
    * Resource Data for package com.my.package in project My Cool Project
    * */
    * class ResourceData {
    *   String dialogTitle = "Romeo vs Juliet";
    *   String label1 = "One of unmentionable major copyrighted labels";
    *   String size = "100x200";
    * }
    */ public FormattedWriter(Writer writer, String head, String body, String tail) { this(writer, head); this.body = body == null ? null : new MessageFormat(body); this.tail = tail == null ? null : new MessageFormat(tail); } /** * Creates a writer that formats its output according to the format specified * * @see #FormattedWriter(Writer,String) * * @param os output stream that outputs the formatted contents * @param format head format string */ public FormattedWriter(OutputStream os, String format) { this(new OutputStreamWriter(os), format); } /** * Creates a writer that formats its output according to head, body and tail formats specified * * @see #FormattedWriter(Writer,String,String,String) * * @param os output stream that outputs the formatted contents * @param head format string for the file head * @param body format string for (repeating) entries of the file body * @param tail format strings for the file tail */ public FormattedWriter(OutputStream os, String head, String body, String tail) { this(new OutputStreamWriter(os), head, body, tail); } /** * Gets head format string * @return head format string */ public MessageFormat getHead() { return head; } /** * Gets body format string * @return body format string */ public MessageFormat getBody() { return body; } /** * gets tail format string * @return tail format string */ public MessageFormat getTail() { return tail; } /** * Opens formatted output * @param args arguments for the head format * @throws IOException if write operation failes */ public void open(Object[]args) throws IOException { writer.write(head.format(args)); } /** * Opens formatted output * @param arg the only argiment for the head format * @throws IOException if write operation fails */ public void open(Object arg) throws IOException { writer.write(head.format(new Object[] {arg})); } /** * Opens formatted output, no arguments for head format * @throws IOException */ public void open() throws IOException { writer.write(head.format(null)); } /** * Writes a body string to formatted output * * @param args arguments for body format * @throws IOException if write operation fails * * Note. If body format is missing (then there is only head format), * then head format is applied to the arguments, the result of formatting is * written to the output, and the writer is closed. */ public void write(Object[]args) throws IOException { if (body != null) { writer.write(body.format(args)); } else { open(args); close(); } } /** * Writes an arbitrary string to (generally speaking) formatted output * * @param s the string to output * @throws IOException if write operation fails * * This skips any formatting; the string is just sent to output "as is". */ public void write(String s) throws IOException { writer.write(s); } /** * Writes the tail to formatted output and closes it * * @param args arguments for tail format * @throws IOException if write operation fails * * Note. if there is no tail format, the output just closes. */ public void close(Object[]args) throws IOException { if (tail != null) { writer.write(tail.format(args)); } writer.close(); } /** * Writes the tail to formatted output and closes it * * @throws IOException if write operation fails */ public void close() throws IOException { close(null); } } PK 4|b com/myjavatools/lib/Strings.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Strings.java 5.0 11/15/04 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib; import java.io.*; import java.text.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import static com.myjavatools.lib.human.Logical.*; import static com.myjavatools.lib.foundation.Objects.*; public abstract class Strings { /** * CharSequence version of indexOf * * @param s CharSequence * @param c char * @param fromIndex int * @return int * * see java.lang.String#indexOf() for description */ public static int indexOf(CharSequence s, char c, int fromIndex) { for (int i = fromIndex; i < s.length(); i++) { if (s.charAt(i) == c) return i; } return -1; } /** * CharSequence version of indexOf * * @param s CharSequence * @param c char * @return int * * see java.lang.String.indexOf(char) for description */ public static int indexOf(CharSequence s, char c) { return indexOf(s, c, 0); } /** * CharSequence version of lastIndexOf * * @param s CharSequence * @param c char * @return int * * see java.lang.String.lastIndexOf(char) for description */ public static int lastIndexOf(CharSequence s, char c) { for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == c)return i; } return -1; } /** * CharSequence version of indexOf * * @param sequence CharSequence * @param subsequence CharSequence * @param fromIndex int * @return int * * see java.lang.String.indexOf(String) for description */ public static int indexOf(CharSequence sequence, CharSequence subsequence, int fromIndex) { if (subsequence.length() == 0) return fromIndex; char c0 = subsequence.charAt(0); int subLength = subsequence.length(); int lastIndex = sequence.length() - subsequence.length(); for (int i = indexOf(sequence, c0, fromIndex); 0 <= i && i <= lastIndex; i = indexOf(sequence, c0, i+1)) { if (startsWith(sequence.subSequence(i, i + subLength), subsequence)) { return i; } } return -1; } /** * CharSequence version of indexOf * * @param sequence CharSequence * @param subsequence CharSequence * @return int * * see java.lang.String.indexOf(String) for description */ public static int indexOf(CharSequence sequence, CharSequence subsequence) { return indexOf(sequence, subsequence, 0); } /** * CharSequence version of startsWith * * @param sequence CharSequence * @param subsequence CharSequence * @return boolean * * see String.starstWith(String) for description */ public static boolean startsWith(CharSequence sequence, CharSequence subsequence) { if (sequence.length() < subsequence.length()) { return false; } for (int i = 0; i < subsequence.length(); i++) { if (sequence.charAt(i) != subsequence.charAt(i)) { return false; } } return true; } /** * Writes CharSequence to Writer (Hello, Sun! Ever heard of CharSequence class?) * * @param writer Writer * @param cs CharSequence * @throws IOException */ public static void write(Writer writer, CharSequence cs) throws IOException { if (cs == null) return; for (int i = 0; i < cs.length(); i++) { writer.write(cs.charAt(i)); } } /** * Checks whether a CharSequence does not contain anything except whitespaces and the like. * * @param s the sequence to check * @return true if empty * *

    Examples: *
  • isAlmostEmpty(""), isAlmostEmpty(null), isAlmostEmpty("\n \r \n") all return true;
  • *
  • isAlmostEmpty("."), isAlmostEmpty("Contains data!") returns false.
  • */ public static boolean isAlmostEmpty(CharSequence s) { if (isEmpty(s)) return true; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) > ' ') return false; } return true; } /** * Checks whether a character is a latin letter. * * @param c character to check * @return true if it is so * *

    Examples: *
  • isAlpha('a'), isAlpha('O'), isAlpha('I'), isAlpha('l') return true;
  • *
  • isAlpha('+'), isAlpha('0'), isAlpha('|'), isAlpha('1') return false.
  • */ public static boolean isAlpha(char c) { return Character.isJavaIdentifierStart(c); } /** * Checks whether a CharSequence contains any latin letters. * * @param s CharSequence to check * @return true if it is so * *

    Examples: *
  • hasAlpha("a"), hasAlpha("2OO2"), hasAlpha("This is a string") return true;
  • *
  • hasAlpha("+"), hasAlpha("1900"), hasAlpha("|1!*") return false.
  • */ public static boolean hasAlpha(CharSequence s) { for (int i = 0; i < s.length(); i++) { if (isAlpha(s.charAt(i))) return true; } return false; } /** * Counts the number of occurrences of char c in CharSequence s. * * @param s the string to scan * @param c the character to count * @return the number of occurrences * *

    Example: *
  • countChar("Goodness me, the clock has struck", 'o') returns 3.
  • */ public static int countChar(CharSequence s, char c) { int n = 0; for (int i = indexOf(s, c); i >= 0; i=indexOf(s, c, i+1)) { n++; } return n; } /** * Calculates how many lines the text contains. * Lines are supposed to be separated by '\n' character. * * @param s the CharSequence with text * @return number of lines in the string (separated by '\n') * *

    Examples: *
  • textHeight("One\nTwo\nThree") returns 3;
  • *
  • textHeight("\nOne\nTwo\nThree\n") returns 5.
  • */ public static int textHeight(CharSequence s) { return countChar(s, '\n') + 1; } /** * Calculates how many horizontal lines will the text take in a textarea. * This is the maximum line length for all lines in the text. * Lines are separated by '\n' character. * * @param s the CharSequence with text * @return maximum line length in the text * *

    Example: *
  • textWidth("One\nTwo\nThree") returns 5.
  • */ public static int textWidth(CharSequence s) { int n = 1; int curPos = 0; while (curPos < s.length()) { int nextPos = indexOf(s, '\n', curPos); if (nextPos < 0) nextPos = s.length(); if (n < nextPos - curPos) n = nextPos - curPos; curPos = nextPos+1; } return n; } /** * Calculates the number of words in the CharSequence. * This is just the number of tokens separated by default separators. * * @param s the CharSequence to analyze * @return number of words * *

    Examples: *
  • wordCount("This is life!") returns 3;
  • *
  • wordCount("C'est la vie !") returns 4, but for a wrong reason.
  • */ public static int wordCount(CharSequence s) { return (new StringTokenizer(s.toString())).countTokens(); } /** * Counts leading spaces in a char sequence * * @param s * @return number of leading spaces * *

    Example: *
  • countLeadingSpaces(" this is a string ") returns 1.
  • */ public static int countLeadingSpaces(CharSequence s) { int l = s.length(); int n = 0; while (n < l && s.charAt(n) == ' ') n++; return n; } /** * Counts trailing spaces in a char sequence * @param s * @return number of trailing spaces * *

    Example: *
  • countTrailingSpaces(" this is a string ") returns 3.
  • */ public static int countTrailingSpaces(CharSequence s) { int l = s.length(); int n = 0; while (n < l && s.charAt(l - n - 1) == ' ') n++; return n == s.length() ? 0 : n; } /** * Fills a string with a character * * @param c * @param n * @return a new string consisting of character c repeated n times * *

    Example: *
  • fill("*", 10) returns "**********".
  • */ public static String fill(char c, int n) { char[] data = new char[n]; Arrays.fill(data, c); return new String(data); } /** * "fast int to string hex" conversion array */ private static final String[] HEX = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff", }; /** * Converts a byte to hex string. * * @param b the byte * @return b representation as a two-character hex string * *

    Example: *
  • toHex(155) returns "9b".
  • */ public static String toHex(byte b) { int i = b; return HEX[(i&255)]; } /** * Converts an integer to hex string. It is the same as Integer.toHexString(). * * @param i the integer * @return i representation as a hex string * *

    Example: *
  • toHex(1234) returns "4d2".
  • */ public static String toHex(int i) { return Integer.toHexString(i); } /** * Converts a char to hex string * * @param ch the char * @param up if true, use upper case, otherwise lower * @return i representation as a four-character hex string * *

    Examples: *
  • toHex('\u005cu12bc', true) returns "12BC";
  • *
  • toHex('\u005cu00af', false) returns "00af".
  • */ public static String toHex(char ch, boolean up) { String hex = "0000" + Integer.toHexString(ch); if (up) hex = hex.toUpperCase(); return hex.substring(hex.length() - 4); } /** * Converts a char to hex string * * @param ch the char * @return a four-character string (lower case) * *

    Example: *
  • toHex('\u005cu00af') returns "00af".
  • */ public static String toHex(char ch) { return toHex(ch, false); } /** * Converts a CharSequence to hex string (character by character) * * @param s the CharSequence * @param up if true, use upper case, otherwise lower * @return s representation as a hex string * *

    Examples: *
  • toHex("kl\u005cu12bc", true) returns "006B006C12BC";
  • *
  • toHex("kl\u005cu12bc", true) returns "006b006c12bc".
  • */ public static String toHex(CharSequence s, boolean up) { StringBuffer b = new StringBuffer(); for (int i = 0; i < s.length(); i++) { b.append(toHex(s.charAt(i), up)); } return b.toString(); } /** * Converts a character to its Java octal encoding format: \\o[o][o] * * @param c the character * @return a string * *

    Example: *
  • toJavaOctalEncoding('\n') returns "\\12".
  • */ public static String toJavaOctalEncoding(char c) { return "\\" + Integer.toString(c, 8); } /** * Converts a character to its Java hex encoding format: \\uxxxx * * @param c the character * @return a string, encoded c representation * *

    Example: *
  • toJavaHexEncoding('\u005cu00af') returns "\\u00af".
  • */ public static String toJavaHexEncoding(char c) { return "\\u" + toHex(c); } /** * Converts a character to its Java hex encoding format: \\uxxxx * * @param c the character * @param up if true, use upper case, otherwise lower * @return a string, encoded c representation * *

    Example: *
  • toJavaHexEncoding('\u005cu00af', false) returns "\\u00af".
  • */ public static String toJavaHexEncoding(char c, boolean up) { return "\\u" + toHex(c, up); } /** * Converts a character to how it should be represented in properties files * * @param c the character * @param up if true, use upper case, otherwise lower * @return a string, encoded c representation * *

    Examples: *
  • toPropertiesEncoding('\u005cu00af', false) returns "\\u00af";
  • *
  • toPropertiesEncoding('\u005cu00af', true) returns "\\u00AF";
  • *
  • toPropertiesEncoding('a', false) returns "a".
  • */ public static String toPropertiesEncoding(char c, boolean up) { return (c > 0x7f || c < ' ') ? toJavaHexEncoding(c, up) : ("" + c); } /** * Converts a character to how it should be represented in properties files * * @param c the character * @return a string, encoded c representation * *

    Examples: *
  • toPropertiesEncoding('\u005cu00af') returns "\\u00af";
  • *
  • toPropertiesEncoding('a') returns "a".
  • */ public static String toPropertiesEncoding(char c) { return toPropertiesEncoding(c, false); } /** * Characters that should be escaped in Java or C code * * {@value} */ public static final String ESCAPEE = "\\\"\'\n\r\t\f\b"; /** * Characters used in escapes * * {@value} */ public static final String ESCAPED = "\\\"'nrtfb"; /** * Checks whether a character needs encoding in Java * * @param c the character * @return true if so * *

    Examples: *
  • needsEncoding('\u005cu00af') returns true;
  • *
  • needsEncoding('a') returns false.
  • */ public static boolean needsEncoding(char c) { return ESCAPEE.indexOf(c) >= 0 || c < ' ' || c > 0x7f; } /** * Converts a character to its Java encoding (hex or escaped or intact) * * @param c the character * @param up if true, use upper case, otherwise lower * @param escape if true, escape escapable characters * @return a string with a proper Java representation of the character c * *

    Examples: *
  • toJavaEncoding('\u005cu00af', false, false) returns "\\u00af";
  • *
  • toJavaEncoding('\u005cu000a', true, true) returns "\\n";
  • *
  • toJavaEncoding('\u005cu000e', true, true) returns "\\16";
  • *
  • toJavaEncoding('a', true, true) returns "a".
  • */ public static String toJavaEncoding(char c, boolean up, boolean escape) { int i = escape ? ESCAPEE.indexOf(c) : -1; return (i >= 0) ? ("\\" + ESCAPED.charAt(i)) : (c < ' ') ? toJavaOctalEncoding(c) : (c > 0x7f) ? toJavaHexEncoding(c, up) : ("" + c); } /** * Converts a character to its Java encoding (hex or escaped or intact) * * @param c the character * @param up if true, use upper case, otherwise lower * @return a string with a proper Java representation of the character c * *

    Examples: *
  • toJavaEncoding('\u005cu00af', false) returns "\\u00af";
  • *
  • toJavaEncoding('\u005cu00af', true) returns "\\u00AF";
  • *
  • toJavaEncoding('\u005cu000a', true) returns "\\n";
  • *
  • toJavaEncoding('\u005cu000e', true) returns "\\16";
  • *
  • toJavaEncoding('a', true) returns "a".
  • */ public static String toJavaEncoding(char c, boolean up) { return toJavaEncoding(c, up, true); } /** * Converts a character to its Java encoding (hex or escaped or intact) * * @param c the character * @return a string with a proper Java representation of the character c * *

    Examples: *
  • toJavaEncoding('\u005cu00af') returns "\\u00af";
  • *
  • toJavaEncoding('\u005cu000a') returns "\\n";
  • *
  • toJavaEncoding('\u005cu000e') returns "\\16";
  • *
  • toJavaEncoding('a') returns "a".
  • */ public static String toJavaEncoding(char c) { return toJavaEncoding(c, false); } /** * Converts a character to its C encoding (hex or escaped or intact) * * @param c the character * @return a string with a proper C language representation of the character c * *

    Examples: *
  • toCEncoding('\u005cuabcd') returns "\\xabcd";
  • *
  • toCEncoding('\u005cu00af') returns "\\xaf";
  • *
  • toCEncoding('\u005cu000a') returns "\\n";
  • *
  • toCEncoding('a') returns "a".
  • */ public static String toCEncoding(char c) { int i = ESCAPEE.indexOf(c); return (i >= 0) ? ("\\" + ESCAPED.charAt(i)) : (c < ' ' || c > 0x7f) ? ("\\x" + Long.toHexString(c)) : ("" + c); } /** * Checks whether a CharSequence needs encoding in Java * * @param s the CharSequence * @return true if so * *

    Examples: *
  • needsEncoding("Feliz Ao Nuevo") returns true;
  • *
  • needsEncoding("Feliz Navedad") returns false.
  • */ public static boolean needsEncoding(CharSequence s) { if (s == null) return false; for (int i = 0; i < s.length(); i++) { if (needsEncoding(s.charAt(i))) return true; } return false; } /** * Converts a CharSequence to its Java encoding (hex or escaped or intact, per char) * * @param s the CharSequence * @param up if true, use upper case, otherwise lower * @param escape if true, escape escapable characters * @return the encoded string * *

    Examples: *
  • toJavaEncoding("\nFeliz Ao Nuevo\n", true, false) * returns "\u005cu000AFeliz \u005cu00A4o Nuevo\u005cu000A";
  • *
  • toJavaEncoding("\nFeliz Ao Nuevo\n", true, true) * returns "\\nFeliz \u005cu00A4o Nuevo\\n";
  • *
  • toJavaEncoding("\nFeliz Ao Nuevo\n\0", false, true) * returns "\\nFeliz \u005cu00a4o Nuevo\\n\\0".
  • */ public static String toJavaEncoding(CharSequence s, boolean up, boolean escape) { if (!needsEncoding(s)) return s.toString(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < s.length(); i++) { buf.append(toJavaEncoding(s.charAt(i), up, escape)); } return buf.toString(); } /** * Converts a CharSequence to its Java encoding (hex or escaped or intact, per char) * * @param s the CharSequence * @param up if true, use upper case, otherwise lower * @return the encoded string * *

    Examples: *
  • toJavaEncoding("\nFeliz Ao Nuevo\n", true) * returns "\nFeliz \u005cu00A4o Nuevo\n";
  • *
  • toJavaEncoding("\nFeliz Ao Nuevo\n\0", false) * returns "\\nFeliz \u005cu00a4o Nuevo\\n\\0".
  • */ public static String toJavaEncoding(CharSequence s, boolean up) { return toJavaEncoding(s, up, true); } /** * Converts a CharSequence to its Java encoding (hex or escaped or intact, per char) * * @param s the CharSequence * @return the encoded string * *

    Example: *
  • toJavaEncoding("\nFeliz Ao Nuevo\n\0") * returns "\\nFeliz A\u005cu00f1o Nuevo\\n\\0".
  • */ public static String toJavaEncoding(CharSequence s) { return toJavaEncoding(s, false); } /** * Converts a CharSequence to its C encoding * * @param s the CharSequence * @return the encoded string * *

    Example: *
  • toCEncoding("\nFeliz Ao Nuevo\n") * returns "\\nFeliz A\\x00f1o Nuevo\\n".
  • */ public static String toCEncoding(CharSequence s) { if (!needsEncoding(s)) return s.toString(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < s.length(); i++) { buf.append(toCEncoding(s.charAt(i))); } return buf.toString(); } /** * Converts a character to its SGML numeric encoding * * @param c the character * @return a string with the representation of c as * "Numeric Character Reference" in SGMLese * *

    Example: *
  • toSgmlEncoding('\n') * returns "&#10;".
  • */ public static String toSgmlEncoding(char c) { return c > 0x20 || c == 0x9 || c == 0xa || c == 0xd ? "&#" + (int)c + ";" : "?"; } /** * Encodes a character by SGML rules * It can be a hex representation * @param c the character * @return the string with either Predefined Entity, Numeric Character Reference, * or null if no entity could be found * *

    Examples: *
  • sgmlEntity('\u005c60ab') returns "&#24747;" (that is, Numeric Character Reference);
  • *
  • sgmlEntity('<') returns "&lt;" (that is, Predefined Entity);
  • *
  • sgmlEntity('&') returns "&lt;" (that is, Predefined Entity);
  • *
  • sgmlEntity('X') returns null";
  • *
  • sgmlEntity('\n') returns null".
  • */ public static String sgmlEntity(char c) { return c == '<' ? "<" : c == '>' ? ">" : c == '\'' ? "'" : c == '\"' ? """ : c == '&' ? "&" : c == ']' ? "]" : (c < '\u0020' && c != '\n' && c != '\r' && c != '\t') || c > '\u0080' ? toSgmlEncoding(c) : null; } /** * Encodes a CharSequence by SGML rules * (using predefined entities and numeric character encodings when necessary) * @param s the original CharSequence * @return the encoded string * *

    Example: *
  • toSgmlEncoding("Feliz Ao Nuevo\n") * returns "&lt;i&gt;Feliz A&#164;o Nuevo&lt;/i&gt;\n".
  • */ public static String toSgmlEncoding(CharSequence s) { if (isEmpty(s)) return s.toString(); StringBuffer buffer = new StringBuffer(s.length() * 2); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); String entity = sgmlEntity(c); if (entity == null) { buffer.append(c); } else { buffer.append(entity); } } return buffer.toString(); } //**************************************************** // html-encode all non-ascii chars /** * encodes a CharSequence into an HTML-acceptable format * * @param s CharSequence original CharSequence * @return String encoded string * * All non-ascii characters are replaced with their &# representation; other * characters are left intact. * *

    Example: *
  • htmlEncode("Feliz Ao Nuevo\n") * returns "Feliz A&#164;o Nuevo\n".
  • */ public static String htmlEncode(CharSequence s) { if (isEmpty(s)) return ""; StringBuffer out = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int k = c; if (c > 0x100) { out.append("&#" + k + ";"); } else { out.append(c); } } return out.toString(); } /** * Converts a char array to a readable string. * (By Replacing potentially unreadables characters with '.') * * @param data original char array * @param beginIndex where to start * @param endIndex where to end (before this position) * @return the string with unreadable chars replaced * *

    Example: *
  • toReadable("\tHola seor!\n".toCharArray(), 2, 12) * will return "..Hola se.or!.".
  • */ public static String toReadable(char[] data, int beginIndex, int endIndex) { StringBuffer buf = new StringBuffer(data.length); for (int i = beginIndex; i < data.length && i < endIndex; i++) { char c = data[i]; if (c < ' ' || c > 127) c = '.'; buf.append(c); } return buf.toString(); } /** * Converts a CharSequence to a readable string. * (By Replacing potentially unreadables characters with '.') * * @param s original CharSequence * @return the string with unreadable chars replaced * *

    Example: *
  • toReadable("\tHola seor!\n") will return "..Hola se.or!.".
  • */ public static String toReadable(CharSequence s) { return toReadable(s.toString().toCharArray(), 0, s.length()); } /** * Hexadecimal dump of a byte array. * Produces neatly arranged lines of bot hex and ascii representation of bytes * from the array. * * @param data the data array * @return the hex dump string * *

    Example: *
  • hexDump(new byte[] {1, 'a', 'b', '\n', 'c'}) will return * "\r\n01 61 62 0a 63 | . a b . c\r\n".
  • */ public static String hexDump(byte[] data) { if (data == null || data.length == 0) return ""; StringBuffer out = new StringBuffer(); for (int i = 0; i < data.length; i+= 16) { out.append("\r\n"); out.append(toHex((byte)(i >> 8))); out.append(toHex((byte)(i ))); out.append(": "); for (int j = i; j < i + 16; j++) { out.append(j < data.length ? toHex(data[j]) : " "); out.append(" "); } out.append("| "); for (int j = i; j < i + 16 && j < data.length; j++) { byte b = data[j]; out.append(b >= ' ' ? (char)b : '\u00b7'); out.append(" "); } } out.append("\r\n"); return out.toString(); } /** * Hexadecimal dump of a char array * Produces neatly arranged lines of bot hex and ascii representation of bytes * from the array. * * @param data the data array * @return a string containing both hex and ascii representation of the data * *

    Example: *
  • hexDump(new char[] {1, 'a', 'b', '\n', 'c'}) will return
    * "\r\n0000: 0001 0061 0062 000a 0063 | .ab.c\r\n".
  • */ public static String hexDump(char[] data) { if (data == null || data.length == 0) return ""; StringBuffer out = new StringBuffer(); for (int i = 0; i < data.length; i+= 16) { out.append("\r\n"); out.append(i < 16 ? "000" : i < 256 ? "00" : i < 4096 ? "0" : ""); out.append(toHex(i)); out.append(": "); for (int j = i; j < i + 16; j++) { out.append(j >= data.length ? " " : toHex(data[j])); out.append(" "); } out.append("| "); out.append(toReadable(data, i, Math.min(i+16, data.length))); } out.append("\r\n"); return out.toString(); } /** * Hexadecimal dump of a CharSequence * Produces neatly arranged lines of bot hex and ascii representation of bytes * from the array. * * @param data the CharSequence * @return a string containing both hex and ascii representation of the data * *

    Example: *
  • hexDump("\u0001ab\nc") will return * "\r\n0001 0061 0062 000a 0063 | .ab.c".
  • */ public static String hexDump(CharSequence data) { return hexDump(data.toString().toCharArray()); } /** * Converts an array of chars to a readable hexadecimal form * * @param data the data array * @return a string that is basically a hex dump of the data * *

    Example: *
  • toHexReadable(new char[] {1, 'a', 'b', '\n', 'c'}) will return * "0001 0061 0062 000a 0063 \r\n".
  • */ public static String toHexReadable(char[] data) { if (data == null || data.length == 0) return ""; StringBuffer out = new StringBuffer(); for (int i = 0; i < data.length; i++) { out.append(toHex(data[i])); out.append(" "); if (i % 16 == 15 || i == data.length - 1) { out.append("\r\n"); } } return out.toString(); } /** * Converts an array of chars to a readable hexadecimal form * * @param data the data array * @param from beginning index * @param to ending index (not included) * @return a string that is basically a hex dump of the data * *

    Example: *
  • toHexReadable(new byte[] {1, 2, 48}, 1, 3) will return * "02 30 \r\n".
  • */ public static String toHexReadable(byte[] data, int from, int to) { if (data == null || data.length == 0) return ""; StringBuffer out = new StringBuffer(); int limit = Math.min(to, data.length); for (int i = from; i < limit; i++) { out.append(toHex(data[i])); out.append(" "); if (i % 16 == 15 || i == limit - 1) { out.append("\r\n"); } } return out.toString(); } /** * Converts an array of bytes to a readable hexadecimal form * * @param data the data array * @return a string that is basically a hex dump of the data * *

    Example: *
  • toHexReadable(new byte[] {1, 2, 48}) will return * "01 02 30 ".
  • */ public static String toHexReadable(byte[] data) { if (data == null) return ""; return toHexReadable(data, 0, data.length); } /** * Converts a CharSequence to a readable hexadecimal string * * @param s the data CharSequence * @return a string that is basically a hex dump of the data * *

    Example: *
  • toHexReadable("\u0001ab\nc") will return * "0001 0061 0062 000a 0063 \r\n".
  • */ public static String toHexReadable(CharSequence s) { if (isEmpty(s)) return ""; StringBuffer out = new StringBuffer(); for (int i = 0; i < s.length(); i++) { out.append(toHex(s.charAt(i))); out.append(" "); if (i % 16 == 15 || i == s.length() - 1) { out.append("\r\n"); } } return out.toString(); } /** * Perl operation join. * Concatenates a collection of (string representations of) objects * using a separator string to separate * * @param separator the separator CharSequence * @param collection the collection of objects to join * @return resulting string * *

    Examples:
    * * HashSet a = new HashSet();
    * List b = new ArrayList(); b.add("entry1"); b.add("entry2");
    *
  • join(", ", a) returns "";
  • *
  • join(", ", b) returns "entry1, entry2".
  • */ public static String join(CharSequence separator, Collection collection) { if (separator == null || collection == null) return ""; StringBuffer buf = new StringBuffer(); for (Object element : collection) { if (buf.length() > 0) buf.append(separator); buf.append(element); } return buf.toString(); } /** * Perl operation join. * Concatenates an array of (string representations of) objects * using a separator to separate * * @param separator the separator * @param what the array of objects to join * @return resulting string * *

    Examples:
    *
  • join(", ", new Long[] {1, 555}) * returns "1, 555";
  • *
  • join(" and ", new String[] {"Here", "there", "everywhere"}) * returns "Here and there and everywhere".
  • */ public static String join(CharSequence separator, T... what) { if (separator == null || what == null) return ""; StringBuffer buf = new StringBuffer(); for (T object : what) { if (object != null) { if (buf.length() > 0) { buf.append(separator); } buf.append(object.toString()); } } return buf.toString(); } /** * Perl operation split. * splits a source string into a collection of strings * * @param separator CharSequence separator character sequence * @param source CharSequence source character sequence * @return an Iterable<CharSequence> of extracted character sequences * * @see #join(CharSequence, Object[]) * see java.lang.String.split(String) * *

    Example:
    * *
  • split(":", "a:ab:abcde:") * returns a list containing four elements, "a", "ab", "abcde", "".
  • */ public static Iterable split(final CharSequence separator, final CharSequence source) { return new Iterable() { public Iterator iterator() { return new Iterator() { int pos = 0; public boolean hasNext() { return pos <= source.length(); } public void remove() { throw new UnsupportedOperationException(); } public CharSequence next() { int next = indexOf(source, separator, pos); if (next < 0) { next = source.length(); } CharSequence result = pos > next ? "" : source.subSequence(pos, next); pos = next + separator.length(); return result; } }; } }; } /** * Perl operation grep. * Extracts from a string array the strings that match a regexp * * @param source source array * @param regexp expression to match * @return a collection of matching character sequences from source * *

    Example:
    * *
  • grep(new String[] {"good", "bad", "ugly"}, "g.")) * returns a list containing two elements: "good", "ugly".
  • */ public static List grep(T[] source, CharSequence regexp) throws PatternSyntaxException { return grep(source, Pattern.compile(regexp.toString())); } /** * Perl operation grep. * Extracts from an array the char sequences that match a regexp * * @param source source array * @param regexp expression to match * @return a collection of matching character sequences * *

    Example:
    * *
  • grep(new String[] {"good", "bad", "ugly"}, Pattern.compile("g."))) * returns a list containing two elements: "good", "ugly".
  • */ public static List grep(T[] source, Pattern regexp) { ArrayList result = new ArrayList(); for (T element : source) { Matcher matcher = regexp.matcher(element); if (matcher.find()) { result.add(element); } } result.trimToSize(); return result; } /** * Replaces a subsequence in a char sequence with another subsequence * * @param where the string containing the substrings to replace * @param oldSubstring what to replace * @param newSubstring with what to replace * @param all if true, all (nonintersecting) substrings are replaced, * otherwise only one * @return resulting string * * @deprecated since 5.0; use replace() without boolean argument, or replaceAll() * * see java.lang.String.replaceAll(String,String) and java.lang.String.replaceFirst(String, String) * *

    Examples: *
  • replace("Bokonon loves you", "love", "hate", true) * returns "Bokonon hates you";
  • *
  • replace("All you need is love, love!", "me", false) * returns "All you need is me, love!".
  • */ public static String replace(CharSequence where, CharSequence oldSubstring, CharSequence newSubstring, boolean all) { if (where == null) return null; if (oldSubstring == null || newSubstring == null) return where.toString(); StringBuffer out = new StringBuffer(); int pos = 0; do { int newPos = indexOf(where, oldSubstring, pos); if (newPos < 0) break; out.append(where.subSequence(pos, newPos)); out.append(newSubstring); pos = newPos + oldSubstring.length(); } while (all); out.append(where.subSequence(pos, where.length())); return out.toString(); } /** * Replaces a subsequence in a char sequence with another subsequence * * @param where the string containing the substrings to replace * @param oldSubstring what to replace * @param newSubstring with what to replace * @return resulting string * * see java.lang.String.replaceAll(String,String) and java.lang.String.replaceFirst(String, String) * *

    Example: *
  • replace("All I need is love, love, love!", "You") * returns "All I need is You, You, You!".
  • */ public static String replaceAll(CharSequence where, CharSequence oldSubstring, CharSequence newSubstring) { return replace(where, oldSubstring, newSubstring, true); } /** * Replaces all instances of subsequence in a char sequence with another subsequence * * @param where the string containing the substrings to replace * @param oldSubstring what to replace * @param newSubstring with what to replace * @return resulting string * * see java.lang.String.replaceAll(String,String) and java.lang.String.replaceFirst(String, String) * *

    Example: *
  • replace("All you need is love, love!", "me") * returns "All you need is me, love!".
  • */ public static String replace(CharSequence where, CharSequence oldSubstring, CharSequence newSubstring) { return replace(where, oldSubstring, newSubstring, false); } /** * Extracts value from a char sequence of format NAME="VALUE" * * @param input sequence of the aforementioned format * @param name the name on the left side of '=' * @return the string value inside the quotes (quotes omitted) if the string * has the specified format; null utherwise * *

    Examples: *
  • extractValue("java.home=\"c:\\java\\jdk1.4.1\"\nx=\"abcd\"", "x") * returns "abcd";
  • *
  • extractValue("java.home=\|c:\\java\\jdk1.4.1\"\nx=\"abcd\"", "java.home") * returns "c:\\java\\jdk1.4.1".
  • */ public static String extractValue(CharSequence input, CharSequence name) { int iname = indexOf(input, name + "=\""); if (iname < 0) return null; int ivalue = iname + name.length() + 2; int ievalu = indexOf(input, '"', ivalue); if (ievalu < 0) return null; return input.subSequence(ivalue, ievalu).toString(); } /** * Packs bytes into a string * * @param from byte array * @return a string that consists of the same bytes, packed two per character * *

    Example: *
  • pack(new byte[] {0x23, 0x67, (byte)0xab, (byte)0xef}) * returns "\u2367\uabef".
  • */ public static String pack(byte[] from) { StringBuffer buffer = new StringBuffer((from.length + 1) / 2); char hibyte = 0; for (int i = 0; i < from.length / 2 * 2; i+=2) { buffer.append((char)((0xff00 & (from[i] << 8)) + ( 0xff & from[i+1]))); } if (from.length % 2 != 0) { buffer.append((char)(0xff & from[from.length - 1])); } return buffer.toString(); } /** * Unpacks bytes packed in the char sequence * * @see #pack(byte[]) * @param data the packed data * @return the unpacked data * *

    Example: *
  • unpack("\u2367\uabef") * returns new byte[] {0x23, 0x67, (byte)0xab, (byte)0xef}.
  • */ public static byte [] unpack(CharSequence data) { // The following method does not work for JDK 1.4; it seems like it replaces // "bad" UTF-16 characters with ff fe sequences. // return encode(string, "UTF-16BE"); byte[] result = new byte[data.length() * 2]; for (int i = 0; i < data.length(); i++) { int c = data.charAt(i); result[i * 2] = (byte)(c >> 8); result[i * 2 + 1] = (byte) c; } return result; } /** * Decodes (and unescapes) a Java string. * Replaces escape sequences with their corresponding character values * * @param string as presented in the source code * @return decoded string in "internal form" * *

    Examples: *
  • decodeJavaString("This is a string") returns "This is a string";
  • *
  • decodeJavaString("\\nFeliz \\u00A4o Nuevo\\n") * returns "\nFeliz Ao Nuevo\n".
  • */ public static String decodeJavaString(CharSequence string) { StringBuffer output = new StringBuffer(string.length() * 2); if (indexOf(string, '\\') < 0) { return string.toString(); } for (int i=0; i < string.length(); i++) { char ch = string.charAt(i); if (ch == '\\' && i < string.length() - 1) { // So, we have a backslash... int escapeIdx = ESCAPED.indexOf(string.charAt(i+1)); if (escapeIdx >= 0) { i++; ch = ESCAPEE.charAt(escapeIdx); } else if (i < string.length() - 5 && string.charAt(i + 1) == 'u') { //possible escape try { ch = (char)Integer.parseInt(string.subSequence(i+2, i+6).toString(), 16); i += 5; } catch (NumberFormatException nfe) { // Okay, okay, not a hex number... } } } output.append(ch); } return output.toString(); } /** * Encodes a char sequence using specified encoding * * @see list of Java encodings * * @param s char sequence to encode * @param encoding the name of encoding * @return encoded array of bytes * @throws IOException when something goes wrong with bytearray streams * @throws UnsupportedEncodingException when encoding is unknown * *

    Examples: *
  • encode("Ao Nuevo", "UTF8") * returns new byte[] {0x41, (byte)0xc3, (byte)0xb1, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f};
  • *
  • encode("Ao Nuevo", "MacRoman") * returns new byte[] {0x41, (byte)0x96, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}.
  • */ public static byte[] encode(CharSequence s, String encoding) throws IOException, UnsupportedEncodingException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Writer osw = new OutputStreamWriter(bos, encoding); write(osw, s); osw.close(); return bos.toByteArray(); } /** * Decodes a stream using specified encoding * * @see list of Java encodings * * @param is stream to decode * @param encoding the name of encoding * @return data decoded from the stream * @throws IOException when something goes wrong with bytearray streams * @throws UnsupportedEncodingException when encoding is unknown * */ public static String decode(InputStream is, String encoding) throws IOException, UnsupportedEncodingException { Reader isr = new InputStreamReader(is, encoding); StringBuffer result = new StringBuffer(); char[] readBuffer = new char[4096]; while (isr.ready()) { int l = isr.read(readBuffer); result.append(readBuffer, 0, l); } return result.toString(); } /** * Decodes an array of bytes using specified encoding * * @see list of Java encodings * * @param bytes byte array * @param encoding the name of encoding * @return decoded string * @throws IOException when something goes wrong with bytearray streams * @throws UnsupportedEncodingException when encoding is unknown * *

    Examples: *
  • decode(new byte[] {0x41, (byte)0xc3, (byte)0xb1, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}, "UTF8") * returns "Ao Nuevo";
  • *
  • encode( new byte[] {0x41, (byte)0x96, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}, "MacRoman") * returns "Ao Nuevo".
  • */ public static String decode(byte[] bytes, String encoding) throws IOException, UnsupportedEncodingException { return decode(new ByteArrayInputStream(bytes), encoding); } /** * zip (like in zip files) a string producing an array of bytes * * @param source the string to zip * @return bytes representing zipped data * @throws IOException when something goes wrong with streams * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 * *

    Example: *
  • zip2bytes("Hello World") * returns new byte[] {0x78, (byte)0xda, (byte)0xf3, 0x48, (byte)0xcd, (byte)0xc9, (byte)0xc9, 0x57, (byte)0x08, (byte)0xcf, 0x2f, (byte)0xca, 0x49, 0x01, 0x00, 0x18, 0x0b, 0x04, 0x1d, 0x00}.
  • */ public static byte[] zip2bytes(CharSequence source) throws IOException, UnsupportedEncodingException { if (source == null) return null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(bos, new Deflater(Deflater.BEST_COMPRESSION)); Writer osw = new OutputStreamWriter(dos, "UTF-8"); write(osw, source); osw.flush(); dos.finish(); bos.write(0); // Just to pad in case of, you know, odd number of bytes. osw.close(); byte[] result = bos.toByteArray(); return result; } /** * zips a char sequence to a string of lower-byte chars. * Does this: CharSequence -> UTF8 bytes -> zip -> bytes -> String * @param source char sequence to zip * @return string with zipped data * @throws IOException when something goes wrong with streams * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 * *

    Example: *
  • zip8bit("Hello World") * returns "x\u00da\u00f3H\u00cd\u00c9\u00c9W\b\u00cf/\u00caI\u0001\u0000\u0018\u000b\u0004\u001d\u0000".
  • */ public static String zip8bit(CharSequence source) throws IOException, UnsupportedEncodingException { return new String(zip2bytes(source)); } /** * zips a char sequence to a string. * Does this: CharSequence -> UTF8 bytes -> zip -> bytes -> High Unicode -> String * * @param source char sequence to zip * @return string with zipped data * @throws IOException when something goes wrong with streams * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 * *

    Example: *
  • zip("Hello World") * returns "\u78da\uf348\ucdc9\uc957\u08cf\u2fca\u4901\u0018\u0b04\u1d00".
  • */ public static String zip(CharSequence source) throws IOException, UnsupportedEncodingException { return pack(zip2bytes(source)); } /** * Unzips a stream. * Does this: stream -> unzip -> bytes -> UTF8 -> String * * @param zippedStream * @return string with unzipped data * @throws IOException when something goes fishy * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 */ public static String unzip(InputStream zippedStream) throws IOException, UnsupportedEncodingException { return decode(new InflaterInputStream(zippedStream), "UTF-8"); } /** * Unzips an array of bytes. * Does this: bytes -> unzip -> bytes -> UTF8 -> String * * @param zippedBytes * @return string with unzipped data * @throws IOException when something goes fishy * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 * *

    Example: *
  • unzip(new byte[] {0x78, (byte)0xda, (byte)0xf3, 0x48, (byte)0xcd, (byte)0xc9, (byte)0xc9, 0x57, 0x08, (byte)0xcf, 0x2f, (byte)0xca, 0x49, 0x01, 0x00, 0x18, 0x0b, 0x04, 0x1d, 0x00}) * returns "Hello World".
  • */ public static String unzip(byte[] zippedBytes) throws IOException, UnsupportedEncodingException { return unzip(new ByteArrayInputStream(zippedBytes)); } /** * Unzips a char sequence * Does this: CharSequence -> High Unicode bytes -> unzip -> bytes -> UTF8 -> String * * @param zipped * @return string with unzipped data * @throws IOException when something goes fishy * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 * *

    Example: *
  • unzip("\u78da\uf348\ucdc9\uc957\u08cf\u2fca\u4901\u0018\u0b04\u1d00") * returns "Hello World".
  • */ public static String unzip(CharSequence zipped) throws IOException, UnsupportedEncodingException { return unzip(unpack(zipped)); } /** * Calculates crc32 on a char sequence * @param data source char sequence * @return its crc32 * @throws IOException when something goes wrong with streams * @throws UnsupportedEncodingException when JDK forgets that it knows UTF8 * *

    Example: *
  • crc32("Hello World") * returns 2178450716l.
  • */ public static long crc32(CharSequence data) throws IOException, UnsupportedEncodingException { return Bytes.crc32(unpack(data)); } /** * Converts a map to string array, "key=value" * * @param map Map<K,V> the map to stringify * @return array of strings * *

    Example: *
  • Map map = new HashMap(); * map.put("PATH", "c:\java\bin"); * map.put("CLASSPATH", "c:\java\lib"); * toStrings(map) * returns new String[] {"PATH=c:\java\bin", "CLASSPATH=c:\java\lib"}.
  • * */ public static String[] toStrings(Map map) { if (map == null) return null; String[] result = new String[map.size()]; Set> entrySet = map.entrySet(); int i = 0; for(Map.Entry entry : entrySet) { result[i++] = entry.getKey().toString() + "=" + entry.getValue().toString(); } return result; } /** * Converts a List to string array, per element * * @param list List the expected list * @return array of strings * *

    Example: *
  • toStrings(Arrays.toList(new Object[] { 22, false, "wow"})) * returns new String[] {"22", "false", "wow"}.
  • * */ public static String[] toStrings(List list) { String[] result = new String[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i).toString(); } return result; } /** * Converts a Collection to string array, per element * * @param collection Collection the expected collection * @return array of strings * *

    Example: *
  • toStrings(Arrays.asList(22, false, "wow")) * returns new String[] {"22", "false", "wow"}.
  • * */ public static String[] toStrings(Collection collection) { String[] result = new String[collection.size()]; int i = 0; for (Object element : collection) { result[i++] = element.toString(); } return result; } /** * Converts an array to string array, per element * * @param array Object[] the expected array * @return array of strings, or null if input is not what expected * *

    Example: *
  • toStrings(new Object[] { new Integer(22), new Boolean(false), "wow"}) * returns new String[] {"22", "false", "wow"}.
  • * */ public static String[] toStrings(Object[] array) { String[] result = new String[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].toString(); } return result; } /** * Converts an array to string array, per element * * @param object the expected array * @return array of strings, or null if input is not what expected * @deprecated since 5.0; use typed versions * *

    Example: *
  • toStrings(new Object[] { new Integer(22), new Boolean(false), "wow"}) * returns new String[] {"22", "false", "wow"}.
  • * */ public static String[] toStrings(Object object) { if (object == null) return null; if (object instanceof Map) { return toStrings((Map)object); } else if (object instanceof List) { return toStrings((List)object); } else if (object instanceof Collection) { return toStrings((Collection)object); } else if (object instanceof Object[]) { return toStrings((Object[])object); } else { return null; } } /** * Stringifies a Throwable, together with is stack trace. * @param e the throwable to convert to string * @return the string representation * *

    Example: *

    * try {
    *   String s = null;
    *   s.toString();
    * } catch (Exception e) {
    *   System.out.println(toString(e));
    * }
    prints *

    java.lang.NullPointerException
    *         at com.myjavatools.util.TestStrings
    */ public static String toString(Throwable e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); return baos.toString(); } /** * Formats string with parameter(s) * * @param fmtString * @param parameters ... * @return formatted string * * @deprecated use MessageFormat.format(String, Object...) * *

    Examples: *

  • format("{0} Monkeys", new Long(12)) returns "12 Monkeys".
  • *
  • format("{0} is {1}", "Life", "struggle") returns "Life is struggle".
  • *
  • format("{0} + {1} = {2}", new Byte(2), new Byte(2), new Long(5)) returns "2 + 2 = 5".
  • * */ public static String format(String fmtString, Object ... parameters) { return MessageFormat.format(fmtString, parameters); } /** * Create Properties from an array of key-value pairs * * @param pairs the source array * @return new Properties * *

    Example: *
  • asProperties(new String[] {"1", "one", "2", "two", "3", "three"}) * returns properties with three keys ("1", "2", "3"), and guess which values.
  • */ public static Properties asProperties(String[]pairs) { if (pairs == null) return null; Properties result = new Properties(); for (int i = 0; i < pairs.length-1; i+=2) { result.setProperty(pairs[i], pairs[i+1]); } return result; } /** * Finds index of the first difference between two char sequences * * @param s1 * @param s2 * @return the first index at which sequences differ, -1 if the sequences are equal * *

    Examples: *
  • findDiff("abcd", "abec") returns 2;
  • *
  • findDiff("abc", "abc") returns -1;
  • *
  • findDiff("ab", null) returns 0.
  • *
  • findDiff("", " ") returns 0.
  • */ public static int findDiff(CharSequence s1, CharSequence s2) { if (isEmpty(s1) && isEmpty(s2)) return -1; if (isEmpty(s1) || isEmpty(s2)) return 0; int i; for (i = 0; i < Math.min(s1.length(), s2.length()); i++) { if (s1.charAt(i) != s2.charAt(i)) return i; } return s1.length() == s2.length() ? -1 : i; } public static Iterable split(final Pattern pattern, final CharSequence source) { return new Iterable() { public Iterator iterator() { return new Iterator() { Matcher m = pattern.matcher(source); boolean done = false; int position = 0; public boolean hasNext() { return !done; }; public void remove() { throw new UnsupportedOperationException(); } public CharSequence next() { if (done) { throw new NoSuchElementException(); } if (m.find()) { int start = m.start(); CharSequence result = source.subSequence(position, start); position = m.end(); return result; } else { done = true; return source.subSequence(position, source.length()); } } }; } }; } /** * returns an iterable good for using in a foreach loop * @param sequence CharSequence to scan * @return Iterable<Character> * *

    Example: *
  • for (char c : chars("this is an example"){ * System.out.println("Character " + c); * } *
  • * */ public static Iterable chars(final CharSequence sequence) { return new Iterable() { public Iterator iterator() { return new Iterator() { int index = 0; public boolean hasNext() { return index < sequence.length(); } public void remove() { throw new UnsupportedOperationException(); } public Character next() { return sequence.charAt(index++); } }; } }; } } PK Г0{?< < "com/myjavatools/lib/TestBytes.javapackage com.myjavatools.lib; import junit.framework.*; import java.util.*; import static com.myjavatools.lib.Bytes.*; public class TestBytes extends TestCase { // private Objects Objects = null; public TestBytes(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public static void assertEquals(String message, Object[] expectedArray, Object[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, byte[] expectedArray, byte[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, char[] expectedArray, char[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public void testCrc32() { byte[] data = new byte[] {1, 2, 3}; long expectedReturn = 1438416925l; long actualReturn = crc32(data); assertEquals("return value", expectedReturn, actualReturn); } public void testCrc321() { byte[] data = new byte[] {0, 1, 2, 3, 4}; long expectedReturn = 1438416925l; int off = 1; int len = 3; long actualReturn = crc32(data, off, len); assertEquals("return value", expectedReturn, actualReturn); } public void testToBytes() { char[] from = new char[] {0x0123, 0x4567, 0x89ab, 0xcdef}; byte[] expectedReturn = new byte[]{0x23, 0x67, (byte)0xab, (byte)0xef}; byte[] actualReturn = toBytes(from); assertEquals("return value", expectedReturn, actualReturn); } public void testToBytes1() { long from = 0x0123456789abcdefl; byte[] expectedReturn = new byte[] {(byte)0xef, (byte)0xcd, (byte)0xab, (byte)0x89, 0x67, 0x45, 0x23, 0x01}; byte[] actualReturn = toBytes(from); assertEquals("return value", expectedReturn, actualReturn); } public void testToChars() { byte[] from = new byte[] {0x23, 0x67, (byte)0xab, (byte)0xef}; char[] expectedReturn = new char[] {0x23, 0x67, 0xab, 0xef}; char[] actualReturn = toChars(from); assertEquals("return value", expectedReturn, actualReturn); } } PK 4R:azWW"com/myjavatools/lib/TestFiles.javapackage com.myjavatools.lib; import junit.framework.*; import java.io.*; import java.util.*; import java.util.regex.Pattern; import static com.myjavatools.lib.Files.*; public class TestFiles extends TestCase { private Files files = null; public TestFiles(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { files = null; super.tearDown(); } public static void assertEquals(String message, Object[] expectedArray, Object[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, byte[] expectedArray, byte[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, char[] expectedArray, char[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public void testRelPath_1() { String expectedReturn = "src\\java"; String actualReturn = relPath("c:\\MyHome\\dev", "c:\\MyHome\\dev\\src\\java"); assertEquals("return value", expectedReturn, actualReturn); } public void testRelPath_2() { String expectedReturn = "jbuilder8/samples/welcome"; String actualReturn = relPath("/home/zaphod", "/home/zaphod/jbuilder8/samples/welcome"); assertEquals("return value", expectedReturn, actualReturn); } public void testRelPath_3() { String expectedReturn = "/home/ford/jbuilder8"; String actualReturn = relPath("/home/zaphod", "/home/ford/jbuilder8"); assertEquals("return value", expectedReturn, actualReturn); } public void testSplitPath_1() { String[] expectedReturn = new String[] {".", "src.java"}; String[] actualReturn = splitPath("src.java"); assertEquals("return value", expectedReturn, actualReturn); } public void testSplitPath_2() { String[] expectedReturn = new String[] {"/home/zaphod/jbuilder8/samples", "welcome"}; String[] actualReturn = splitPath("/home/zaphod/jbuilder8/samples/welcome"); assertEquals("return value", expectedReturn, actualReturn); } public void testSplitPath_3() { String[] expectedReturn = new String[] {"MyHome", "dev"}; String[] actualReturn = splitPath("MyHome\\dev"); assertEquals("return value", expectedReturn, actualReturn); } public void testDirname_1() { assertEquals("return value", "/home/zaphod/jbuilder8/samples", dirname("/home/zaphod/jbuilder8/samples/welcome")); } public void testDirname_2() { assertEquals("return value", "MyHome", dirname("MyHome\\dev")); } public void testDirname_3() { assertEquals("return value", ".", dirname("src.java")); } public void testFilename() { String path = "/home/zaphod/jbuilder8/samples/welcome"; String expectedReturn = "welcome"; String actualReturn = filename(path); assertEquals("return value", expectedReturn, actualReturn); } public void testPath_1() { assertEquals("return value", "c:\\MyHome\\dev\\src\\java", path("c:\\MyHome\\dev", "src\\java")); } public void testPath_2() { assertEquals("return value", "/home/zaphod/jbuilder8/samples/welcome", path("/root/inetd", "/home/zaphod/jbuilder8/samples/welcome")); } public void testPath_3() { assertEquals("return value", "c:\\MyHome\\dev", path("\\Program Files", "c:\\MyHome\\dev")); } public void testFind() { try { List expectedReturn = Arrays.asList(new String[] {new File("src\\com\\myjavatools\\lib\\Files.java").getCanonicalPath()}); List actualReturn = find(new File("."), Pattern.compile("src.*les\\.java$")); assertEquals("return value", expectedReturn, actualReturn); } catch (Exception ex) { fail("problems: " + ex); } } public void testFind1() { try { List expectedReturn = Arrays.asList(new String[] {new File("src\\com\\myjavatools\\lib\\Files.java").getCanonicalPath()}); List actualReturn = find(new File("."), Pattern.compile("src.*les\\.java$")); assertEquals("return value", expectedReturn, actualReturn); } catch (Exception ex) { fail("problems: " + ex); } } public void testFind2() { List expectedReturn = Arrays.asList(new String[] {new File("src\\com\\myjavatools\\lib\\Files.java").getAbsolutePath()}); List actualReturn = find(".", "src.*les\\.java$"); assertEquals("return value", expectedReturn, actualReturn); } // public void testLastModified() { // File file = new File("src/com/myjavatools/lib/Objects.java"); // String expectedReturn = "Thu Mar 18 10:00:18 PST 2004"; // String actualReturn = lastModified(file); // assertEquals("return value", expectedReturn, actualReturn); // } public void testReadStringFromFile() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; String actualReturn = readStringFromFile(filename); int i = Strings.findDiff(expectedReturn, actualReturn); assertEquals(i, expectedReturn.length()); assertTrue(actualReturn.startsWith(expectedReturn)); } public void testReadBytesFromStream() { InputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5}); byte[] expectedReturn = new byte[] {1, 2, 3, 4, 5}; byte[] actualReturn = readBytesFromStream(is); assertEquals("return value", expectedReturn, actualReturn); } public void testReadBytesFromFile() { String filename = "src/com/myjavatools/lib/Files.java"; byte[] expectedReturn = new byte[] {47, 42, 13, 10, 32, 42, 32}; byte[] actualReturn = new byte[7]; System.arraycopy(readBytesFromFile(filename), 0, actualReturn, 0, 7); assertEquals("return value", expectedReturn, actualReturn); } public void testGetPackage() { String basePath = null; String currentPath = null; String expectedReturn = "com.myjavatools.util"; String actualReturn = getPackageName("c:\\home\\myjavatools\\src", "c:\\home\\myjavatools\\src\\com\\myjavatools\\util"); assertEquals("return value", expectedReturn, actualReturn); actualReturn = getPackageName("c:\\home\\myjavatools\\src\\java", "c:\\home\\myjavatools\\src\\com\\myjavatools\\util"); assertNull("must be null", actualReturn); } public void testPipe() { try { InputStream is = new FileInputStream("src/com/myjavatools/lib/Files.java"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); pipe(is, baos, true, new ByteFilter() { public byte[] filter(byte[]data, int size) { byte[] result = new byte[(size+1)/2]; for (int i = 0; i < size; i+=2) { result[i/2] = data[i]; } return result; } }); byte[] expectedReturn = new byte[] {47, 13, 32, 32, 60, 62, 105}; byte[] actualReturn = new byte[7]; System.arraycopy(baos.toByteArray(), 0, actualReturn, 0, 7); assertEquals("return value", expectedReturn, actualReturn); } catch (Exception ex) { fail("got exception " + Strings.toString(ex)); } } public void testPipe1() { String sample = "Mare bella donna,\n" + "Che un bel canzone,\n" + "Sai, che ti amo, sempre amo.\n" + "Donna bella mare,\n" + "Credere, cantare,\n" + "Dammi il momento,\n" + "Che mi piace piu'!\n" + "\n\n" + "Uno, uno, uno, un momento,\n" + "Uno, uno, uno sentimento,\n" + "Uno, uno, uno complimento\n" + "E sacramento, sacramento, sacramento"; StringWriter w = new StringWriter(); pipe(new StringReader(sample), w); assertEquals("output data", sample, w.toString()); } /* public void testChdirBug() { new File("C:\\tmp\\tmpdir").mkdirs(); System.setProperty("user.dir", "C:\\tmp"); File subdir = new File("tmpdir"); assertEquals("C:\\tmp\\tmpdir", subdir.getAbsolutePath()); assertTrue(subdir.getAbsoluteFile().isDirectory()); assertFalse(subdir.isDirectory()); // fail("Oh shit, can you see..."); } */ // public void testChdir() { // String rootname = "D:\\tmp"; // String filename = "testfiles.txt"; // String rootfilename = rootname + File.separator + filename; // String expected = "this is a test"; // writeToFile(expected, rootfilename); // System.out.println(getcwd()); // System.setProperty("user.dir", rootname); // //chdir(rootname); // assertEquals(rootname, getcwd()); // System.out.println(getcwd()); // File file = new File(filename); // System.out.println(file.getAbsolutePath()); // assertEquals(rootfilename, file.getAbsolutePath()); // File rootfile = file.getAbsoluteFile(); // assertTrue(rootfile.exists()); // assertTrue(file.exists()); // // String actual = Files.readStringFromFile("testfiles.txt"); // assertEquals(expected, actual); // } public void testCopy1() { String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; copy("src/com/myjavatools/lib/foundation", "/tmp", "Objects.java"); String actualReturn = readStringFromFile("/tmp/Objects.java"); int i = Strings.findDiff(expectedReturn, actualReturn); assertEquals(i, expectedReturn.length()); assertTrue(actualReturn.startsWith(expectedReturn)); } public void testCopy2() { String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; copy(new File("src/com/myjavatools/lib/foundation"), new File("/tmp"), "Objects.java"); String actualReturn = readStringFromFile("/tmp/Objects.java"); int i = Strings.findDiff(expectedReturn, actualReturn); assertEquals(i, expectedReturn.length()); assertTrue(actualReturn.startsWith(expectedReturn)); } public void testWriteToFile() { try { String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *"; String filename1 = "src/com/myjavatools/lib/foundation/Objects.java"; String filename2 = "/tmp/Objectsx.java"; File file1 = new File(filename1); File file2 = new File(filename2); writeToFile(expectedReturn, filename2); assertEquals( -1, compare(file1, file2)); assertEquals(1, compare(file2, file1)); String actualReturn = readStringFromFile(filename2); assertEquals(expectedReturn, actualReturn); } catch (IOException ex) { fail("got " + ex); } } public void testCopyCompare() { try { String filename1 = "src/com/myjavatools/lib/foundation/Objects.java"; String filename2 = "/tmp/Objects.java"; File file1 = new File(filename1); File file2 = new File(filename2); if (!copy(filename1, filename2)) { fail("Failed to copy " + filename1 + " to " + filename2); } assertEquals(0, compare(file1, file2)); } catch (IOException ex) { fail("got " + ex); } } long timeCopy(String name1, String name2) { File file1 = new File(name1); File file2 = new File(name2); file2.delete(); if (file2.exists()) { fail("Could not remove " + file2 + " before copying to it."); return -1; } long t0 = System.nanoTime(); if (!copy(file1, file2)) { fail("Failed to copy " + file1 + " to " + file2); return -1; } long t1 = System.nanoTime(); return t1 - t0; } long copyFixture() { long time = -1; for (int i = 0; new File("/tmp/myjavatools/marvin" + i + ".zip").exists(); i++) { time = timeCopy("/tmp/myjavatools/marvin" + i + ".zip", "/tmp/myjavatools/marvin/t" + i + "/m.zip"); } return time; } long copyTimesFixture(int n) { long sum = 0; int total = 0; for (int i = 0; i < n; i++) { long time = copyFixture(); if (time > 0) { sum += time; total++; } } return total == 0 ? -1 : sum/total; } /* public void testNioCopy1() { long timeNio = copyTimesFixture(10); if (timeNio > 0) { System.out.println("it took " + (timeNio / 1000000000.0) + " seconds to copy with NIO"); } Files.USE_NIO = false; long timeOld = copyTimesFixture(10); if (timeOld > 0) { System.out.println("it took " + (timeOld / 1000000000.0) + "seconds to copy without NIO"); } if (timeNio > 0 && timeOld > 0) { long d = timeOld < timeNio ? timeNio - timeOld : timeOld - timeNio; System.out.println((timeNio > timeOld ? "Old way is " : "Nio is ") + (d / 1000000.0) + " milliseconds faster"); } } */ /* public void testNioCopy2() { String filename1 = "/tmp/myjavatools/s0.jar"; String filename2 = "/tmp/myjavatools/t0/s.jar"; long t0 = System.nanoTime(); if (!copy(filename1, filename2)) { fail("Failed to copy " + filename1 + " to " + filename2); } long t1 = System.nanoTime(); System.out.println("it took " + ((t1 - t0) / 1000000000.0) + "seconds to copy " + filename1 + " with NIO"); filename1 = "/tmp/myjavatools/s1.jar"; filename2 = "/tmp/myjavatools/t1/s.jar"; Files.USE_NIO = false; t0 = System.nanoTime(); if (!copy(filename1, filename2)) { fail("Failed to copy " + filename1 + " to " + filename2); } t1 = System.nanoTime(); Files.USE_NIO = true; System.out.println("it took " + ((t1 - t0) / 1000000000.0) + "seconds to copy " + filename1 + " without NIO"); File file1 = new File(filename1); File file2 = new File(filename2); assertTrue(equal(file1, file2)); }*/ /* public void testCopy5() { String filename1 = "/tmp/myjavatools/t0"; String filename2 = "/tmp/myjavatools/test50"; long t0 = System.nanoTime(); if (!copy(filename1, filename2)) { fail("Failed to copy " + filename1 + " to " + filename2); } long t1 = System.nanoTime(); System.out.println("it took " + (t1 - t0) + " to copy " + filename1 + " with NIO"); File file1 = new File(filename1); File file2 = new File(filename2); assertTrue(equal(file1, file2)); } */ public void testCopyAndCompare() { File source = new File("src/com/myjavatools/lib"); File target = new File("/tmp/myjavatools/lib"); for (File file : target.listFiles()) { file.delete(); } target.delete(); copy("src/com/myjavatools/lib", "/tmp/myjavatools/lib"); String list1 = Strings.join(",", source.list()); String list2 = Strings.join(",", target.list()); assertEquals(list1, list2); } public void testSynchronize() { File folder1 = new File("src/com"); File folder2 = new File("/tmp/myjavatools/tmp" + new Date().getTime()); folder2.mkdirs(); synchronize(folder1, folder2); String list1 = Strings.join(",", new File(folder1, "myjavatools/lib").list()); String list2 = Strings.join(",", new File(folder2, "myjavatools/lib").list()); assertEquals(list1, list2); deleteFile(folder2); assertFalse(folder2.isDirectory()); } public void testBytes1() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; int i = 0; try { for (byte b : bytes(new FileInputStream(filename))) { assertEquals("byte #" + i, expectedReturn.charAt(i++), b); } } catch (FileNotFoundException ex) { fail(ex.getMessage()); } catch (StringIndexOutOfBoundsException siobex) { // that's good! } } public void testChars1() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; int i = 0; try { for (char b : chars(new FileReader(filename))) { assertEquals("char #" + i, expectedReturn.charAt(i++), b); } } catch (FileNotFoundException ex) { fail(ex.getMessage()); } catch (StringIndexOutOfBoundsException siobex) { // that's good! } } public void testLines1() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String[] expectedReturn = new String[] {"/*", " *

    Title: My Java Tools Library

    ", " *", " *

    Description: This is a mixture of useful Java Tools

    "}; int i = 0; try { for (String s : lines(new FileReader(filename))) { assertEquals("line #" + i, expectedReturn[i++], s); } } catch (FileNotFoundException ex) { fail(ex.getMessage()); } catch (ArrayIndexOutOfBoundsException siobex) { // that's good! } } public void testBytes2() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; int i = 0; try { for (byte b : bytes(new File(filename))) { assertEquals("byte #" + i, expectedReturn.charAt(i++), b); } } catch (StringIndexOutOfBoundsException siobex) { // that's good! } } public void testChars2() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String expectedReturn = "/*\r\n *

    Title: My Java Tools Library

    \r\n *\r\n *

    Description: This is a mixture of useful Java Tools

    \r\n"; int i = 0; try { for (char b : chars(new File(filename))) { assertEquals("char #" + i, expectedReturn.charAt(i++), b); } } catch (StringIndexOutOfBoundsException siobex) { // that's good! } } public void testLines2() { String path = new File(".").getAbsolutePath(); String filename = "src/com/myjavatools/lib/foundation/Objects.java"; String[] expectedReturn = new String[] {"/*", " *

    Title: My Java Tools Library

    ", " *", " *

    Description: This is a mixture of useful Java Tools

    "}; int i = 0; try { for (String s : lines(new File(filename))) { assertEquals("line #" + i, expectedReturn[i++], s); } } catch (ArrayIndexOutOfBoundsException siobex) { // that's good! } } public void testFiles() { int n = 0; for (File f : files(new File("src/com/myjavatools/lib/human"))) { n++; // System.out.println(f); } assertEquals(3, n); } public void testTree() { Set check = new HashSet(); check.add(new File("src/com/myjavatools")); check.add(new File("src/com/myjavatools/lib")); check.add(new File("src/com/myjavatools/lib/foundation")); check.add(new File("src/com/myjavatools/lib/human")); for (File f : tree(new File("src/com/myjavatools"))) { // System.out.println(f); assertTrue("must have contained " + f, check.remove(f)); } assertEquals("must be empty now", check.size(), 0); } public void testTree1() { for (File dir : tree(new File("src/com/myjavatools"))) { System.out.println(dir); for (File f : files(dir)) { System.out.println(" " + f); } } } public void testTree2() { Set check = new HashSet(); check.add(new File("src/com/myjavatools/lib")); check.add(new File("src/com/myjavatools/lib/foundation")); check.add(new File("src/com/myjavatools/lib/human")); check.add(new File("src/com/myjavatools")); for (File f : treePostorder(new File("src/com/myjavatools"))) { System.out.println(f); assertTrue("must have contained " + f, check.remove(f)); } assertEquals("must be empty now", check.size(), 0); } public void testTree3() { Set check = new HashSet(); check.add(new File("src/com/myjavatools")); check.add(new File("src/com/myjavatools/lib")); check.add(new File("src/com/myjavatools/lib/human")); for (File f : tree(new File("src/com/myjavatools"), new FileFilter() { public boolean accept(File file) { return !file.getPath().contains("tion"); } })) { System.out.println(f); assertTrue("Should not contain " + f, check.remove(f)); } assertEquals("must be empty now", check.size(), 0); } } PK y1Z·$com/myjavatools/lib/TestLogical.javapackage com.myjavatools.lib; import junit.framework.*; import static com.myjavatools.lib.human.Logical.*; import com.myjavatools.lib.foundation.*; import com.myjavatools.lib.human.Predicate; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 1.5 */ public class TestLogical extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testAnd() { assertEquals("return value", LogicalConstant.TRUE, and(LogicalConstant.TRUE, LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.UNDEF, and(LogicalConstant.UNDEF, LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.UNDEF, and(LogicalConstant.TRUE, LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.UNDEF, and(LogicalConstant.UNDEF, LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.FALSE, and(LogicalConstant.TRUE, LogicalConstant.FALSE)); assertEquals("return value", LogicalConstant.FALSE, and(LogicalConstant.FALSE, LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.FALSE, and(LogicalConstant.UNDEF, LogicalConstant.FALSE)); assertEquals("return value", LogicalConstant.FALSE, and(LogicalConstant.FALSE, LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.FALSE, and(LogicalConstant.FALSE, LogicalConstant.FALSE)); } static final LogicalConstant[] logarray = new LogicalConstant[] { LogicalConstant.TRUE, LogicalConstant.UNDEF, LogicalConstant.FALSE }; // Wow! Now we get what in c++ is called a function returning a pointer to a function! public Predicate p(int i) { final int shift = i; return new Predicate() { public LogicalConstant apply(Integer x) { int idx = (x.intValue() + shift) % 3; return logarray[idx]; } }; } /* public void testAnd1() { Predicate p00 = and(p(0), p(0)); assertEquals("return value", LogicalConstant.TRUE, p00.apply(0)); assertEquals("return value", LogicalConstant.UNDEF, p00.apply(1)); assertEquals("return value", LogicalConstant.FALSE, p00.apply(2)); Predicate p01 = and(p(0), p(1)); assertEquals("return value", LogicalConstant.UNDEF, p01.apply(0)); assertEquals("return value", LogicalConstant.FALSE, p01.apply(1)); assertEquals("return value", LogicalConstant.FALSE, p01.apply(2)); Predicate p02 = and(p(0), p(2)); assertEquals("return value", LogicalConstant.FALSE, p02.apply(0)); assertEquals("return value", LogicalConstant.UNDEF, p02.apply(1)); assertEquals("return value", LogicalConstant.FALSE, p02.apply(2)); Predicate p12 = and(p(1), p(2)); assertEquals("return value", LogicalConstant.FALSE, p12.apply(0)); assertEquals("return value", LogicalConstant.FALSE, p12.apply(1)); assertEquals("return value", LogicalConstant.UNDEF, p12.apply(2)); } public void testNot() { assertEquals("return value", LogicalConstant.FALSE, not(LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.FALSE, not(LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.TRUE, not(LogicalConstant.FALSE)); } public void testNot1() { Predicate pnot0 = not(p(0)); assertEquals("return value", LogicalConstant.FALSE, pnot0.apply(0)); assertEquals("return value", LogicalConstant.FALSE, pnot0.apply(1)); assertEquals("return value", LogicalConstant.TRUE, pnot0.apply(2)); } public void testOr() { assertEquals("return value", LogicalConstant.TRUE, or(LogicalConstant.TRUE, LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.TRUE, or(LogicalConstant.UNDEF, LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.TRUE, or(LogicalConstant.TRUE, LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.UNDEF, or(LogicalConstant.UNDEF, LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.TRUE, or(LogicalConstant.TRUE, LogicalConstant.FALSE)); assertEquals("return value", LogicalConstant.TRUE, or(LogicalConstant.FALSE, LogicalConstant.TRUE)); assertEquals("return value", LogicalConstant.UNDEF, or(LogicalConstant.UNDEF, LogicalConstant.FALSE)); assertEquals("return value", LogicalConstant.UNDEF, or(LogicalConstant.FALSE, LogicalConstant.UNDEF)); assertEquals("return value", LogicalConstant.FALSE, or(LogicalConstant.FALSE, LogicalConstant.FALSE)); } public void testOr1() { Predicate p00 = or(p(0), p(0)); assertEquals("return value", LogicalConstant.TRUE, p00.apply(0)); assertEquals("return value", LogicalConstant.UNDEF, p00.apply(1)); assertEquals("return value", LogicalConstant.FALSE, p00.apply(2)); Predicate p01 = or(p(0), p(1)); assertEquals("return value", LogicalConstant.TRUE, p01.apply(0)); assertEquals("return value", LogicalConstant.UNDEF, p01.apply(1)); assertEquals("return value", LogicalConstant.TRUE, p01.apply(2)); Predicate p02 = or(p(0), p(2)); assertEquals("return value", LogicalConstant.TRUE, p02.apply(0)); assertEquals("return value", LogicalConstant.TRUE, p02.apply(1)); assertEquals("return value", LogicalConstant.UNDEF, p02.apply(2)); Predicate p12 = or(p(1), p(2)); assertEquals("return value", LogicalConstant.UNDEF, p12.apply(0)); assertEquals("return value", LogicalConstant.TRUE, p12.apply(1)); assertEquals("return value", LogicalConstant.TRUE, p12.apply(2)); }*/ } PK q4x$com/myjavatools/lib/TestObjects.javapackage com.myjavatools.lib; import junit.framework.*; import java.util.*; import static com.myjavatools.lib.Bytes.*; import static com.myjavatools.lib.foundation.Objects.*; import static com.myjavatools.lib.foundation.Maps.*; public class TestObjects extends TestCase { // private Objects Objects = null; public TestObjects(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public static void assertEquals(String message, Object[] expectedArray, Object[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": actual must not be null", actualArray); assertEquals("sizes must be equal", expectedArray.length, actualArray.length); for (int i = 0; i < Math.min(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, byte[] expectedArray, byte[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, char[] expectedArray, char[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public void testNothing() { SortedSet ss = new TreeSet(); ss.addAll(Arrays.asList(new Integer[] {3, 17, 60, 2, 28, 2005})); assertEquals(6, ss.size()); } public void testToMap() { Object[] pairs = new Object[] {1, "one", 2, "two", 3, "three"}; java.util.Map expectedReturn = new HashMap(); expectedReturn.put(1, "one"); expectedReturn.put(2, "two"); expectedReturn.put(3, "three"); java.util.Map actualReturn = toMap(pairs); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmpty() { assertTrue("return value", isEmpty(null)); assertTrue("return value", isEmpty(new Long[]{})); assertTrue("return value", isEmpty(new HashMap())); assertTrue("return value", isEmpty("")); assertFalse("return value", isEmpty(" ")); } public void testOneOf2() { assertEquals("return value", "xyz", oneOf(null, "xyz")); assertEquals("return value", "abc", oneOf("abc", "xyz")); assertEquals("return value", "", oneOf("", null)); assertEquals("return value", "abc", oneOf("abc", null)); } public void testOneOf3() { assertEquals("return value", "xyz", oneOf(null, "", "xyz")); assertEquals("return value", "abc", oneOf("abc", null, "xyz")); assertEquals("return value", "def", oneOf("", "def", null)); assertEquals("return value", "", oneOf("", null, "")); } public void testOneOf4() { assertEquals("return value", "xyz", oneOf(null, "", null, "xyz")); assertEquals("return value", "abc", oneOf("abc", null, "pqr", "xyz")); assertEquals("return value", "def", oneOf("", "def", null, "xyz")); assertEquals("return value", "", oneOf("", null, "", null)); } public void testMap() { java.util.Map m = new HashMap(); m.put(0xa, "ValueOfA"); m.put(0xb, "ValueOfB"); m.put(0xc, "ValueOfC"); List domain = Arrays.asList(new Integer[] {0xb, 0, 0xb}); List expectedReturn = Arrays.asList(new String[] {"ValueOfB", null, "ValueOfB"}); List actualReturn = map(m, (List)domain); assertEquals("return value", expectedReturn, actualReturn); } public void testMap1() { java.util.Map m = new HashMap(); m.put(1, "One"); m.put(2, "Two"); m.put(3, "Three"); Collection domain = Arrays.asList(new Integer[] {2, 0, 2}); Collection expectedReturn = new ArrayList(Arrays.asList(new String[] {"Two", null, "Two"})); Collection actualReturn = new ArrayList(map(m, domain)); Collection ar = actualReturn; if(!actualReturn.equals(expectedReturn)) { System.out.println("oops1"); } if(!expectedReturn.equals(actualReturn)) { System.out.println("oops2"); expectedReturn.equals(actualReturn); } assertEquals("return value", expectedReturn, actualReturn); } public void testMap2() { java.util.Map m = new HashMap(); m.put(1, "One"); m.put(2, "Two"); m.put(3, "Three"); m.put(4, "Four"); java.util.Map expectedReturn = new TreeMap(); expectedReturn.put(2, "Two"); expectedReturn.put(4, "Four"); Collection keys = Arrays.asList(new Integer[] {2,4}); java.util.Map actualReturn = restrict(m, keys); assertEquals("return value", actualReturn, expectedReturn); assertEquals("return value", expectedReturn, actualReturn); } public void testCompose() { Map f = toMap(new Object[] {1, "one", 2, "two", 3, "three"}); Map g = toMap(new Object[] {"one", 1.0, "two", 2.0, "three", 3.0}); Map composition = compose(f, g); Map expected = toMap(new Object[] {1, 1.0, 2, 2.0, 3, 3.0}); assertEquals("Return value", expected, composition); } public void testInverse() { Map f = toMap(new Object[] {1, "one", 2, "two", 3, "three"}); Map expected = toMap(new Object[] {"one", 1, "two", 2, "three", 3}); try { Map inverse = inverse(f); assertEquals("Return value", expected, inverse); } catch (InstantiationException e) { fail("got " + e + " - but must be invertible"); } Map g = toMap("John", "Doe", "Jack", "Rabbit", "Jane", "Doe"); try { inverse(g); fail("Inverse does not exist"); } catch (InstantiationException e) { // Correct, must throw this exception } } public void testIndexOf() { assertEquals("must be 1", 1, indexOf("abc", new String[] {"123", "abc", "xyz"})); assertEquals("must be 2", 2, indexOf(null, new String[] {"123", "abc", null})); assertEquals("must be 3", 3, indexOf(5, new Integer[] {-1, 1, 3, 5, 7, 9, 11})); } public void testIndexOf1() { assertEquals("must be 1", 1, indexOf("abc", new String[] {"abc", "abc", "xyz"}, 1)); assertEquals("must be 2", 2, indexOf(null, new String[] {"123", "abc", null}, 1)); assertEquals("must be 5", 5, indexOf(14, new Integer[] {1, 3, 14, 7, 9, 14, 11}, 4)); } public void testIndexOf2() { List list = new ArrayList(); list.add("abc"); list.add("abc"); list.add("xyz"); list.add(null); assertEquals("must be 1", 1, indexOf("abc", list, 1)); assertEquals("must be 3", 3, indexOf(null, list, 1)); } public void testToMap1() { Map result = toMap("first", "primero", "second", "segundo", "third", "tercero"); assertEquals("must be three elements", 3, result.size()); assertEquals("must be segundo", "segundo", result.get("second")); } public void testToMap2() { Map result = toMap("1", "US", "7", "Russia", "49", "Germany", "1", "US"); assertEquals("must be four elements", 4, result.size()); assertEquals("must be Germany", "Germany", result.get("49")); } } PK 4|bb$com/myjavatools/lib/TestStrings.javapackage com.myjavatools.lib; import junit.framework.*; import java.io.*; import java.util.*; import java.util.regex.PatternSyntaxException; import java.util.regex.Pattern; import static com.myjavatools.lib.Strings.*; public class TestStrings extends TestCase { public TestStrings(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); /**@todo verify the constructors*/ } protected void tearDown() throws Exception { super.tearDown(); } public static void assertEquals(String message, Object[] expectedArray, Object[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": actual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, byte[] expectedArray, byte[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ": ctual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, char[] expectedArray, char[] actualArray) { if (expectedArray == null) { assertNull(message + ": actual must be null", actualArray); } assertNotNull(message + ":actual must not be null", actualArray); for (int i = 0; i < Math.max(expectedArray.length, actualArray.length); i++) { assertEquals(message + ": #" + i, expectedArray[i], actualArray[i]); } } public static void assertEquals(String message, Iterable expected, Iterable actual) { if (expected == null) { assertNull(message + ": actual must be null", actual); } assertNotNull(message + ":actual must not be null", actual); Iterator exp = expected.iterator(); Iterator act = actual.iterator(); int i = 0; while(exp.hasNext()) { assertTrue(message + ": actual must have element #" + i, act.hasNext()); assertEquals(message + ": #" + i, exp.next(), act.next()); i++; } assertFalse(message + ": actual must have " + i + " elements", act.hasNext()); } public void testCountTrailingSpaces() { String s = null; int expectedReturn = 3; int actualReturn = countTrailingSpaces(" this is a string "); assertEquals("return value", expectedReturn, actualReturn); } public void testToSgmlEncoding() { String s = "Feliz Ao Nuevo\n"; String expectedReturn = "<i>Feliz Año Nuevo</i>\n"; String actualReturn = toSgmlEncoding(s); assertEquals("return value", expectedReturn, actualReturn); } public void testHtmlEncode() { String s = "Feliz Ao Nuevo\n"; String expectedReturn = "<i>Feliz Año Nuevo</i>\n"; String actualReturn = toSgmlEncoding(s); assertEquals("return value", expectedReturn, actualReturn); } public void testUnpack() { String string = "\u2367\uabef"; byte[] expectedReturn = new byte[] {0x23, 0x67, (byte)0xab, (byte)0xef}; byte[] actualReturn = unpack(string); assertEquals("return value", expectedReturn, actualReturn); } public void testDecode() throws IOException, UnsupportedEncodingException { byte[] bytes = new byte[] {0x41, (byte)0xc3, (byte)0xb1, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}; String expectedReturn = "Ao Nuevo"; String actualReturn = decode(bytes, "UTF8"); assertEquals("return value", expectedReturn, actualReturn); bytes = new byte[] {0x41, (byte)0x96, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}; actualReturn = decode(bytes, "MacRoman"); assertEquals("return value", expectedReturn, actualReturn); } public void testToHex() { char ch = '\u00af'; String expectedReturn = "00af"; String actualReturn = toHex(ch); assertEquals("return value", expectedReturn, actualReturn); } public void testToReadable() { String s = "\tHola seor!\n"; String expectedReturn = "..Hola se.or!."; String actualReturn = toReadable(s); assertEquals("return value", expectedReturn, actualReturn); } public void testToReadable1() { String s = "\tHola seor!\n"; String expectedReturn = "Hola se.or"; String actualReturn = toReadable(s.toCharArray(), 2, 12); assertEquals("return value", expectedReturn, actualReturn); } public void testUnzip() throws IOException, UnsupportedEncodingException { String zippedString = "\u78da\uf348\ucdc9\uc957\u08cf\u2fca\u4901\u0018\u0b04\u1d00"; String expectedReturn = "Hello World"; String actualReturn = unzip(zippedString); assertEquals("return value", expectedReturn, actualReturn); } public void testToHexReadable() { byte[] data = new byte[] {1, 2, 48}; String expectedReturn = "01 02 30 \r\n"; String actualReturn = toHexReadable(data); assertEquals("return value", expectedReturn, actualReturn); } public void testAsProperties() { String[] pairs = new String[] {"1", "one", "2", "two", "3", "three"}; Properties expectedReturn = new Properties(); expectedReturn.setProperty("1", "one"); expectedReturn.setProperty("2", "two"); expectedReturn.setProperty("3", "three"); Properties actualReturn = asProperties(pairs); assertEquals("return value", expectedReturn, actualReturn); } // public void testFormat2() { // String expectedReturn = "Life is struggle"; // String actualReturn = format("{0} is {1}", "Life", "struggle"); // assertEquals("return value", expectedReturn, actualReturn); // } public void testGrep() throws PatternSyntaxException { String[] source = new String[] {"good", "bad", "ugly"}; String regexp = "g."; List expectedReturn = new ArrayList(); expectedReturn.add("good"); expectedReturn.add("ugly"); List actualReturn = grep(source, regexp); assertEquals("return value", expectedReturn, actualReturn); } public void testToPropertiesEncoding() { assertEquals("return value", toPropertiesEncoding('\u00af', false), "\\u00af"); assertEquals("return value", toPropertiesEncoding('\u00af', true), "\\u00AF"); assertEquals("return value", toPropertiesEncoding('a', false), "a"); } public void testTextHeight() { assertEquals("return value", 3, textHeight("One\nTwo\nThree")); assertEquals("return value", 5, textHeight("\nOne\nTwo\nThree\n")); } public void testJoin() { assertEquals("return value", "1, 555", join(", ", new Long[] {new Long(1), new Long(555)})); assertEquals("return value", "Here and there and everywhere", join(" and ", new String[] {"Here", "there", "everywhere"})); } public void testHasAlpha() { assertTrue("return value", hasAlpha("2OO2")); assertTrue("return value", hasAlpha("This is a string")); assertFalse("return value", hasAlpha("+")); assertFalse("return value", hasAlpha("1900")); assertFalse("return value", hasAlpha("|1!*")); } public void testSplit1() { String source = "a,ab,abcde"; String separator = ","; Collection expectedReturn = new ArrayList(); expectedReturn.add("a"); expectedReturn.add("ab"); expectedReturn.add("abcde"); Iterable actualReturn = split(separator, source); assertEquals("return value", expectedReturn, actualReturn); } public void testSplit2() { String source = "a:ab:abcde:"; String separator = ":"; List expectedReturn = new ArrayList(); expectedReturn.add("a"); expectedReturn.add("ab"); expectedReturn.add("abcde"); expectedReturn.add(""); Iterable actualReturn = split(separator, source); assertEquals("return value", expectedReturn, actualReturn); } public void testSplit1r() { String source = "a,ab,abcde"; String separator = ","; Collection expectedReturn = new ArrayList(); expectedReturn.add("a"); expectedReturn.add("ab"); expectedReturn.add("abcde"); Iterable actualReturn = Strings.split(Pattern.compile(separator), source); assertEquals("return value", expectedReturn, actualReturn); } public void testSplit2r() { String source = "a:ab:abcde:"; String separator = ":"; List expectedReturn = new ArrayList(); expectedReturn.add("a"); expectedReturn.add("ab"); expectedReturn.add("abcde"); expectedReturn.add(""); Iterable actualReturn = split(Pattern.compile(separator), source); assertEquals("return value", expectedReturn, actualReturn); } public void testToCEncoding() { assertEquals("return value", "\\nFeliz A\\xf1o Nuevo\\n", toCEncoding("\nFeliz Ao Nuevo\n")); } public void testToJavaEncoding() { assertEquals("return value", "\\nFeliz A\\u00f1o Nuevo\\n\\0", toJavaEncoding("\nFeliz Ao Nuevo\n\0")); } public void testDecodeJavaString() { assertEquals("return value", "This is a string", decodeJavaString("This is a string")); String expected = decodeJavaString("\\nFeliz A\\u00F1o Nuevo\\n"); assertEquals("return value", "\nFeliz Ao Nuevo\n", expected); } public void testZip() throws IOException, UnsupportedEncodingException { String source = "Hello World"; String expectedReturn = "\u78da\uf348\ucdc9\uc957\u08cf\u2fca\u4901\u0018\u0b04\u1d00"; String actualReturn = zip(source); assertEquals("return value", expectedReturn, actualReturn); } public void testCrc32() throws IOException, UnsupportedEncodingException { String string = "Hello World"; long expectedReturn = 2178450716l; long actualReturn = crc32(string); assertEquals("return value", expectedReturn, actualReturn); } public void testHexDump() { char[] data = new char[] {1, 'a', 'b', '\n', 'c'}; String expectedReturn = "\r\n0000: 0001 0061 0062 000a 0063 | .ab.c\r\n"; String actualReturn = hexDump(data); int diffidx = findDiff(expectedReturn, actualReturn); assertEquals("difference", -1, diffidx); } // public void testFormat3() { // assertEquals("return value", "2 + 2 = 5", // format("{0} + {1} = {2}", new Byte((byte)2), new Byte((byte)2), new Long(5))); // } public void testCountLeadingSpaces() { assertEquals("return value", 1, countLeadingSpaces(" this is a string ")); } public void testToJavaEncoding1() { assertEquals("return value", "\\nFeliz A\\u00f1o Nuevo\\n\\16", toJavaEncoding("\nFeliz Ao Nuevo\n\u000e")); } public void testToJavaHexEncoding() { assertEquals("return value", "\\u00af", toJavaHexEncoding('\u00af', false)); } public void testToJavaHexEncoding1() { assertEquals("return value", "\\u00af", toJavaHexEncoding('\u00af')); } public void testToJavaOctalEncoding() { assertEquals("return value", "\\1", toJavaOctalEncoding('\u0001')); assertEquals("return value", "\\14", toJavaOctalEncoding('\u000c')); assertEquals("return value", "\\377", toJavaOctalEncoding('\u00ff')); } public void testExtractValue1() { String expectedReturn = "abcd"; String actualReturn = extractValue("java.home=\"c:\\java\\jdk1.4.1\"\nx=\"abcd\"", "x"); assertEquals("return value", expectedReturn, actualReturn); } public void testExtractValue2() { String expectedReturn = "c:\\java\\jdk1.4.1"; String actualReturn = extractValue( "java.home=\"c:\\java\\jdk1.4.1\"\nx=\"abcd\"", "java.home"); assertEquals("return value", expectedReturn, actualReturn); } public void testJoin1() { assertEquals("return value", "", join(", ", (Collection)null)); assertEquals("return value", "", join(":", new HashSet())); } public void testJoin2() { String separator = ", "; List list = new ArrayList(); list.add("entry1"); list.add("entry2"); String expectedReturn = "entry1, entry2"; String actualReturn = join(separator, list); assertEquals("return value", expectedReturn, actualReturn); } public void testToHexReadable1() { String actual = toHexReadable(new char[] {1, 'a', 'b', '\n', 'c'}); String expected = "0001 0061 0062 000a 0063 \r\n"; int diffidx = findDiff(actual, expected); assertEquals("return value", expected, actual); } public void testHexDump1() { String data = "\u0001ab\nc"; String expectedReturn = "\r\n0000: 0001 0061 0062 000a 0063 | .ab.c\r\n"; String actualReturn = hexDump(data); assertEquals("return value", expectedReturn, actualReturn); } public void testToHexReadable2() { byte[] data = new byte[] {1, 2, 48}; String expectedReturn = "02 30 \r\n"; String actualReturn = toHexReadable(data, 1, 3); assertEquals("return value", expectedReturn, actualReturn); } public void testToJavaEncoding2() { assertEquals("return value", "\\u00af", toJavaEncoding('\u00af', false)); assertEquals("return value", "\\u00AF", toJavaEncoding('\u00af', true)); assertEquals("return value", "\\n", toJavaEncoding('\n', true)); assertEquals("return value", "\\16", toJavaEncoding('\16', true)); assertEquals("return value", "\\0", toJavaEncoding('\0', true)); assertEquals("return value", "a", toJavaEncoding('a', true)); } public void testCountChar() { assertEquals("return value", 3, countChar("Goodness me, a clock has struck", 'o')); } public void testToJavaEncoding3() { String actual; assertEquals("return value", "\\u00af", toJavaEncoding('\u00af', false, false)); actual = toJavaEncoding('\u00af', true, true); assertEquals("return value", "\\u00AF", actual); assertEquals("return value", "\\12", toJavaEncoding('\n', false, false)); assertEquals("return value", "\\n", toJavaEncoding('\n', true, true)); assertEquals("return value", "a", toJavaEncoding('a', true)); } public void testSgmlEntity() { assertEquals("return value", "悫", sgmlEntity('\u60ab')); assertEquals("return value", "&", sgmlEntity('&')); assertEquals("return value", "<", sgmlEntity('<')); assertEquals("return value", null, sgmlEntity('X')); assertEquals("return value", null, sgmlEntity('\n')); } public void testHexDump2() { byte[] data = new byte[] {1, 'a', 'b', '\n', 'c'}; String expectedReturn = "\r\n0000: 01 61 62 0a 63 | \u00b7 a b \u00b7 c \r\n"; String actualReturn = hexDump(data); assertEquals("return value", expectedReturn, actualReturn); } public void testToHex1() { assertEquals("return value", "4d2", toHex(1234)); } public void testToStrings() { Object[] object = new Object[] { new Integer(22), new Boolean(false), "wow"}; String[] expectedReturn = new String[] {"22", "false", "wow"}; String[] actualReturn = toStrings(object); assertEquals("return value", expectedReturn, actualReturn); } public void testPack() { String expectedReturn = "\u2367\uabef"; String actualReturn = pack(new byte[] {0x23, 0x67, (byte)0xab, (byte)0xef}); assertEquals("return value", expectedReturn, actualReturn); } public void testGrep1() { String[] source = new String[] {"good", "bad", "ugly"}; Pattern regexp = null; try { regexp = Pattern.compile("g."); } catch (PatternSyntaxException ex) { fail(ex.toString()); } List expectedReturn = new ArrayList(); expectedReturn.add("good"); expectedReturn.add("ugly"); List actualReturn = grep(source, regexp); assertEquals("return value", expectedReturn, actualReturn); } public void testToHexReadable3() { String s = "\u0001ab\nc"; String expectedReturn = "0001 0061 0062 000a 0063 \r\n"; String actualReturn = toHexReadable(s); assertEquals("return value", expectedReturn, actualReturn); } public void testNeedsEncoding() { assertTrue("return value", needsEncoding('\u00af')); assertFalse("return value", needsEncoding('a')); } public void testFill() { String actualReturn = fill('*', 10); assertEquals("return value", "**********", actualReturn); } public void testToJavaEncoding4() { assertEquals("return value", "\\u00af", toJavaEncoding('\u00af')); assertEquals("return value", "\\n", toJavaEncoding('\n')); assertEquals("return value", "a", toJavaEncoding('a')); } public void testZip2bytes() throws IOException, UnsupportedEncodingException { String source = "Hello World"; byte[] expectedReturn = new byte[] {0x78, (byte)0xda, (byte)0xf3, 0x48, (byte)0xcd, (byte)0xc9, (byte)0xc9, 0x57, (byte)0x08, (byte)0xcf, 0x2f, (byte)0xca, 0x49, 0x01, 0x00, 0x18, 0x0b, 0x04, 0x1d, 0x00}; byte[] actualReturn = zip2bytes(source); assertEquals("return value", expectedReturn, actualReturn); } public void testToHex2() { assertEquals("return value", "12BC", toHex('\u12bc', true)); assertEquals("return value", "00af", toHex('\u00af', false)); } // public void testFormat1() { // assertEquals("return value", "12 Monkeys", format("{0} Monkeys", new Long(12))); // } public void testToHex3() { assertEquals("return value", "9b", toHex((byte)155)); } public void testNeedsEncoding1() { assertTrue("return value", needsEncoding("Feliz Ao Nuevo")); assertFalse("return value", needsEncoding("Feliz Navedad")); } public void testUnzip1() throws IOException, UnsupportedEncodingException { byte[] zippedBytes = new byte[] {0x78, (byte)0xda, (byte)0xf3, 0x48, (byte)0xcd, (byte)0xc9, (byte)0xc9, 0x57, 0x08, (byte)0xcf, 0x2f, (byte)0xca, 0x49, 0x01, 0x00, 0x18, 0x0b, 0x04, 0x1d, 0x00}; String expectedReturn = "Hello World"; String actualReturn = unzip(zippedBytes); assertEquals("return value", expectedReturn, actualReturn); } public void testToHex4() { assertEquals("return value", "006B006C12BC", toHex("kl\u12bc", true)); assertEquals("return value", "006b006c12bc", toHex("kl\u12bc", false)); } public void testToCEncoding1() { assertEquals("return value", "\\xabcd", toCEncoding('\uabcd')); assertEquals("return value", "\\xaf", toCEncoding('\u00af')); assertEquals("return value", "\\n", toCEncoding('\n')); assertEquals("return value", "a", toCEncoding('a')); } public void testIsAlpha() { assertTrue("must be alpha", isAlpha('a')); assertTrue("must be alpha", isAlpha('O')); assertTrue("must be alpha", isAlpha('I')); assertTrue("must be alpha", isAlpha('l')); assertFalse("can't be alpha", isAlpha('+')); assertFalse("can't be alpha", isAlpha('0')); assertFalse("can't be alpha", isAlpha('|')); assertFalse("can't be alpha", isAlpha('1')); } public void testTextWidth() { assertEquals("return value", 5, textWidth("One\nTwo\nThree")); } public void testToJavaEncoding5() { String actual = toJavaEncoding("\nFeliz Ao Nuevo\n", true, false); assertEquals("return value", "\\12Feliz A\\u00F1o Nuevo\\12", actual); assertEquals("return value", "\\nFeliz A\\u00F1o Nuevo\\n", toJavaEncoding("\nFeliz Ao Nuevo\n", true, true)); assertEquals("return value", "\\nFeliz A\\u00f1o Nuevo\\n", toJavaEncoding("\nFeliz Ao Nuevo\n", false, true)); } public void testZip8bit() throws IOException, UnsupportedEncodingException { String expectedReturn = "x\u00da\u00f3H\u00cd\u00c9\u00c9W\b\u00cf/\u00caI\u0001\u0000\u0018\u000b\u0004\u001d\u0000"; String actualReturn = zip8bit("Hello World"); assertEquals("return value", expectedReturn, actualReturn); /**@todo fill in the test code*/ } /* public void testIsVowel() { assertFalse("can't be vowel", isVowel('x')); assertTrue("must be vowel", isVowel('U')); } */ public void testEncode() throws IOException, UnsupportedEncodingException { String s = "Ao Nuevo"; String encoding = null; byte[] expectedReturn = new byte[] {0x41, (byte)0xc3, (byte)0xb1, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}; byte[] actualReturn = encode(s, "UTF8"); assertEquals("return value", expectedReturn, actualReturn); expectedReturn = new byte[] {0x41, (byte)0x96, 0x6f, 0x20, 0x4e, 0x75, 0x65, 0x76, 0x6f}; actualReturn = encode("Ao Nuevo", "MacRoman"); assertEquals("return value", expectedReturn, actualReturn); } public void testWordCount() { assertEquals("return value", 3, wordCount("This is life!")); assertEquals("return value", 4, wordCount("C'est la vie !")); } public void testIndexOf1() { String t1 = "ABCDefghDB"; assertEquals(indexOf(t1, 'A', 0), t1.indexOf('A', 0)); assertEquals(indexOf(t1, 'A', 1), t1.indexOf('A', 1)); for (int i = 0; i < 10; i++) { assertEquals(indexOf(t1, 'B', i), t1.indexOf('B', i)); } } public void testIndexOf2() { String t1 = "ABCDefghDB"; String t2 = "ABCDefghijk"; for (int i = 0; i < t2.length(); i++) { assertEquals(indexOf(t1, t2.charAt(i)), t1.indexOf( t2.charAt(i))); } } public void testLastIndexOf() { String t1 = "ABCDefghDB"; String t2 = "ABCDefghijk"; for (int i = 0; i < t2.length(); i++) { assertEquals(lastIndexOf(t1, t2.charAt(i)), t1.lastIndexOf( t2.charAt(i))); } } public void testIndexOf3() { String t1 = "ABCDefghDABCdefAB"; String t2 = "ABC"; for (int i = 0; i < 20; i++) { assertEquals(indexOf(t1, t2, i), t1.indexOf( t2, i)); } } public void testIndexOf4() { String t1 = "ABCDefghDABCdefAB"; String t2 = 'x' + t1 + 'y'; for (int i = 0; i < 20; i++) { for (int j = i; j < 20; j++) { if (indexOf(t1, t2.subSequence(i, j)) != t1.indexOf(t2.substring(i, j))) { int k = indexOf(t1, t2.subSequence(i, j)); System.out.println("oops"); } assertEquals(indexOf(t1, t2.subSequence(i, j)), t1.indexOf(t2.substring(i, j))); } } } public void testIsAlmostEmpty() { assertTrue("must be almost empty", isAlmostEmpty("")); assertTrue("must be almost empty", isAlmostEmpty(null)); assertTrue("must be almost empty", isAlmostEmpty("\n \r \n")); assertFalse("must be non-empty", isAlmostEmpty(".")); assertFalse("must be non-empty", isAlmostEmpty("Contains data!")); } public void testToSgmlEncoding1() { assertEquals("return value", " ", toSgmlEncoding('\n')); } public void testReplace() { String where = null; String oldSubstring = null; String newSubstring = null; String expectedReturn = null; String actualReturn = replace(where, oldSubstring, newSubstring); assertEquals("return value", expectedReturn, actualReturn); assertEquals("return value", "God hates you", replaceAll("God loves you", "love", "hate")); assertEquals("return value", "All you need is me, love!", replace("All you need is love, love!", "love", "me")); } public void testToPropertiesEncoding1() { assertEquals("return value", toPropertiesEncoding('\u00af'), "\\u00af"); assertEquals("return value", toPropertiesEncoding('a'), "a"); } public void testToString() { String s = null; String expected = "java.lang.NullPointerException\r\n" + "\tat com.myjavatools.lib.TestStrings"; try { s.toString(); s = "?"; } catch (Exception e) { String returned = Strings.toString(e); //!!! does not compile if Strings is missing. assertTrue("returnValue is " + returned, returned.startsWith(expected)); } assertNull(s); } public void testChars1() { String t = "this is the string"; Iterator it = chars(t).iterator(); for (int i = 0; i < t.length(); i++) { assertEquals(t.charAt(i), it.next()); } assertFalse(it.hasNext()); } public void testChars2() { assertFalse(chars("").iterator().hasNext()); } } PK 0j lmm"com/myjavatools/lib/TestTools.javapackage com.myjavatools.lib; import junit.framework.*; public class TestTools extends TestCase { private Tools tools = null; public TestTools(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); /**@todo verify the constructors*/ tools = null; } protected void tearDown() throws Exception { tools = null; super.tearDown(); } public void testBark() { String msg = "Test Error Message, just click 'OK'"; boolean expectedReturn = false; boolean actualReturn = tools.bark(msg); assertEquals("return value", expectedReturn, actualReturn); } public void testCommandLineArg() { assertEquals("return value", "abcd", tools.commandLineArg("abcd")); assertEquals("return value", "\"ab cd\"", tools.commandLineArg("ab cd")); assertEquals("return value", "\" \"", tools.commandLineArg(" ")); } public void testInform() { String msg = "Test Informative Message, just click 'OK'"; boolean expectedReturn = false; boolean actualReturn = tools.inform(msg); assertEquals("return value", expectedReturn, actualReturn); } public void testRunCommand1_1() { String cmd = "notepad src/com/myjavatools/lib/Tools.java&"; boolean expectedReturn = true; boolean actualReturn = tools.runCommand(cmd); assertEquals("return value", expectedReturn, actualReturn); } public void testRunCommand1_2() { String cmd = "rmdir xxx"; boolean expectedReturn = false; boolean actualReturn = tools.runCommand(cmd); assertEquals("return value", expectedReturn, actualReturn); } public void testRunCommand2_1() { String cmd = "cmd /c dir ."; String dir = "c:\\Program Files"; boolean expectedReturn = true; boolean actualReturn = tools.runCommand(cmd, dir); assertEquals("return value", expectedReturn, actualReturn); } public void testWhether() { assertEquals("return value", false, tools.whether("Are you a cat or a dog")); assertEquals("return value", true, tools.whether("Is it true that 0 + 0 = 0")); } } PK n0R*? ? com/myjavatools/lib/TestWeb.javapackage com.myjavatools.lib; import junit.framework.*; import java.util.Map; import java.nio.charset.Charset; import java.util.Iterator; import java.util.Set; public class TestWeb extends TestCase { private Web web = null; public TestWeb(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); /**@todo verify the constructors*/ Map charsets = Charset.availableCharsets(); for (Iterator i = charsets.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); Charset charset = (Charset)entry.getValue(); System.out.print(entry.getKey().toString() + ": " + charset + " "); Set aliases = charset.aliases(); for (Iterator j = aliases.iterator(); j.hasNext();) { System.out.print(", aka " + j.next()); } System.out.println(); } web = new Web(); } protected void tearDown() throws Exception { web = null; super.tearDown(); } public void testGetHtmlCharset() { String s = ""; String expectedReturn = "shift-jis"; String actualReturn = web.getHtmlCharset(s); assertEquals("return value", expectedReturn, actualReturn); } public void testGetHtmlEncoding() { String s = ""; String expectedReturn = "SJIS"; String actualReturn = web.getHtmlEncoding(s); assertEquals("return value", expectedReturn, actualReturn); } public void testGetXmlCharset() { String s = ""; String expectedReturn = "utf-8"; String actualReturn = web.getXmlCharset(s); assertEquals("return value", expectedReturn, actualReturn); } public void testGetXmlEncoding() { String s = ""; String expectedReturn = "UTF8"; String actualReturn = web.getXmlEncoding(s); assertEquals("return value", expectedReturn, actualReturn); } public void testUrlEncode() { String actual = web.urlEncode("dir", "C:\\Program Files"); String expected="dir=C%3A%5CProgram+Files"; assertEquals("return value", expected, actual); } } PK 1TdSASAcom/myjavatools/lib/Tools.java/** *

    Title: MyJavaTools: General Purpose Tools

    *

    Description: Miscellaneous all-purpose tools. * Good for Java 5.0 and up.

    *

    Copyright: This is public domain; * The right of people to use, distribute, copy or improve the contents of the * following may not be restricted.

    * * @version 5.0 * @author Vlad Patryshev */ package com.myjavatools.lib; import java.io.*; import java.text.MessageFormat; import javax.swing.*; import static com.myjavatools.lib.Files.*; import java.util.Map; import java.util.zip.ZipInputStream; public abstract class Tools { private static boolean DEBUG = false; /** * Reports a fatal error to sderr and exits, upon a condition * * @param condition it is fatal error when condition is true * @param message the error message *

    Example: *

    fatalError(!file.exists(), "File " + file + " does not exist!") */ public static final void fatalError(boolean condition, String message) { if (condition) fatalError(message); } /** * Reports a fatal error to sderr and exits * * @param message the error message *

    Example: *

    fatalError("Your System is Windows!") */ public static final void fatalError(String message) { System.err.println(message); System.exit(1); } /** * Reports a fatal exception to stderr and exits * * @param exception the fatal exception * *

    Example: *

    * try {
    *   String s = null;
    *   s.toString();
    * } catch (Exception e) {
    *   fatalError(e);
    * }
    prints *

    java.lang.NullPointerException
    *         at com.myjavatools.util.Tools.main
    */ public static final void fatalError(Exception exception) { exception.printStackTrace(System.err); System.exit(1); } /** * Reports an error message and an exception to sderr and exits * * @param message the error message * @param exception the fatal exception * *

    Example: *

    * try {
    *   String s = null;
    *   s.toString();
    * } catch (Exception e) {
    *   fatalError("Null pointers are bad!", e);
    * }
    prints *

    Null pointers are bad!
    * java.lang.NullPointerException
    *         at com.myjavatools.util.Tools.main
    */ public static final void fatalError(String message, Exception exception) { System.err.println(message); exception.printStackTrace(System.err); System.exit(1); } /** * Displays an error message * * @param msg the message to display * @return always false * *

    Example: *

  • bark("Code Red Alert!").
  • */ public static boolean bark(String msg) { JOptionPane.showConfirmDialog(null, msg, "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); return false; } /** * Displays an informative message * * @param msg the message to display * @return always false * *

    Example: *
  • inform("To beguile the time, be like the time.").
  • */ public static boolean inform(String msg) { JOptionPane.showConfirmDialog(null, msg, "FYI", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE); return false; } /** * Displays a message and receives user's choice (yes/no) * * @param msg the messge to display * @return true if user clicked "Yes", otherwise returns "No" * *

    Example: *
  • if (!whether("Want this program to proceed?")) System.exit(1);
  • */ public static boolean whether(String msg) { return JOptionPane.showConfirmDialog(null, msg + "?", "Confirmation required", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION; } /** * Collects garbage, reports back * @return an array of three Longs, containing total memory, * free memory before and after gc */ public static Long[] gc() { Long total = new Long(Runtime.getRuntime().totalMemory() / 1000); Long free1 = new Long(Runtime.getRuntime().freeMemory() / 1000); System.gc(); Long free2 = new Long(Runtime.getRuntime().freeMemory() / 1000); return new Long[] {total, free1, free2}; } /** * Collects garbage, reports back * @return a string with memory usage report */ public static String freeMemory() { return MessageFormat.format("Memory usage: total = {0}, free: {1} -> {2}", (Object)gc()); } /** * gets values of all environment variables * * @return Map * * The returned map contains environment variable names as keys and their values as values. */ public static Map getEnv() { String output = getCommandOutput("env"); if (DEBUG) System.out.println("getEnv: env returned\n" + output + "\n-----------------------"); if (output == null) { output = getCommandOutput("cmd /c set"); if (DEBUG) System.out.println("getEnv: cmd /c set returned\n" + output + "\n-----------------------"); } if (output == null) return null; String[] env = output.replaceAll("\r\n", "\n"). replaceAll("\r", "\n"). split("\n"); Map result = new java.util.TreeMap(); for (int i = 0; i < env.length; i++) { String[] nv = env[i].split("="); if (nv.length > 1) { result.put(nv[0].trim(), nv[1].trim()); } } return result; } private static class Runner extends Thread { public static final int ERR_CANNOT_START = -1; public static final int PROC_KILLED = -2; public int exitCode = -1; private String cmd; private Process process; private String dir; private PrintWriter out; private PrintWriter err; private Reader in = null; private Reader processOut; private Reader processErr; private PrintWriter processIn; private String[] env = null; private boolean needKill; Runner(String cmd, String dir, PrintStream out, PrintStream err) { this.cmd = cmd; this.dir = dir; this.out = new PrintWriter(out); this.err = new PrintWriter(err); } Runner(String cmd, String dir, InputStream in, PrintStream out, PrintStream err) { this.cmd = cmd; this.dir = dir; this.in = new BufferedReader(new InputStreamReader(in)); this.out = new PrintWriter(out); this.err = new PrintWriter(err); } Runner(String cmd, String dir, Reader in, PrintWriter out, PrintWriter err, Map environment) { this.cmd = cmd; this.dir = dir; this.in = in; this.out = out; this.err = err; this.env = Strings.toStrings(environment); } void relieve() { if (process != null) { Files.pipe(processOut, out); Files.pipe(processErr, err); Files.pipe(in, processIn); } } static void pipe(InputStream in, OutputStream out, boolean isBlocking) throws IOException { byte[] buf = new byte[65500]; int nread; int navailable; int total = 0; synchronized (in) { while((navailable = isBlocking ? Integer.MAX_VALUE : in.available()) > 0 && (nread = in.read(buf, 0, Math.min(buf.length, navailable))) >= 0) { out.write(buf, 0, nread); total += nread; } } out.flush(); } public void run() { try { setLowestPriority(); process = Runtime.getRuntime().exec(cmd, env, new File(dir)); processOut = new BufferedReader(new InputStreamReader(process.getInputStream())); processErr = new BufferedReader(new InputStreamReader(process.getErrorStream())); processIn = new PrintWriter(process.getOutputStream()); while (true) { try { if (needKill) { process.destroy(); exitCode = PROC_KILLED; break; } exitCode = process.exitValue(); // If the process is still run we get and exception. The following lines // will be reached only when the task is closed. break; } catch( Exception e ) { relieve(); try { this.sleep(200); // Make the loop less tight... } catch( InterruptedException ie ) {} } } } catch (Exception e) { if (DEBUG) e.printStackTrace(System.err); if (err != null) { err.println(e); e.printStackTrace(err); } } relieve(); try { process.getInputStream().close(); process.getErrorStream().close(); } catch (Exception e) {}; } } /** * Runs a command in current directory * @param cmd the command to run; append '&' if no need to wait * @return false if return code is not 0 * *

    Examples: *
  • runCommand("notepad&")> launches Notepad
  • *
  • runCommand("rmdir xxx")> returns false * (unless you had a directory 'xxx' and it was just removed).
  • */ public static boolean runCommand(String cmd) { return runCommand(cmd, "."); } /** * Runs a command in specified directory * @param cmd the command to run; append '&' if no need to wait * @param dir starting directory name * @return false if return code is not 0 * *

    Example: *
  • runCommand("cmd /c dir .", "C:\\Program Files")>.
  • */ public static boolean runCommand(String cmd, String dir) { return runCommand(cmd, dir, System.out, System.err); } /** * Runs a command in current directory * @param cmd the command to run; append '&' if no need to wait * @param out command output stream * @param err command error stream * @return false if return code is not 0 * *

    Example: *
  • runCommand("cmd /c dir .", "C:\\Program Files", System.out, System.err)>.
  • */ public static boolean runCommand(String cmd, PrintStream out, PrintStream err) { return runCommand(cmd, ".", out, err); } /** * Runs a command in specified directory * @param cmd the command to run; append '&' if no need to wait * @param dir starting directory name * @param out command output stream * @param err command error stream * @return false if return code is not 0 * *

    Example: *
  • runCommand("cmd /c dir .", "C:\\Program Files", System.out, System.err)>.
  • */ public static boolean runCommand(String cmd, String dir, PrintStream out, PrintStream err) { return runCommand(cmd, dir, null, out, err); } /** * Runs a command in current directory * @param cmd the command to run; append '&' if no need to wait * @param in command input stream * @param out command output stream * @param err command error stream * @return false if return code is not 0 * *

    Example: *
  • runCommand("cmd /c dir .", "C:\\Program Files", System.in, System.out, System.err)>.
  • */ public static boolean runCommand(String cmd, InputStream in, PrintStream out, PrintStream err) { return runCommand(cmd, ".", in, out, err); } /** * Runs a command in specified directory * @param cmd the command to run; append '&' if no need to wait * @param dir starting directory name * @param in command input stream * @param out command output stream * @param err command error stream * @return false if return code is not 0 * *

    Example: *
  • runCommand("cmd /c dir .", "C:\\Program Files", System.in, System.out, System.err)>.
  • */ public static boolean runCommand(String cmd, String dir, InputStream in, PrintStream out, PrintStream err) { Reader br = in == null ? null : new BufferedReader(new InputStreamReader(in)); if (err == null) err = out; if (err == null) err = System.err; if (out == null) out = System.out; return runCommand(cmd, dir, br, new PrintWriter(out), new PrintWriter(err)); } /** * Runs a command in specified directory * @param cmd the command to run; append '&' if no need to wait * @param dir starting directory name * @param in command input reader * @param out command output writer * @param err command error writer * @return false if return code is not 0 * *

    Example: *
  • runCommand("cmd /c dir .", "C:\\Program Files", System.in, System.out, System.err)>.
  • */ public static boolean runCommand(String cmd, String dir, Reader in, PrintWriter out, PrintWriter err) { return runCommand(cmd, dir, in, out, err, null); } public static boolean runCommand(String cmd, String dir, Reader in, PrintWriter out, PrintWriter err, Map environment) { boolean isParallel = cmd.endsWith("&"); if (isParallel) cmd = cmd.substring(0, cmd.length() - 1); Runner process = new Runner(cmd, dir, in, out, err, environment); process.start(); if (isParallel) return true; while (process.isAlive()) { try { Thread.sleep(500); // process.relieve(); } catch( Exception e ) { } } // process.relieve(); System.gc(); //System.out.println("exitcode = " + process.exitCode); if (process.exitCode == -1) { return false; } else if (process.exitCode != 0) { if (err != null) err.println("runner: exit_code = " + process.exitCode); return false; } else { return true; } } /** * returns as string the output of a command * @param command String the command to run * @return String command output (from STDOUT) */ public static String getCommandOutput(String command) { StringWriter w = new StringWriter(); runCommand(command, getcwd(), null, new PrintWriter(w), null); if (w.getBuffer().length() > 0) { return w.toString(); } else { return null; } } /** * Wraps command line argument into quotes if it contains spaces * @param arg * @return wrapped value */ public static String commandLineArg(String arg) { return (arg.indexOf(' ') < 0) ? arg : ("\"" + arg + "\""); } /** * sets priority and returns previous priority * @param priority int * @return int the priority that was before */ public static int setPriority(int priority) { int currentPriority = Thread.currentThread().getPriority(); Thread.currentThread().setPriority(priority); return currentPriority; } /** * sets the lowest priority, Thread.MIN_PRIORITY * @return int the priority that was before */ public static int setLowestPriority() { return setPriority(Thread.MIN_PRIORITY); } } PK =2z5454com/myjavatools/lib/Web.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Web.java 5.0 11/15/04 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import static com.myjavatools.lib.Files.*; import static com.myjavatools.lib.Strings.*; import static com.myjavatools.lib.foundation.Objects.*; public class Web { protected static Pattern HTML_CHARSET_PATTERN = Pattern.compile(".*]+content=\"[^\"]*charset=([^\"\\s]*)\".*", Pattern.CASE_INSENSITIVE); /** * Detects charset from html contents * * @param s the char sequence with html content * @return charset name * *

    Examples: *
  • getHtmlCharset("") * returns "shift-jis".
  • */ public static String getHtmlCharset(CharSequence s) { if (isEmpty(s)) return null; Matcher matcher = HTML_CHARSET_PATTERN.matcher(s); return matcher.matches() ? matcher.group(1).toLowerCase() : null; } protected static Pattern XML_CHARSET_PATTERN = Pattern.compile(".*<\\?xml[^>]+encoding=\"([^\"]*)\".*", Pattern.CASE_INSENSITIVE); /** * Detects charset from xml contents * * @param s the char sequence with html content * @return charset name * *

    Examples: *
  • getXmlCharset("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") * returns "utf-8".
  • */ public static String getXmlCharset(CharSequence s) { if (isEmpty(s)) return null; Matcher matcher = XML_CHARSET_PATTERN.matcher(s); return matcher.matches() ? matcher.group(1).toLowerCase() : null; } /** * A short conversion table for IANA charsets and Java 1.3 "encodings". * You do not need them if you use Java 1.4 (and up) java.nio. */ private static Map CHARSET_TO_ENCODING; private static Map ENCODING_TO_CHARSET; private static void addCharset(String charset, String encoding) { CHARSET_TO_ENCODING.put(charset, encoding); ENCODING_TO_CHARSET.put(encoding, charset); } static { CHARSET_TO_ENCODING = new LinkedHashMap(); ENCODING_TO_CHARSET = new LinkedHashMap(); addCharset("iso-2022-jp", "ISO2022JP"); addCharset("iso-2022-cn-cns", "ISO2022CN_CNS"); addCharset("iso-2022-cn-gb", "ISO2022CN_GB"); addCharset("iso-2022-kr", "ISO2022KR"); addCharset("iso-8859-1", "ISO8859_1"); addCharset("iso-8859-2", "ISO8859_2"); addCharset("iso-8859-3", "ISO8859_3"); addCharset("iso-8859-4", "ISO8859_4"); addCharset("iso-8859-5", "ISO8859_5"); addCharset("iso-8859-6", "ISO8859_6"); addCharset("iso-8859-7", "ISO8859_7"); addCharset("iso-8859-8", "ISO8859_8"); addCharset("iso-8859-9", "ISO8859_9"); addCharset("iso-8859-13", "ISO8859_13"); addCharset("shift_jis", "SJIS"); addCharset("tis-620", "TIS620"); addCharset("utf-8", "UTF8"); addCharset("windows-1250", "Cp1250"); addCharset("windows-1252", "Cp1252"); addCharset("windows-1253", "Cp1253"); addCharset("windows-1254", "Cp1254"); addCharset("windows-1255", "Cp1255"); addCharset("windows-1256", "Cp1256"); addCharset("windows-1257", "Cp1257"); addCharset("windows-1258", "Cp1258"); addCharset("windows-31j", "MS932"); addCharset("windows-949", "MS949"); addCharset("windows-950", "MS950"); }; /** * gets IANA charset given Java encoding * @param encoding the Java charset * @return encoding name * * @deprecated should use java.nio.Charset */ public static String getCharsetByEncoding(String encoding) { if (encoding == null) return ""; java.nio.charset.Charset cs; return oneOf(ENCODING_TO_CHARSET.get(encoding), encoding.replace('_', '-'), ""); } /** * gets Java encoding given an IANA charset * @param charset the IANA charset * @return encoding name * */ public static String getEncodingByCharset(String charset) { if (charset == null) return ""; // java.nio.charset.Charset.forName(s); String candidate1 = charset.toLowerCase(); String candidate2 = candidate1.replace('-', '_'); return oneOf(CHARSET_TO_ENCODING.get(candidate1), CHARSET_TO_ENCODING.get(candidate2), charset.replace('-', '_'), ""); } /** * gets Java encoding of HTML contents * @param s HTML data * @return its most probable Java encoding * *

    Examples: *
  • getHtmlCharset("") * returns "SJIS".
  • * */ public static String getHtmlEncoding(CharSequence s) { return getEncodingByCharset(getHtmlCharset(s)); } /** * gets Java encoding of XML data * @param s XML data (first line is enough) * @return Java encoding to decode the data * *

    Example: *
  • getXmlEncoding("?xml version=\"1.0\" encoding=\"UTF-8"?>") * will return "UTF8".
  • * */ public static String getXmlEncoding(CharSequence s) { String charset = getXmlCharset(s); return getEncodingByCharset(charset); } /** * gets an input stream for a given url * @param url the universal resource locator * @return the input stream * @throws java.io.IOException * @throws java.lang.InstantiationException * *

    Example: *
  • getUrlInputStream(new URL("http://www.google.com/images/logo.gif")) * will return an input stream that contains the Google gif.
  • */ static public InputStream getUrlInputStream(java.net.URL url) throws java.io.IOException, java.lang.InstantiationException { java.net.URLConnection conn = url.openConnection(); conn.connect(); InputStream input = url.openStream(); if (input == null) { throw new java.lang.InstantiationException("Url " + url + " does not provide data."); } return input; } /** * Downloads a file from a specified URL * * @param url URL that points to a resource * @param filename the name of the file to store the contents * @return error message; an empty string if none * *

    Example: *
  • downloadFile(new URL("http://www.google.com/images/logo.gif"), "googlelogo.gif") * will download the gif, store it into the file, and return an empty string.
  • * */ public static String downloadFile(java.net.URL url, String filename) { try { writeToFile(getUrlInputStream(url), filename); } catch (Exception e) { return "error: " + e; } return ""; } /** * Downloads a file from a specified URL * * @param url URL string that points to a resource * @param filename the name of the file to store the contents * @return error message; an empty string if none * *

    Example: *
  • downloadFile("http://www.google.com/images/logo.gif", "googlelogo.gif") * will download the gif, store it into the file, and return an empty string.
  • * */ public static String downloadFile(String url, String filename) { try { downloadFile(new java.net.URL(url), filename); } catch (Exception e) { return "error: " + e; } return ""; } /** * sendMail sends emails. * * Borrowed from Slavik Dimitrovich, Richmond, Virginia * @see The original article * * @param from sender address * @param to receiver address * @param subj message subject * @param message message body * @throws java.io.MalformedURLException * @throws java.io.IOException */ public static void sendMail(String from, String to, String subj, String message) throws MalformedURLException, IOException { URLConnection connection = new URL("mailto:" + to).openConnection(); connection.setDoInput(false); connection.setDoOutput(true); connection.connect(); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println("From: \"" + from + "\" <" + from + ">"); out.println("To: " + to); out.println("Subject: " + subj); out.println(); out.println(message); out.close(); } /** * converts a name-value pair into an element of url string * @param name parameter name * @param value parameter value * @return a string like "name=value", where value is url-encoded
    * returns an empty string if value is empty * *

    Example: *
  • urlEncode("dir", "C:\\Program Files"") * will return "dir=C%3A%5CProgram+Files".
  • * */ public static final String urlEncode(String name, String value) { try { return isEmpty(value) ? "" : (name + "=" + URLEncoder.encode(value, "UTF8")); } catch (UnsupportedEncodingException ex) { return null; } } /** * produces a GET request string for a uri and a collection of parameters * @param href url where to send the request * @param nvPairList a collection of (already url-encoded) name-value pair * strings that look like "name=value" * @return formatted url string, see example * *

    Example: *
  • urlEncode("http://example.myjavatools.com/mycomputer", * new ArrayList(new String[] {"dir=C%3A%5CProgram+Files", "cmd=dir+*"})) * will return "http://example.myjavatools.com/mycomputer?dir=C%3A%5CProgram+Files&cmd=dir+*".
  • */ public static final String url(String href, Collection nvPairList) { String stringifiedAttributes = join("&", nvPairList); return href + (isEmpty(stringifiedAttributes) ? "" : "?" + stringifiedAttributes); } /** * produces a GET request string for a uri and request parameters * @param uri where to send the request * @param paramvalue String... * (etc) * @return formatted url string, see examples * *

    Examples: *
  • urlEncode("http://example.myjavatools.com/mycomputer", * "dir, "C:\Program Files")) * will return "http://example.myjavatools.com/mycomputer?dir=C%3A%5CProgram+Files".
  • * *
  • urlEncode("http://example.myjavatools.com/mycomputer", * "dir, "C:\Program Files", "cmd", "dir *") * will return "http://example.myjavatools.com/mycomputer?dir=C%3A%5CProgram+Files&cmd=dir+*".
  • * *
  • urlEncode("http://mycomputer", * "dir, "C:\Program Files", "cmd", "dir *", "login", "root", "password", "urowned") * will return "http://mycomputer?dir=C%3A%5CProgram+Files&cmd=dir+*&login=root&password=urowned".
  • */ public static final String url(String uri, String ... paramvalue) { StringBuffer buffer = new StringBuffer(uri); String separator = "?"; for (int i = 0; i < paramvalue.length; i+=2) { String nvpair = urlEncode(paramvalue[i], paramvalue[i+1]); if (!isEmpty(nvpair)) { buffer.append(separator); buffer.append(nvpair); separator = "&"; } } return buffer.toString(); } /** * converts a string into something that could be literally placed into a web page, * that is, replaces CR with CRLF (to be polite with browser's 'view source'), * replaces all '<' with "<", and html-encodes (&#dddd;) characters above low-ascii. * * @param s string to convert * @return converted string */ public static final String toWebReadable(String s) { if (isEmpty(s)) return ""; LineNumberReader in = new LineNumberReader(new StringReader(s)); StringBuffer out = new StringBuffer(); String buf; try { while ((buf = in.readLine()) != null) { for (int i = 0; i < buf.length(); i++) { char c = buf.charAt(i); int k = c; if (c == '&') { out.append("&"); } else if (c == '<') { out.append("<"); } else if (c > 0x7f) { out.append("&#" + k + ";"); } else { out.append(c); } } out.append("\r\n"); } } catch (Exception e) {}; return out.toString(); } /** * surrounds a string with single quotes (apostrophes), which is convenient for * generating Javascript code, but just senseless otherwise. * * @param s string to quote * @return "'" + s + "'" */ public static final String quote(String s) { return "'" + s + "'"; } } PK A0v+TT!com/myjavatools/lib/ZipInput.javapackage com.myjavatools.lib; import java.io.*; import java.util.*; import java.util.zip.*; import static com.myjavatools.lib.Bytes.*; /** *

    Title: MyJavaTools: ZippedInput

    *

    Description: Extends ZipInputStream functionality. * Good for Java 1.4 and up.

    *

    Copyright: This is public domain; * The right of people to use, distribute, copy or improve the contents of the * following may not be restricted.

    * * @version 1.4 * @author Vlad Patryshev */ public class ZipInput { ZipInputStream zis = null; ZipEntry ze = null; /** * initializes ZipInput with InputStream * @param is InputStream the source of data */ public ZipInput(InputStream is) { zis = new ZipInputStream(is); } /** * initializes ZipInput with data * @param data byte[] the source data represented as bytes */ public ZipInput(byte[] data) { this(new ByteArrayInputStream(data)); // System.out.println("crc is " + Long.toHexString(Tools.crc32(data))); } /** * initializes ZipInput with data * @param data char[] the source data represented as chars (a byte per char) */ public ZipInput(char[] data) { this(toBytes(data)); // System.out.println("crc is " + Long.toHexString(Tools.crc32(Tools.toBytes(data)))); } /** * moves to next ZipEntry * @throws IOException when there are problems reading the input * @return boolean true if there is a next entry; false otherwise */ public boolean next() throws IOException { return (ze = zis.getNextEntry()) != null; } /** * gets current ZipEntry * @return ZipEntry current entry */ public ZipEntry getEntry() { return ze; } /** * gets the name of current ZipEntry * @return String the entry name */ public String getEntryName() { return ze.getName(); } /** * gets timestamp of current zip entry * @return long the entry timestamp (ms since 1/1/70) */ public long getEntryTime() { return ze.getTime(); } /** * gets the size of current entry data * @return long the number of bytes in current entry data */ public long getEntrySize() { return ze.getSize(); } /** * checks whether current ZipEntry is a directory * @return boolean true if it is directory, false otherwise */ public boolean isEntryDirectory() { return ze.isDirectory(); } /** * retrieves the contents of current ZipEntry data * @throws IOException if could not read the data * @return byte[] the contents of current entry data */ public byte[] getBytes() throws IOException { if (ze == null || ze.isDirectory()) return new byte[0]; int size = (int)getEntrySize(); if (size < 0) { // Yeah, right... unknown length. How can we treat it, I wonder... List chunkList = new ArrayList(); int bcount = 0; int total = 0; final int bufsize = 65500; while (bcount >= 0) { byte[] buffer = new byte[bufsize]; chunkList.add(buffer); int pos = 0; while ( (bcount = zis.read(buffer, pos, buffer.length - pos)) > 0) { // System.out.print("-" + bcount + "- "); pos += bcount; } total += pos; } byte[] buffer = new byte[total]; int pos = 0; for (Iterator i = chunkList.iterator(); i.hasNext();) { System.arraycopy(i.next(), 0, buffer, pos, Math.min(bufsize, total - pos)); pos += bufsize; } return buffer; } byte[] buffer = new byte[(int)getEntrySize()]; int bcount = 0; int pos = 0; while((bcount = zis.read(buffer, pos, buffer.length - pos)) > 0) { pos += bcount; } return buffer; } /** * gets the contents of current ZipEntry data as characters * @param encoding String encoding to use * @throws IOException when could not read the data * @return String unzipped and decoded data */ public String getChars(String encoding) throws IOException { return Strings.decode(getBytes(), encoding); } } PK 54@&&0com/myjavatools/lib/foundation/AbstractMap2.javapackage com.myjavatools.lib.foundation; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.HashMap; /** *

    AbstractMap2 is a partial implementation of * two-parameter map.

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 12/10/2006 */ public abstract class AbstractMap2 implements Map2 { protected static boolean equal(Object o1, Object o2) { return o1 == o2 || o1 != null && o1.equals(o2); } /** * An entry of a two-parameter map. */ public static class Entry implements Map2.Entry { private X key1; private Y key2; private V value; /** * Constructor * @param key1 X * @param key2 Y * @param value V */ public Entry(X key1, Y key2, V value) { this.key1 = key1; this.key2 = key2; this.value = value; } /** * {@inheritDoc} */ public X getKey1() { return key1; } /** * {@inheritDoc} */ public Y getKey2() { return key2; } /** * {@inheritDoc} */ public V getValue() { return value; } /** * {@inheritDoc} */ public V setValue(V value) { V old = this.value; this.value = value; return old; } public boolean equals(Object other) { if (other == null || !(other instanceof Map2.Entry)) { return false; } Map2.Entry otherEntry = (Map2.Entry) other; return equal(key1, otherEntry.getKey1()) && equal(key2, otherEntry.getKey2()); } private int hashCode(Object o) { return o == null ? 0 : o.hashCode(); } public int hashCode() { return (hashCode(key1) * 79 + hashCode(key2)) * 79 + hashCode(value); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("). append(getKey1()). append(","). append(getKey2()). append(")->"). append(getValue()); return sb.toString(); } } /** * Default constructor */ public AbstractMap2() { } /** * {@inheritDoc} */ public int size() { return entrySet().size(); } /** * {@inheritDoc} */ public boolean isEmpty() { return size() == 0; } /** * {@inheritDoc} */ public boolean containsValue(Object value) { for (Map2.Entry e : entrySet()) { if (equal(value, e.getValue())) { return true; } } return false; } /** * {@inheritDoc} * * This implementation iterates over entrySet() searching for an * entry with the specified keys. If such an entry is found, * true is returned. If the iteration terminates without * finding such an entry, false is returned. Note that this * implementation requires linear time in the size of the map; many * implementations will override this method. * * @param key1 first key * @param key2 second key * @return true if this map contains a mapping for the specified * pair of keys. */ public boolean containsKeyPair(Object key1, Object key2) { for (Map2.Entry e : entrySet()) { if (equal(key1, e.getKey1()) && equal(key2, e.getKey2())) { return true; } } return false; } /** * {@inheritDoc} * * This implementation iterates over entrySet() searching for an * entry with the specified pair of keys. If such an entry is found, * the entry's value is returned. If the iteration terminates without * finding such an entry, null is returned. Note that * this implementation requires linear time in the size of the map; * many implementations will override this method. * * * @param key1 first key * @param key2 second key * @return the value to which this map maps the specified keys. * * @see #containsKeyPair(X,Y) */ public V get(X key1, Y key2) { for (Map2.Entry e : entrySet()) { if (equal(key1, e.getKey1()) && equal(key2, e.getKey2())) { return e.getValue(); } } return null; } /** * {@inheritDoc} * * This implementation always throws an * UnsupportedOperationException. */ public V put(X key1, Y key2, V value) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * This implementation iterates over entrySet() searching for an * entry with the specified pair of keys. If such an entry is found, * its value is obtained with its getValue operation, * the entry is removed from the collection of entries with the iterator's * remove operation, and the saved value is returned. If the * iteration terminates without finding such an entry, null is * returned. Note that this implementation requires linear time in the * size of the map; many implementations will override this method.

    */ public V remove(X key1, Y key2) { for (Iterator> i = entrySet().iterator(); i.hasNext();) { Map2.Entry e = i.next(); if (equal(key1, e.getKey1()) && equal(key2, e.getKey2())) { i.remove(); return e.getValue(); } } return null; } /** * {@inheritDoc} * * This implementation iterates over the specified map's * entrySet() collection, and calls this map's put * operation once for each entry returned by the iteration.

    */ public void putAll(Map2 source) { for (Map2.Entry e : source.entrySet()) { put(e.getKey1(), e.getKey2(), e.getValue()); } } /** * {@inheritDoc} * * This implementation calls entrySet().clear(). */ public void clear() { entrySet().clear(); } public abstract Set keySet1(); public abstract Set keySet2(); transient volatile Collection values = null; /** * {@inheritDoc} * * This implementation returns a collection and is based * on the map's entrySet. */ public Collection values() { if (values == null) { values = new AbstractCollection() { public Iterator iterator() { return new Iterator() { private Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap2.this.size(); } public boolean contains(Object v) { return AbstractMap2.this.containsValue(v); } }; } return values; } /** * {@inheritDoc} * * This implementation builds the map on every call. Better implementations * are available if entries are indexed. */ public Map curry1(X key1) { Map result = new HashMap(); for (Map2.Entry e : entrySet()) { if (e.getKey1().equals(key1)) { result.put(e.getKey2(), e.getValue()); } } return result; } /** * {@inheritDoc} * * This implementation builds the map on every call. Better implementations * are available if entries are indexed. */ public Map curry2(Y key2) { Map result = new HashMap(); for (Map2.Entry e : entrySet()) { if (e.getKey2().equals(key2)) { result.put(e.getKey1(), e.getValue()); } } return result; } /** * {@inheritDoc} */ public abstract Set> entrySet(); /** * Compares the specified object with this map for equality. Returns * true if the given object is also a map2 and the two maps * represent the same mappings. * * @param o object to be compared for equality with this map. * @return true if the specified object is equal to this map. */ public boolean equals(Object o) { if (o == this) { return true; } if (o == null || !(o instanceof Map2)) { return false; } return entrySet().equals(((Map2)o).entrySet()); } /** * @return the hash code value for this map. */ public int hashCode() { return entrySet().hashCode(); } /** * @return a String representation of this map. */ public String toString() { StringBuilder sb = new StringBuilder("{"); for (Map2.Entry e : entrySet()) { if (sb.length() > 1) { sb.append(", "); } sb.append("("). append(e.getKey1()). append(","). append(e.getKey2()). append(")->"). append(e.getValue()); } sb.append("}"); return sb.toString(); } } PK i5>  ,com/myjavatools/lib/foundation/AllTests.javapackage com.myjavatools.lib.foundation; import junit.framework.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class AllTests extends TestCase { public AllTests(String s) { super(s); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(com.myjavatools.lib.foundation.TestFilter.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestFunction.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestFunction2.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestAbstractMap2.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestIndexedMap2.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestIterators.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestPair.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestObjects.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestPair.class); suite.addTestSuite(com.myjavatools.lib.foundation. TestRestrictedFunctionEntrySet.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestRestrictedMapEntrySet.class); suite.addTestSuite(com.myjavatools.lib.foundation.TestMaps.class); return suite; } } PK `4#vJ  6com/myjavatools/lib/foundation/CompoundCollection.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)CompoundCollection.java 6.0 04/28/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * CompoundCollection is a Collection that consists of other Collections, * viewed as one Collection. * * @version 6.0 04/28/06 * @see java.util.Collection * @see Iterators * @since 5.0 */ class CompoundCollection extends ShrinkingCompoundCollection { /** * This collection takes bulk additions. */ List> bulkAppendage; /** * This collection takes bulk additions. */ List appendage; /** * Instantiates a compound collection from vararg list of components. * @param components Collection[] */ public CompoundCollection(Collection... components) { this(Arrays.asList(components)); } /** * Instantiates a compound collection, saving appendageCollection * for future use. * @param components Collection * @param bulkAppendage Collection that will be used for adding new collections * @param dummy to differentiate this constructor */ private CompoundCollection( Collection> components, List> bulkAppendage, boolean dummy) { super(new ShrinkingCompoundCollection> (components, bulkAppendage)); this.bulkAppendage = bulkAppendage; this.appendage = new LinkedList(); this.bulkAppendage.add(this.appendage); } /** * Instantiates a compound collection from a collection of components. * @param components Collection */ public CompoundCollection(Collection> components) { this(components, new LinkedList>(), false); } /** * Adds the specified collection to the list, so that * its element can be listed as the elements of this view collection. * No action if the collection being added is empty.

    * * @param toAdd collection to add to this collection. * @return true if this collection has changed * as a result of the call. * @see #add(Object) */ public boolean addAll(Collection toAdd) { if (toAdd.isEmpty()) return false; bulkAppendage.add(toAdd); return true; } /** * Adds an element to the collection. Returns true * meaning the collection changed as a result of the call. * In this implementation, a singlton collection containing the element is * being added.

    * * @param element element being added to this collection. * @return true if the collection changed as a result of the call. */ public boolean add(T element) { return appendage.add(element); } } PK 4>%ǒ4com/myjavatools/lib/foundation/CompoundIterable.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)CompoundIterable.java 6.0 04/28/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * CompoundIterable is an Iterable that is composed of several other iterable. * Its iterator() returns an iterator that scans through the components' * iterators, one after another. * * @version 6.0 04/28/06 * * @see java.util.Iterable * @see com.myjavatools.lib.foundations.Iterators * @since 5.0 */ public class CompoundIterable implements Iterable { private final Iterable> components; /** * builds a CompoundIterable from a vararg list of Iterable components * @param components Iterable... */ public CompoundIterable(Iterable... components) { this(Arrays.asList(components)); } /** * builds a CompoundIterable from an Iterable container of Iterable components * @param components Iterable> */ public CompoundIterable(Iterable> components) { this.components = components; } public Iterator iterator() { return new CompoundIterator(components.iterator()); } } PK I4V GG4com/myjavatools/lib/foundation/CompoundIterator.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)CompoundIterator.java 6.0 04/28/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * CompoundIterator is an Iterator that walks over iterators of its components, * one after another. * You are not supposed to use this class directly; it is being used by other * classes, like CompoundIterable and CompoundCollection. * * @version 6.0 04/28/06 * * @see java.util.Iterator * @see java.util.Iterable * @see Iterators * @since 5.0 */ class CompoundIterator implements Iterator { private final Iterator> outerIterator; private Iterator currentIterator = null; CompoundIterator(Iterator> outerIterator) { this.outerIterator = outerIterator; } /** @return true if the iterator has more elements. */ public boolean hasNext() { while (currentIterator == null || !currentIterator.hasNext()) { if (!outerIterator.hasNext()) { return false; } else { currentIterator = outerIterator.next().iterator(); } } return true; } /** @return the next element in the iteration. */ public T next() { if (hasNext()) { return currentIterator.next(); } throw new NoSuchElementException(); } /** * Removes from the underlying collection the last element returned by the * iterator. */ public void remove() { if (currentIterator == null) throw new IllegalStateException(); currentIterator.remove(); } } PK 5B^"mm*com/myjavatools/lib/foundation/Filter.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Filter.java 6.0 04/28/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * Filter is a Function that returns Boolean values; boolean accept() is * an alias for Function.apply(). A good example of Filter is java.io.FileFilter, * unfortunately not derived from Filter. To implement this class you should define * accept(). * * @version 6.0 04/28/06 * * @see Function * @see java.util.Iterator * @since 5.0 */ public abstract class Filter extends Function { /** * checks whether an object is accepted by the filter * @param x T an element to check for acceptance * @return boolean true if x is accepted, false otherwise */ public abstract boolean accept(T x); /** * Filter.apply() is the same as accept(); * @param x T an element to which this filter is applied * @return Boolean result of applying this filter to x */ public Boolean apply(T x) { return accept(x); } /** * creates a filter that accepts only x such that f(x) > 0 * @param f Function<T,Double> * @return Filter as defined above */ public static Filter toFilter(final Function f) { return new Filter() { public boolean accept(T x) { return f.apply(x) > 0; } }; } /** * Returns filtered iterator * @param source Iterator original iterator * @return Iterator filtered iterator * the resulting iterator will contain only those elements of source that * satisfy this filter * *

    Example: *

    new Filter<String>() { boolean accept(String s) { return s.startsWith("M"); }}.
       * filter(Arrays.asList(new String[] {"New", "Magic", "Logic"}).iterator());
       *  
    * returns an iterator returning just "Magic".

    */ public Iterator filter(final Iterator source) { return new Iterator() { T pointer; boolean found = false; boolean canRemove = false; public boolean hasNext() { if (found) { return true; } canRemove = false; while(source.hasNext()) { pointer = source.next(); if (accept(pointer)) { found = true; return true; } } return false; } public T next() throws NoSuchElementException { if (!found && !hasNext()) { throw new NoSuchElementException(); } else { found = false; canRemove = true; return pointer; } } public void remove() { if (canRemove) { source.remove(); found = false; } else { throw new IllegalStateException(); } } }; } /** * filters an Iterable * @param iterable Iterable * @return Iterable (view) that contains values that this filter approves */ public Iterable filter(final Iterable iterable) { return new Iterable() { public Iterator iterator() { return Filter.this.filter(iterable.iterator()); } }; } /** * Creates conjunction of filters. * @param filters (vararg) * @return Filter that returns true only on those x for which * all filters return true */ public static Filter and(final Filter... filters) { return new Filter() { public boolean accept(T x) { for (Filter filter : filters) { if (!filter.accept(x)) return false; } return true; } }; } /** * Creates disjunction of filters. * @return Filter that returns false only on those x for which * all filters return false */ public static Filter or(final Filter... filters) { return new Filter() { public boolean accept(T x) { for (Filter filter : filters) { if (filter.accept(x)) return true; } return false; } }; } /** * Creates negation of a filter. * @param filter Filter * @return Filter that returns true on those x for which source filter return false */ public static Filter not(final Filter filter) { return new Filter() { public boolean accept(T x) { return !filter.accept(x); } }; } } PK }4Ҥ?KK,com/myjavatools/lib/foundation/Function.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Function.java 6.0 05/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * Function is an abstract class that represents the mathematical notion of * function: X -> Y. To implement a function, you need to define method apply(): * Y y = function.apply(X x). * * @version 6.0 05/04/06 * * @see Filter * @see Maps * @see java.util.Map * @since 5.0 */ public abstract class Function { /** * the only method you should implement * @param x X the function parameter * @return Y the function value at x */ public abstract Y apply(X x); /** * Restricts this function to a specified Set, returning a map * with keys from the set. * @param keys Set<X> keys * @return Map<X,Y> that maps keys from the set to function values on those * keys */ public Map toMap(final Set keys) { return new AbstractMap() { Set> entrySet = new RestrictedMapEntrySet(this, keys); public Set> entrySet() { return entrySet; } public boolean containsKey(Object o) { return keys.contains(o); } public Y get(Object key) { return containsKey(key) ? Function.this.apply((X)key) : null; } }; } /** * Restricts this function to a specified Collection, returning a map on the * set of collection entries * @param keys Collection<X> keys * @return Map<X,Y> that maps keys from the collection to function values * on those keys */ public Map toMap(Collection keys) { return toMap(new HashSet(keys)); } /** * turns a Map into a Function * @param map Map<X,Y> source map * @return Function<X,Y> function that returns map.get(x) for each X x */ public static Function forMap(final Map map) { return new Function() { public Y apply(X x) { return map.get(x); } }; } /** * turns a Map into a Function * @param map Map<X,Y> source map * @return Function<X,Y> function that returns map.get(x) for each X x * @deprecated use forMap instead */ public static Function function(Map map) { return forMap(map); } /** * Returns a function defied by a map and a default value * * @param map Map<X,Y> * @param defaultValue Y * @return Function f such that f(x)=map.get(x) if map.containsKey(x), * and defaultValue otherwise. */ public static Function forMap(final Map map, final Y defaultValue) { return new Function() { public Y apply(X x) { return map.containsKey(x) ? map.get(x) : defaultValue; } }; } /** * Returns a function defied by a map and a default value * * @param map Map<X,Y> * @param defaultValue Y * @return Function f such that f(x)=map.get(x) if map.containsKey(x), * and defaultValue otherwise. * @deprecated use forMap instead. */ public static Function function(Map map, Y defaultValue) { return forMap(map, defaultValue); } /** * applies Function to a List * @param domain List * @return List */ public List apply(final List domain) { return new AbstractList() { /** * Returns true if the function maps one or more keys from domain * to the specified value. * * @param value value whose presence in this map is to be tested. * @return true if the function's value on one or more keys is the specified * value. * Note that this method is extremely inefficient - as probably any implementation * of contains() on an unstructured, non-indexed collection. */ public boolean contains(Object value) { for (X x : domain) { Y y = Function.this.apply(x); if (Objects.equal(y, value)) { return true; } } return false; } /** * @return the number of elements in this collection. */ public int size() { return domain.size(); } /** * @return an Iterator that scans over the values of function on domain */ public Iterator iterator() { return Function.this.apply(domain.iterator()); } /** * Returns the element at the specified position in this list. * * @param index index of element to return. * @return the element at the specified position in this list. * * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). */ public Y get(int index) { return Function.this.apply(domain.get(index)); } }; } /** * applies Function to an Iterator * @param iterator Iterator * @return Iterator that lists values of function applied to elements returned * by the original iterator * *

    Example: *

    new Function<String, Integer>() {
       *               Integer apply(String s) { return s.length(); } }.
       *                apply(
       *                Arrays.asList(new String[] {"One", "Two", "Three"}).iterator());
    * returns an iterator returning 3, 3, 5.

    */ public Iterator apply(final Iterator iterator) { return new Iterator() { public boolean hasNext() { return iterator.hasNext(); } public Y next() { return Function.this.apply(iterator.next()); } public void remove() { iterator.remove(); } }; } /** * applies Function to an Iterable * @param iterable Iterable * @return Iterable that contains values of function applied to elements * of the original iterable */ public Iterable apply(final Iterable iterable) { return new Iterable() { public Iterator iterator() { return Function.this.apply(iterable.iterator()); } }; } /** * Returns a composition f.g : W->Y of two functions, * g:W->X and f(which is this Function): X->Y. * Compostion is defined as a function h such that * h(x) = f(g(x)) for each w. * * @param g Function<W,X> * @return Function<W,Y> composition of g and f */ public Function compose(Function g) { return compose(g, this); } /** * Returns a compostion f.g : X->Z of two functions, f: X->Y and g: Y->Z. * Compostion is defined as a function h such that * h(x) = g(f(x)) for each x. * * @param f Function<X,Y> * @param g Function<Y,Z> * @return Function<X,Z> composition of f and g */ public static Function compose(final Function f, final Function g) { return new Function () { public Z apply(X x) { return g.apply(f.apply(x)); } }; } public static Function id() { return new Function() { public X apply(X x) { return x; } }; } } PK A5_`-com/myjavatools/lib/foundation/Function2.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Function.java 6.0 12/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * Function2 is an abstract class that represents the mathematical notion of * two-parameter function: X x Y -> Z. To implement a function, you need to define method apply(): * Z z = function.apply(X x, Y y). * * @version 6.0 12/06/06 * * @see Filter * @see Maps * @see Function * @since 6.0 */ public abstract class Function2 { /** * the only method you should implement * @param x X the function parameter * @param y Y the function parameter * @return Z the function value at (x,y) */ public abstract Z apply(X x, Y y); /** * First component projection. * @return Function2 that returns its first parameter */ public static Function2 p1() { return new Function2() { public X apply(X x, Y y) { return x; } }; } /** * Second component projection. * @return Function2 that returns its second parameter */ public static Function2 p2() { return new Function2() { public Y apply(X x, Y y) { return y; } }; } /** * Converts a two-parameter function to a function on pairs, (X x, Y y). * @return Function that takes a pair (actually, a Map.Entry, which is * a popular interface that represents pairs of objects) and returns the value * of the original function on the components of the pair. * * That is, for f: X x Y -> Z, the resulting function, when applied to (x,y), * will return f(x,y). */ public Function,Z> toFunction() { return new Function,Z>() { public Z apply(Map.Entry pair) { return Function2.this.apply(pair.getKey(), pair.getValue()); } }; } /** * Creates a two-parameter function for a function defined on pairs. * * @param f Function that takes Map.Entry as an argument and returns * an instance of Z * @return Function2 defined on X x Y, such that for X x and Y y it returns * f((x,y)). */ public static Function2 forFunction(final Function,Z> f) { return new Function2() { public Z apply(X x, Y y) { return f.apply(new Pair(x,y)); } }; } /** * Creates a two-parameter function for a "cascade map". * * @param map <X,Map<Y,Z>>Map * @param defaultValue Z default function value for parameters that are not * contained as keys in Map * @return Function2 defined on X x Y and taking values in * Z. For a map m, an X x, and * a Y y, the value of the function is calculated like this: * m.get(x).get(y). If any of these get() returns null, * the function returns defaultValue. */ public static Function2 forMap(final Map> map, final Z defaultValue) { return new Function2() { public Z apply(X x, Y y) { Map curry = map.get(x); return curry == null || !curry.containsKey(y) ? defaultValue : curry.get(y); } }; } /** * Creates a two-parameter function for a "cascade map". * * @param map <X,Map<Y,Z>>Map * @return Function2 defined on X x Y and taking values in * Z. For a map m, an X x, and * a Y y, the value of the function is calculated like this: * m.get(x).get(y). If any of these get() returns null, * the function returns null. */ public static Function2 forMap(final Map> map) { return forMap(map, null); } /** * Creates a (virtual) map for a two-parameter function. * @param xKeys Set the set of keys for the first argument * @param yKeys Set the set of keys for the second argument * @return Map a cascade map that for an x from xKeys and a y from yKeys * get(x).get(y) returns f(x,y). */ public Map> toMap(final Set xKeys, final Set yKeys) { return new AbstractMap>() { private final Function> xToMap = new Function>() { public Map apply(X x) { return curry1(x).toMap(yKeys); } }; public Set>> entrySet() { return new RestrictedFunctionEntrySet>(xToMap, xKeys); } }; } /** * Swaps function arguments. * * @return Function2 such that its arguments are in reverse order: * g(y,x) = f(x,Y). */ public Function2 swap() { return new Function2() { public Z apply(Y y, X x) { return Function2.this.apply(x, y); } }; } /** * Curries the function by the first argument. * @param x X * @return Function that for each Y y returns f(x,y). */ public Function curry1(final X x) { return new Function() { public Z apply(Y y) { return Function2.this.apply(x, y); } }; } public Z zz(X x) { return null; } /** * Curries the function by the second argument. * @param y Y * @return Function that for each X x returns f(x,y). */ public Function curry2(final Y y) { return new Function() { public Z apply(X x) { return Function2.this.apply(x, y); } }; } /** * Returns a compostion f.g : XxY->T of a two-parameter function, f: XxY->Z * and g: Z->T. * Compostion is defined as a function h such that * h(x,y) = g(f(x,y)) for each pair x,y. * * @param f Function2<X,Y,Z> * @param g Function<Z,T> * @return Function<X,Y,T> composition of f and g */ public static Function2 compose(final Function2 f, final Function g) { return new Function2 () { public T apply(X x, Y y) { return g.apply(f.apply(x, y)); } }; } /** * Returns a compostion (f,g).h : AxB->Z of a two-parameter function, * h: XxY->Z and two single-parameter functions, f:A->Z and g:B->Y. * Compostion is defined as a function q such that * q(a,b) = h(f(a),g(b))) for each pair a,b. * * @param f Function<A,X> * @param g Function<B,Y> * @param h Function2<X,Y,Z> * @return Function<A,B,Z> composition of (f,g) and h. */ public static Function2 compose(final Function f, final Function g, final Function2 h) { return new Function2 () { public Z apply(A a, B b) { return h.apply(f.apply(a), g.apply(b)); } }; } } PK 5`㤛//3com/myjavatools/lib/foundation/IndexedHashMap2.javapackage com.myjavatools.lib.foundation; import java.util.*; /** *

    IndexedHashMap2 is an class that implements a * two-parameter map with indexes for both parameters; entries are stored * in a HashMap.

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 12/10/2006 */ public class IndexedHashMap2 extends IndexedMap2 { Set> entrySet = new HashSet>(); /** * {@inheritDoc} * * This implementation uses HashSet for storing entries. */ public Set> entrySet() { return entrySet; } } PK P5kBDD/com/myjavatools/lib/foundation/IndexedMap2.javapackage com.myjavatools.lib.foundation; import java.util.*; /** *

    IndexedMap2 is an abstract class that implements a * two-parameter map with indexes for both parameters.

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 12/10/2006 */ public abstract class IndexedMap2 extends AbstractMap2 { Map>> index1 = new HashMap>>(); Map>> index2 = new HashMap>>(); /** * Default constructor. */ public IndexedMap2() { super(); } protected Entry getEntry(Object key1, Object key2) { Map> m = index1.get(key1); return m == null ? null : m.get(key2); } protected Map> ensureSlot1(X key1) { Map> m = index1.get(key1); if (m == null) { index1.put(key1, m = new HashMap>()); } return m; } protected Map> ensureSlot2(Y key2) { Map> m = index2.get(key2); if (m == null) { index2.put(key2, m = new HashMap>()); } return m; } /** * {@inheritDoc} * * This implementation uses two indexes. */ @Override public V get(X key1, Y key2) { Entry entry = getEntry(key1, key2); return entry == null ? null : entry.getValue(); } /** * {@inheritDoc} * * This implementation uses and updates two indexes. */ public V put(X key1, Y key2, V value) { Map> m = ensureSlot1(key1); Entry oldEntry = m.get(key2); if (oldEntry != null) { entrySet().remove(oldEntry); } Entry newEntry = new Entry(key1, key2, value); entrySet().add(newEntry); ensureSlot1(key1).put(key2, newEntry); ensureSlot2(key2).put(key1, newEntry); return oldEntry == null ? null : oldEntry.getValue(); } /** * {@inheritDoc} * * This implementation returns a Set that subclasses AbstractSet and is based * on the map's entrySet. */ public Set keySet1() { return index1.keySet(); } /** * {@inheritDoc} * * This implementation returns a Set that subclasses AbstractSet and is based * on the map's entrySet. */ public Set keySet2() { return index2.keySet(); } /** * {@inheritDoc} * * This implementation uses index to check for key pair presence. * * @param key1 first key * @param key2 second key * @return true if this map contains a mapping for the specified * pair of keys. */ @Override public boolean containsKeyPair(Object key1, Object key2) { return getEntry(key1, key2) != null; } /** * {@inheritDoc} * * This implementation uses index to retrieve an entry with the specified * pair of keys. */ // @Override public V remove(X key1, Y key2) { Entry entry = getEntry(key1, key2); if (entry == null) { return null; } entrySet().remove(entry); this.ensureSlot1(key1).remove(key2); this.ensureSlot2(key2).remove(key1); return entry.getValue(); } private Function, V> entryToValue = new Function,V>() { public V apply(Map2.Entry entry) { return entry.getValue(); } }; /** * {@inheritDoc} * * This implementation uses the index to return a Map<Y,V> * view of Map<Y,Entry<X,Y,Z>> map that is stored in index. */ public Map curry1(X key1) { Map> entries = index1.get(key1); return entries == null ? Collections.EMPTY_MAP : Maps.compose(entries, entryToValue); } /** * {@inheritDoc} * * This implementation uses the index to return a Map<X,V> * view of Map<Y,Entry<X,Y,Z>> map that is stored in index. */ public Map curry2(Y key2) { Map> entries = index2.get(key2); return entries == null ? Collections.EMPTY_MAP : Maps.compose(entries, entryToValue); } } PK 58 B**3com/myjavatools/lib/foundation/IndexedTreeMap2.javapackage com.myjavatools.lib.foundation; import java.util.*; /** *

    IndexedHashMap2 is an class that implements a * two-parameter map with indexes for both parameters; entries are stored * in a TreeMap.

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 12/10/2006 */ public class IndexedTreeMap2 extends IndexedMap2 { Set> entrySet = new TreeSet>(); /** * {@inheritDoc} * * This implementation uses TreeSet for storing entries. */ public Set> entrySet() { return entrySet; } } PK U4-com/myjavatools/lib/foundation/Iterators.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Iterators.java 6.0 05/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the content of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * Iterators is a utility class that contains static methods for iterators * * @version 6.0 05/04/06 * @see java.util.Collection * @see java.util.Iterator * @see Filter * @since 5.0 */ public abstract class Iterators { /** * Creates an Iterator view of an Iterable consisting of Iterators * * @param outerLoop Iterable <? extends Iterator<? extends T>> source iterators * @return Iterator a compound iterator that scans the first iterator from * the sequence, then the second, etc. * * Can be used with varargs: cat(iterator1, iterator2, iterator3) and * with arrays: cat(iterators[]). * *

    Example: *

    
       * List list1 = Arrays.asList(new String[] {"One", "Two", "Three"});
       * List list2 = Arrays.asList(new String[] {"Four", "Five", "Six"});
       * List list3 = Arrays.asList(new String[] {"One", "Two", "Three", "Four", "Five", "Six"}
       * cat(Arrays.asList(new Iterator {list1.iterator(), list2.iterator()}))
    * returns the same as list3.iterator().

    */ public static Iterator cat(final Iterable > outerLoop) { return new Iterator() { Iterator > iterator = outerLoop.iterator(); Iterator current = null; public boolean hasNext() { while (current == null || !current.hasNext()) { if (!iterator.hasNext()) { return false; } current = iterator.next(); } return true; } public T next() { if (!hasNext()) throw new NoSuchElementException(); return current.next(); } public void remove() throws IllegalStateException { if (current == null) throw new IllegalStateException(); current.remove(); } }; } /** * Creates an Iterator view of a sequence of Iterators * * @param components Iterator<? extends T>[] source iterators * @return Iterator a compound iterator that scans the first iterator from * the sequence, then the second, etc. * * Can be used with varargs: cat(iterator1, iterator2, iterator3) and * with arrays: cat(iterators[]). * *

    Example: *

    
       * List list1 = Arrays.asList(new String[] {"One", "Two", "Three"});
       * List list2 = Arrays.asList(new String[] {"Four", "Five", "Six"});
       * List list3 = Arrays.asList(new String[] {"One", "Two", "Three", "Four", "Five", "Six"}
       * cat(list1.iterator(), list2.iterator())
    * returns the same as list3.iterator().

    */ public static Iterator cat(Iterator... components) { return cat(Arrays.asList(components)); } /** * Concatenates vararg Iterables into one List * @param elements Iterable<? extends T>... * @return an Iterable view that has elements of the component Iterables. * *

    Example: *
  • cat(Arrays.asList(new String[] {"a", "b", "c"}), Arrays.asList(new String[] {"b", "a", "d"})) * returns the same Iterable as Arrays.asList(new String[] {"a", "b", "c", "b", "a", "d"}).
  • */ public static Iterable cat(Iterable... elements) { return new CompoundIterable(elements); } /** * Concatenates vararg Collections into one Collection * @param elements Collection<T>... * @return an Collection view that has elements of the component Collections. * *

    Example: *
  • cat(Arrays.asList("a", "b", "c"), Arrays.asList("b", "a", "d")) * returns the same Collection as Arrays.asList("a", "b", "c", "b", "a", "d").
  • */ public static Collection cat(Collection... elements) { return new CompoundCollection(elements); } /** * Concatenates a collection of collections into one Collection * @param elements Collection<? extends Collection<? extends T>>... * @return an Collection view that has elements of the component Collections. * *

    Example: *
  • cat(Arrays.asList(Arrays.asList("a", "b", "c"), Arrays.asList("b", "a", "d")) * returns the same Collection as Arrays.asList(new String[] {"a", "b", "c", "b", "a", "d"}).
  • */ public static Collection cat(Collection> elements) { return new CompoundCollection(elements); } /** * returns an iterable good for using in a foreach loop * @param sequence CharSequence to scan * @return Iterable<Character> * *

    Example: *
  • for (char c : chars("this is an example"){ * System.out.println("Character " + c); * } *
  • * @deprecated This iterable has been moved to Strings */ public static Iterable chars(final CharSequence sequence) { return new Iterable() { public Iterator iterator() { return new Iterator() { int index = 0; public boolean hasNext() { return index < sequence.length(); } public void remove() { throw new UnsupportedOperationException(); } public Character next() { return sequence.charAt(index++); } }; } }; } /** * EmptyIterator is a helper class that does not contain * any elements and throws an exception when next() * is called. The exception message can be customized. */ public static class EmptyIterator implements Iterator { NoSuchElementException exception; public EmptyIterator(String message) { exception = new NoSuchElementException(message); } public EmptyIterator() { exception = new NoSuchElementException(); } public boolean hasNext() { return false; } public T next() { throw exception; } public void remove() { throw new UnsupportedOperationException(); } } } PK 34xq q 4com/myjavatools/lib/foundation/KeyValueArrayMap.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)KeyValueArrayMap.java 6.0 05/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * KeyValueArrayMap is a helper class that implements Map which is based on a key/value array * * Note that this class does not take any additional memory; lazy evaluation uses * only the array provided. It is very inefficient; to improve * performance, you will have to create a copy of the Map using * a concrete Map implementation from Collections framework. * * @version 6.0 05/04/06 * * @see Maps * @see java.util.Map * @since 5.0 */ public class KeyValueArrayMap extends AbstractMap { private final Object[] keyValueArray; /** * constructor * @param array Object... even elements contains keys, odd elements contain values */ public KeyValueArrayMap(Object... array) { this.keyValueArray = array; } private int indexOf(Object x) { for (int i = 0; i < keyValueArray.length; i+=2) { if (Objects.equal(keyValueArray[i], x)) { return i; } } return -1; } /** * Returns true if this map contains a mapping for the specified key. * * @param x key whose presence in this map is to be tested. * @return true if this map contains a mapping for the specified * key. */ public boolean containsKey(Object x) { return indexOf(x) >= 0; } /** * Returns a set view of the mappings contained in this map. * * @return a set view of the mappings contained in this map. * * Implementation note. Actually no large object is created; * the returned set is a lazy evaluation implementation of Set. */ public Set> entrySet() { return new AbstractSet>() { public boolean contains(Object o) { if (o == null) return false; if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; int index = indexOf(entry.getKey()); if (index < 0) { return false; } return Objects.equal(entry.getValue(), keyValueArray[index+1]); } public int size() { return keyValueArray.length / 2; } public Iterator> iterator() { return new Iterator>() { int index = 0; public Map.Entry next() { try { return new Pair ((X)keyValueArray[index], (Y)keyValueArray[index + 1]); } finally { index += 2; } } public boolean hasNext() { return index < keyValueArray.length - 1; } public void remove() { throw new UnsupportedOperationException(); } }; } }; } } PK 44ќDm m 4com/myjavatools/lib/foundation/KeyValuePairsMap.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)KeyValuePairsMap.java 6.0 05/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * KeyValuePairsMap is a helper class that implements Map which is based on a key/value array * * Note that this class does not take any additional memory; lazy evaluation uses * only the array provided. It is very inefficient; to improve * performance, you will have to create a copy of the Map using * a concrete Map implementation from Collections framework. * * Another important caveat. It takes a vararg array of Map.Entry instances. * It is up to the user to make sure that keys in the entries are all distinct - * consider this as a contract that must be stipulated, or else. What else? * First, it won't be a map in its regular sense. Second, size() will * return the number of entries, not the number of distinct entries. * But you can always addAll() this instance to a new Map, * and in that other Map all duplications will disappear. * * @version 6.0 05/04/06 * * @see Maps * @see java.util.Map * @since 5.0 */ public class KeyValuePairsMap extends AbstractMap { private final List> pairs; /** * constructor * @param pairs Map.Entry<X,Y>... even elements contains keys, odd elements contain values */ public KeyValuePairsMap(Map.Entry... pairs) { this.pairs = Arrays.asList(pairs); } /** * Returns true if this map contains a mapping for the specified key. * * @param x key whose presence in this map is to be tested. * @return true if this map contains a mapping for the specified * key. */ public boolean containsKey(Object x) { for (Map.Entry pair : pairs) { if (Objects.equal(pair.getKey(), x)) { return true; } } return false; } /** * Returns a set view of the mappings contained in this map. * * @return a set view of the mappings contained in this map. * * Implementation note. Actually no large object is created; * the returned set is a lazy evaluation implementation of Set. */ public Set> entrySet() { return new AbstractSet>() { public boolean contains(Object o) { return pairs.indexOf(o) >= 0; } public int size() { return pairs.size(); } public Iterator> iterator() { return new Iterator>() { Iterator> iterator = pairs.iterator(); public Map.Entry next() { return iterator.next(); } public boolean hasNext() { return iterator.hasNext(); } public void remove() { iterator.remove(); } }; } }; } } PK ڮ4;u,com/myjavatools/lib/foundation/LazyPair.java/** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ package com.myjavatools.lib.foundation; /** * LazyPair<Left, Right> is a pair consisting of key and value; its * value won't be calculated until requested. * LazyPair is immutable. * * @version 6.0 04/25/06 * * @see Map#Entry * @since 6.0 */ public class LazyPair extends Pair { boolean isCached = false; final Function function; /** * Constructor; saves argument and function * @param x X * @param f Function */ public LazyPair(X x, Function f) { super(x, null); function = f; } /** * right getter * @return the value of the function */ public Y right() { if (!isCached) { right = function.apply(left); isCached = true; } return right; } } PK 5p(com/myjavatools/lib/foundation/Map2.javapackage com.myjavatools.lib.foundation; import java.util.Collection; import java.util.Set; import java.util.Map; /** *

    Map2 is an interface that represents a two-parameter map.

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 12/10/2006 */ public interface Map2 { /** * @return the number of key-value mappings in this map. */ int size(); /** * @return true if this map contains no key-value mappings. */ boolean isEmpty(); /** * Returns true if this map contains a mapping for the * specified key pair. * * @param key1 first key. * @param key2 second key. * @return true if this map contains a mapping for this * key pair. */ boolean containsKeyPair(Object key1, Object key2); /** * Returns the value to which this map maps the specified key pair, and * null if the map contains no mapping for these keys. * * @param key1 first key. * @param key2 second key. * @return the value to which this map maps the specified keys, or * null if the map contains no mapping for these keys. * * @throws ClassCastException if the key is of an inappropriate type for * this map (optional). * @throws NullPointerException if the key is null and this map * does not permit null keys (optional). * * @see #containsKey(Object) */ V get(X key1, Y key2); /** * Associates the specified value with the specified key pair. * If the map previously contained a mapping for this key pair, * the old value is replaced by the specified value. * * @param key1 first key. * @param key2 second key. * @param value value to be associated with the specified key pair. * @return previous value associated with specified key, * or null if there was no mapping for key. */ V put(X key1, Y key2, V value); /** * Removes the mapping for this key pair from this map if it is present. * *

    Returns the value to which the map previously associated the keys, or * null if the map contained no mapping for this key pair. * * @param key1 first key. * @param key2 second key. * @return previous value, or null * if there was no mapping for key. */ V remove(X key1, Y key2); /** * Copies all of the mappings from the specified map to this map. * * @param source Mappings to be stored in this map. */ void putAll(Map2 t); /** * Removes all mappings from this map. */ void clear(); /** * A Map2 has two sets of keys, first component and second component. * This method returns an unmodifiable set view of the set of keys of the * first component. The set is backed by the map, so changes to the map * are reflected in the set. If the map is modified while an iteration over * the set is in progress, the results of the iteration are undefined. * * @return an unmodifiable set view of the keys contained in this map. */ Set keySet1(); /** * A Map2 has two sets of keys, first component and second component. * This method returns an unmodifiable set view of the set of keys of the * second component. The set is backed by the map, so changes to the map * are reflected in the set. If the map is modified while an iteration over * the set is in progress, the results of the iteration are undefined. * * @return an unmodifiable set view of the keys contained in this map. */ Set keySet2(); /** * Returns a collection view of the values contained in this map. The * collection is backed by the map, so changes to the map are reflected in * the collection. If the map is modified while an * iteration over the collection is in progress, the results of the * iteration are undefined. * * @return a collection view of the values contained in this map. */ Collection values(); /** * Currying by first argument. Produces a map that for each Y key2 returns * the same value as get(key1, key2) would return. If key1 is not present in * the set of keys, an empty map is returned. * @param key1 X * @return Map resulting map. */ Map curry1(X key1); /** * Currying by second argument. Produces a map that for each X key1 returns * the same value as get(key1, key2) would return. If key2 is not present in * the set of keys, an empty map is returned. * @param key2 X * @return Map resulting map. */ Map curry2(Y key2); /** * A map entry (key1-key2-value pair). The Map.entrySet method * returns a collection view of the map, whose elements are of this class. * You can use an iterator or a loop to scan through the entries. * * @see Map2#entrySet() */ interface Entry { /** * @return first key of the entry */ public X getKey1(); /** * @return second key of the entry */ public Y getKey2(); /** * @return entry value */ public V getValue(); /** * Replaces the value corresponding to this entry with the specified * value * * @param value new value to be stored in this entry. * @return old value corresponding to the entry. */ V setValue(V value); } /** * Returns a set view of the mappings contained in this map. Each element * in the returned set is a {@link Map2.Entry}. The set is backed by the * map, so changes to the map are reflected in the set, and vice-versa. * * @return a set view of the mappings contained in this map. */ Set> entrySet(); } PK e5K299(com/myjavatools/lib/foundation/Maps.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Maps.java 6.0 12/10/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; /** * Maps is a utility class that contains static methods for maps * * @version 5.0, 11/24/04 * @see java.util.Map * @see Function * @since 5.0 */ import java.util.*; import static com.myjavatools.lib.foundation.Function.*; public abstract class Maps { /** * composes two Maps (like functions, see Functions#compose) * * @param f Map<X,? extends Y> first Map * @param g Map<Y,Z> second Map * @return Map<X,Z> composition, x -> g(f(x)); * *

    Example: *

    Suppose we have the following:
    * Map<Integer,String> f = toMap(new Object[] {1, "one", 2, "two", 3, "three"});
    * Map<String,String> g = toMap(new String[] {"one", "uno", "two", "dos", "three", "tres"});
    *

    Then compose(f, g)
    * returns the same map as produced by
    * toMap(new Object[] {1, "uno", 2, "dos", 3, "tres"});
    */ public static Map compose(Map f, Map g) { return compose(f, forMap(g)); } /** * Composes a Map and a Function (see Functions#compose) by applying function * to all the values in the map. * * @param f Map<X,? extends Y> Map * @param g Function<Y,Z> Function * @return Map<X,Z> composition, x -> g(f(x)); * *

    Example: *

    Suppose we have the following:
    * Map<Integer,String> f = toMap(new Object[] {1, "one", 2, "two", 3, "three"});
    * Function<String,String> g ... { return toUppper(string); }...
    *

    Then compose(f, g)
    * returns the same map as produced by
    * toMap(new Object[] {1, "ONE", 2, "TWO", 3, "THREE"});
    */ public static Map compose(Map f, Function g) { return Function.compose(forMap(f), g).toMap(f.keySet()); } /** * finds all map keys that map to a specified value * @param map Map<X,Y> * @param y Y - the key * @return Iterable<X> - all X x such that y.equals(f(x)). * * If you want to obtain a Set instead of an Iterable, please use * resolveToSet(). */ public static Iterable resolve(final Map map, final Y y) { return new Filter() { public boolean accept(X x) { return y.equals(map.get(x)); } }.filter(map.keySet()); } /** * Returns a set of keys which are mapped to y by the specified map. * @param map Map * @param y Y * @return Set */ public static Set resolveToSet(Map map, Y y) { Set result = new LinkedHashSet(); Objects.addAll(result, resolve(map, y)); return result; } /** * reverts a Map f, producing a new one that maps values of f to sets of keys * of f * @param f Map<X,Y> original map * @return Map<Y,Set<X>> resulting map: for each y it returns {x | y.equals(f(x))} * * This method skips any null keys and values. * *

    Example: *

    Suppose we have the following:
    * Map<String,String> f = toMap(new String[] {"1", "odd", "2", "even", "3", "odd"});
    *

    Then revert(f)
    * returns the same map as produced by
    * Map<String,Collection<String>> g = new Map<String,Collection<String>>; * g.put("even", new HashSet(Arrays.asList("2"))); * g.put("odd", new HashSet(Arrays.asList("1", "3"))); *
    * */ public static Map> revert(Map f) { Map> result = new LinkedHashMap>(); for (Map.Entry entry : f.entrySet()) { X x = entry.getKey(); Y y = entry.getValue(); Set s = result.get(y); if (s == null) { result.put(y, s = new LinkedHashSet ()); } s.add(x); } return result; } /** * Inverses a Map * * @param f Map<X,Y> to inverse, must be monomorphic (one-to-one) * @throws InstantiationException in case f is not one-to-one * @return Map<Y,X> inverse to f * *

    Example: *

    Suppose we have the following:
    * Map f = toMap(new String[] {"1", "one", "2", "two", "3", "three"});
    *

    Then inverse(f)
    * returns the same map as produced by
    * toMap(new String[] {"one", "1", "two", "2", "three", "3"});
    */ public static Map inverse(Map f) throws InstantiationException { Map result = new LinkedHashMap(f.size()); for (Map.Entry entry : f.entrySet()) { if (result.containsKey(entry.getValue())) { throw new InstantiationException("non-invertible map"); } result.put(entry.getValue(), entry.getKey()); } return result; } /** * Maps a List using Map. * If Map m is considered as a map from its keys to its values, then * for each x in domain m(x) is calculated and stored into resulting List * * @param m Map<X,Y> the map * @param domain List<? extends X> the domain list * @return list List<Y> with the same number of elements as domain, and with elements * being values that correspond to the map's keys. * *

    Example: *

    Suppose we have the following: Map m = new HashMap();
    * m.put("a", "ValueOfA"); m.put("b", "ValueOfB"); m.put("c", "ValueOfC");
    *

    Then map(m, Arrays.asList(new String[] {"b", "x", "b"})) * returns a List that contains "ValueOfB", null, and "ValueOfB". */ public static List map(Map m, List domain) { return forMap(m).apply(domain); } /** * Restricts a Map to a Collection * * Resulting Map is a virtual map that has an intersection of * map's keyset and keys as a keyset, and maps them to the * same values as the original map does. * * @param map Map<X,Y> * @param keys Set<? extends X> of keys * @return Map<X,Y> */ public static Map restrict(final Map map, final Set keys) { return new AbstractMap() { public Set> entrySet() { return new RestrictedMapEntrySet(map, keys); } }; } /** * Restricts a Map to a Collection * * Resulting Map is a virtual map that has an intersection of * map's keyset and the set of keys from collection as a keyset, and maps them * to the same values as the original map does. * * @param map Map * @param keys Collection * @return Map */ public static Map restrict(final Map map, final Collection keys) { return new AbstractMap() { public Set> entrySet() { return new RestrictedMapEntrySet(map, keys); } }; } /** * Maps a Collection using Map. * If Map m is considered as a map from its keys to its values, then * for each x in domain m(x) is calculated and stored into resulting List * * @param m Map<X,Y> the map * @param domain Colection<? extends X> the domain list * @return Collection<Y> collection consisting of the values of the map corresponding to the keys * from domain. * *

    Example: *

    Suppose we have the following: Map<String,String> m = new HashMap<String,String>();
    * m.put("a", "ValueOfA"); m.put("b", "ValueOfB"); m.put("c", "ValueOfC");
    *

    Then map(m, Arrays.asList(new String[] {"b", "x", "b"})) * returns a Collection that contains {"ValueOfB", null, "ValueOfB"}. */ public static Collection map(final Map m, final Collection domain) { return new AbstractCollection() { public int size() { return domain.size(); } public Iterator iterator() { return Function.forMap(m).apply(domain.iterator()); } }; } /** * Maps an Iterator using Map. * If Map m is considered as a function from its keys to its values, then * the iterator that map returns is the one that, * for each x in iterator, returns m(x) is returned by next() call. * * @param m Map<X,Y> the map * @param iterator Iterator<? extends X> the domain iterator * @return Iterator<Y> iterator with the same number of elements as domain, and with elements * being values that correspond to the map's keys. * *

    Example: *

    Suppose we have the following: Map<String,String> m = new HashMap<String,String>();
    * m.put("a", "ValueOfA"); m.put("b", "ValueOfB"); m.put("c", "ValueOfC");
    *

    Then map(m, Arrays.asList(new String[] {"b", "x", "b"}).iterator()) * returns an Iterator that consequently returns "ValueOfB", null, and "ValueOfB". */ public static Iterator map(Map m, Iterator iterator) { return forMap(m).apply(iterator); } /** * Maps an Iterable using Map. * If Map m is considered as a map from its keys to its values, then * the iterable that map returns is the one with the iterator that * returns m.get(x) is returned by next() call for each x returned by * next() of the iterator of the original Iterable. * * @param m Map<X,Y> the map * @param iterable Iterable<? extends X> the domain iterator * @return Iterable<Y> iterable with the same number of elements as domain, and with elements * being values that correspond to the map's keys. * *

    Example: *

    Suppose we have the following: Map<String,String> m = new HashMap<String,String>();
    * m.put("a", "ValueOfA"); m.put("b", "ValueOfB"); m.put("c", "ValueOfC");
    *

    Then map(m, Arrays.asList(new String[] {"b", "x", "b"})) * returns an Iterable that contains "ValueOfB", null, and "ValueOfB". */ public static Iterable map(Map m, Iterable iterable) { return forMap(m).apply(iterable); } /** * makes a singleton Map<X,Y> from a key-value pair * * @param key X * @param value Y * @return Map<X,Y> that has just one key and its value * *

    Example: *

  • toMap("the key", "This is the value").get("the key"); * returns "This is the value";
  • * */ public static Map toMap(X key, Y value) { return new KeyValueArrayMap(key, value); } /** * makes a Map<X,Y> from two key-value pairs * * @param key1 X first key * @param value1 Y first value * @param key2 X second key * @param value2 Y second value * @return Map<X,Y> that has these two keys and values * *

    Example: *
  • toMap(2, "kaksi", 3, "kolmi").get(3); * returns "kolmi";
  • */ public static Map toMap(X key1, Y value1, X key2, Y value2) { return new KeyValueArrayMap(key1, value1, key2, value2); } /** * makes a Map<X,Y> from three key-value pairs * * @param key1 X first key * @param value1 Y first value * @param key2 X second key * @param value2 Y second value * @param key3 X third key * @param value3 Y third value * @return Map<X,Y> the map that contains these three keys and values * *

    Example: *
  • toMap("1", "un", "2", "deux", "3", "troix").get("2"); * returns "deux";
  • */ public static Map toMap(X key1, Y value1, X key2, Y value2, X key3, Y value3) { return new KeyValueArrayMap(key1, value1, key2, value2, key3, value3); } /** * makes a Map from key-value pairs * * @param pairs Pair<X,Y>[] the array of key-value pairs * @return Map the map that maps left pair elements from pairs array to right elements; * if pairs is null, returns null * *

    Example: *
  • toMap(new Pair<Integer, String>[] { * new Pair<Integer, String>(1, "un"), * new Pair<Integer, String>(2, "deux"), * new Pair<Integer, String>(3, "troix")}).get(2); * returns "deux";
  • */ public static Map toMap(Map.Entry... pairs) { return new KeyValuePairsMap(pairs); } /** * makes a Map from a vararg of key-value pairs * * @param keysAndValues Object... odd elements of the array are keys, and even elements are values * @return Map the map that maps odd elements from pairs array to even elements; * if pairs is null, returns null * *

    Example: *
  • toMap(new Integer(1), "un", new Integer(2), "deux", new Integer(3), "troix"}).get(2); * returns "deux";
  • * * not recommended (but not deprecated) since 5.0 - use map(Pair<S,T>[] pairs) instead */ public static Map toMap(Object... keysAndValues) { return new KeyValueArrayMap(keysAndValues); } /** * makes a Map from an array key-value pairs * * @param nameValuePairs Object[] odd elements of the array are keys, and even elements are values * @return Map<X,Y> the map that maps odd elements from pairs array to even elements; * if pairs is null, returns null * *

    Example: *
  • arrayToMap(new Object[] {1, "un", 2, "deux", 3, "troix"}).get(2); * returns "deux";
  • * * not recommended (but not deprecated) since 5.0 - use map(Pair<S,T>[] pairs) instead */ public static Map arrayToMap(Object[] nameValuePairs) { if (nameValuePairs == null) return null; return new KeyValueArrayMap(nameValuePairs); } } PK `4xթCC+com/myjavatools/lib/foundation/Objects.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Objects.java 6.0 05/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; import java.lang.reflect.Method; /** * Objects is a utility class that contains various unsorted static methods for foundation package * * @version 5.0, 6.0 05/04/06 * @see Maps * @see Function * @since 5.0 */ public abstract class Objects { /** * Gets the index of the first element of an array that equals to specified object * * @param what T the object to look for in array * @param array T[] array of objects to look for what * @return index of the object in array, or -1 if none found * *

    Examples: *
  • indexOf("abc", new String[] {"123", "abc", "xyz"}) * returns 1;
  • * *
  • indexOf(null, new String[] {"123", "abc", null}) * returns 2;
  • * */ public static int indexOf(T what, T[] array) { return Arrays.asList(array).indexOf(what); } /** * The method that everyone needs and nobody wants to make public. * @param x Object * @param y Object * @return boolean x == y || x != null && x.equals(y) */ public static boolean equal(Object x, Object y) { return x == y || x != null && x.equals(y); } /** * Gets the index of the next element of an array that equals to specified object * * @param what T the object to look for in array * @param array T[] array of objects to look for what * @param fromIndex int start search from this position * @return index of the object in array, or -1 if none found * *

    Examples: *
  • indexOf("abc", new String[] {"abc", "abc", "xyz", 1}) * returns 1;
  • * *
  • indexOf(null, new String[] {"123", "abc", null}}, 1) * returns 2;
  • * */ public static int indexOf(T what, T[] array, int fromIndex) { for (int i = fromIndex; i < array.length; i++) { if ((what == null && array[i] == null) || (what != null && what.equals(array[i]))) return i; } return -1; } /** * Gets the index of the next element of a list that equals to specified object * * @param what T the object to look for in list * @param list List<T> list of objects to look for what * @param fromIndex int start search from this position * @return index of the object in list, or -1 if none found * *

    Examples: *
  • List l = new ArrayList(); * l.add("abc"); l.add("abc"), l.add("xyz"); * indexOf("abc", list, 1} * returns 1;
  • * *
  • List l = new ArrayList(); * l.add("abc"); l.add("abc"), l.add(null); * indexOf(null, list, 1} * returns 2;
  • * */ public static int indexOf(T what, List list, int fromIndex) { for (int i = fromIndex; i < list.size(); i++) { Object current = list.get(i); if ((what == current) || (what != null && what.equals(current))) return i; } return -1; } /** * makes a Set from an array of elements * * @param elements T[] elements to fill the set * @return Set the set that contains all the elements from array * if the array is null, returns null * *

    Examples: *
  • toSet(new String[] {"1", "2", "3").size() return 3;
  • *
  • toSet(3, 1, 4, 1, 5, 9, 2, 6, 5).size() returns 7.
  • * @deprecated since 5.0; the usefulness of this method is doubtful */ public static Set toSet(T... elements) { return new LinkedHashSet(Arrays.asList(elements)); } /** * In a "creative", anti-scientific way checks whether a string or a container is empty. *
    Accepts a Collection, a Map, an array, a String. * * @param data a Collection or a Map or an array or a string to check * @return true if data is empty * *

    Examples: *
  • isEmpty(""), isEmpty(null), isEmpty(new HashMap()) all return true;
  • *
  • isEmpty(" "), isEmpty(new int[] {0}) returns false.
  • */ public static boolean isEmpty(T data) { if (data == null) return true; // attempt 1: array length if (data instanceof Object[]) return ((Object[]) data).length == 0; // attempt 2: isEmpty try { Method isEmpty = data.getClass().getMethod("isEmpty"); if (isEmpty != null) { return ((Boolean)isEmpty.invoke(data)).booleanValue(); } } catch (Exception e) {} // attempt 3: size try { Method size = data.getClass().getMethod("size"); if (size != null) { return ((Integer)size.invoke(data)).intValue() == 0; } } catch (Exception e) {} // attempt 4: check whether the string representation is empty or "null" return (data.toString().length() == 0) || "null".equals(data.toString()); } /** * Chooses the first non-empty object out of objects in parameter list. * * @param arglist the first candidate ... * @return the first one of the list of candidates that is not empty, converted to String * *

    Examples: *
  • oneOf(null, "xyz") returns "xyz";
  • *
  • oneOf("abc", "xyz") returns "abc";
  • *
  • oneOf(null, "", "xyz") returns "xyz";
  • *
  • oneOf("abc", null, "xyz") returns "abc";
  • *
  • oneOf("", "def", null) returns "def";
  • *
  • oneOf(null, null, 2) returns 2.
  • *
  • oneOf("abc", null, "pqr", "xyz") returns "abc";
  • *
  • oneOf("", "def", null, "xyz") returns "def";
  • */ public static T oneOf(T ... arglist) { T candidate = null; for (T o : arglist) { if (!isEmpty(o)) return o; if (o != null) candidate = o; } return candidate; } /** * Adds all elements of iterable to a collection. This method should be * in AbstractCollection, but... * @param collection Collection * @param toAdd Iterable */ public static void addAll(Collection collection, Iterable toAdd) { for (T o : toAdd) { collection.add(o); } } } PK 54w8 (com/myjavatools/lib/foundation/Pair.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Pair.java 6.0 04/25/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.Map; /** * Pair<Left, Right> is a class that represents pairs of objects. * It is similar to Map.Entry. Pair is immutable. * * @version 6.0 04/25/06 * * @see Map#Entry * @since 5.0 */ public class Pair implements Map.Entry { protected Left left; protected Right right; /** * Constructor, creates a new pair from two objects. * @param left Left * @param right Right */ public Pair(Left left, Right right) { this.left = left; this.right = right; } /** * value setter - unsupported (immutable class) * @param value Right ignored * @return Right none actually * @throws UnsupportedOperationException - always */ public Right setValue(Right value) { throw new UnsupportedOperationException(); } /** * value getter (to implement Map.Entry) * @return Right the map entry value */ public Right getValue() { return right(); } /** * key getter (to implement Map.Entry) * @return Left the map entry key */ public Left getKey() { return left(); } protected static boolean pairEqual(Map.Entry pair1, Map.Entry pair2) { return pair1 == null ? pair2 == null : Objects.equal(pair1.getKey(), pair2.getKey()) && Objects.equal(pair1.getValue(), pair2.getValue()); } /** * equals method * @param x Object to compare to * @return boolean true if x is not null and equals(this) * equals(Map.Entry) returns true if the two entries have equal key and * equal value are equal */ public boolean equals(Object x) { return x == this || x instanceof Map.Entry && pairEqual(this, (Map.Entry)x); } protected static int hashCode(Map.Entry pair) { return pair.getKey().hashCode() * 37 + pair.getValue().hashCode(); } /** * some hashcode for Pair made from left and right hash codes * @return int */ public int hashCode() { return hashCode(this); } /** * left getter * @return Left */ public Left left() { return left; } /** * right getter * @return Right */ public Right right() { return right; } /** * swaps left and right * @return new Pair<Right,Left> (right, left) */ public Pair swap() { return new Pair(right(), left()); } } PK j4 -com/myjavatools/lib/foundation/RangeList.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)RangeList.java 6.0 05/04/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * RangeList is a class that represents a list of values in a range. * It is immutable. * * @version 6.0 05/04/06 * * @see List * @since 5.0 */ public class RangeList { /** * Creates a list of integers * @param from int * @param to int * @param step int * @return List that "contains" integers from * from to to with a step step */ public static List rangeList(final int from, int to, final int step) { final int sign = step < 0 ? -1 : 1; final int size = step == 0 ? 0 : (to - from + step - sign) / step < 0 ? 0 : (to - from + step - sign) / step; return new AbstractList() { public Integer get(int index) { if (index < size) { return from + step * index; } else { throw new IndexOutOfBoundsException("" + index + "/" + size); } } public int size() { return size; } }; } /** * Creates a list of integers * @param from integer * @param to int * @return List that "contains" integers from from to to */ public static List rangeList(int from, int to) { return rangeList(from, to, 1); } /** * Creates a list of doubles * @param from double * @param to double * @param step double * @return List that "contains" doubles * from from to to with a step step */ public static List rangeList(final double from, final double to, final double step) { final int size = step == 0 ? 0 : (int) ( (to - from + step / 2) / step); return new AbstractList () { public Double get(int index) { if (index < size) { return from + step * index; } else { throw new IndexOutOfBoundsException("" + index + "/" + size); } } public int size() { return size; } }; } } PK ڮ45AA>com/myjavatools/lib/foundation/RestrictedFunctionEntrySet.javapackage com.myjavatools.lib.foundation; import java.util.*; /** *

    Title: My Java Tools Library, foundations, RestrictedFunctionEntrySet

    * *

    Description: This helper class represents an entry set for a map * restricted to a set of keys; it is used in Maps class.

    * * @(#)RestrictedFunctionEntrySet.java 6.0 04/25/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ class RestrictedFunctionEntrySet extends AbstractSet> { /** * the function */ private Function function; /** * the set of keys */ private Set keys; /** * Constructor, creates an instance of RestrictedFunctionEntrySet * @param function Function * @param keys Set key set */ public RestrictedFunctionEntrySet(Function function, Set keys) { super(); this.function = function; this.keys = Collections.unmodifiableSet(keys); } /** * Constructor, creates an instance of RestrictedFunctionEntrySet * @param function Function * @param keys Collection key collection * * Note. This constructor creates a new HashSet that contains the keys. */ public RestrictedFunctionEntrySet(Function function, Collection keys) { this(function, new HashSet(keys)); } /** * the size of the map is the size of the background keys collection * (I take the liberty to ignore the requirement that keys ought to be * non-repeating) */ public int size() { return keys.size(); } /** * iterator that scans through the entries of this map, * that is those that belong to the key collection and are valid * @return Iterator */ public Iterator> iterator() { return new Iterator>() { Iterator baseIterator = getKeys().iterator(); X currentKey; boolean haveKey = false; public void remove() { baseIterator.remove(); } public boolean hasNext() { while(!haveKey && baseIterator.hasNext()) { currentKey = baseIterator.next(); haveKey = isValidKey(currentKey); } return haveKey; } public Map.Entry next() { if (!hasNext()) throw new NoSuchElementException(); haveKey = false; return new LazyPair(currentKey, function); } }; } /** * operation not supported */ public void clear() { throw new UnsupportedOperationException(); } /** * operation not supported */ public boolean remove(Object toRemove) { throw new UnsupportedOperationException(); } /** * operation not supported */ public boolean removeAll(Collection toRemove) { throw new UnsupportedOperationException(); } /** * operation not supported */ public boolean retainAll(Collection toRemove) { throw new UnsupportedOperationException(); } /** * operation not supported */ public boolean add(Map.Entry toAdd) { throw new UnsupportedOperationException(); } /** * operation not supported */ public boolean addAll(Collection> toAdd) { throw new UnsupportedOperationException(); } /** * checks whether a collection is contained in this entryset. * @param toCheck Collection * @return boolean */ public boolean containsAll(Collection toCheck) { for (Object element : toCheck) { if (!(element instanceof Map.Entry)) { return false; } Map.Entry entry = (Map.Entry)element; if (!isValidKey(entry.getKey())) { return false; } if (!function.apply((X)entry.getKey()).equals(entry.getValue())) { return false; } } return true; } /** * creates an array of entries from this entry set * @return Map.Entry<X,Y>[] */ public Map.Entry[] toArray() { return toArray(null); } /** * produces an array of entries from this entry set * @param array Map.Entry[] suggested storage for results * @return Map.Entry[] resulting array */ public Map.Entry[] toArray(Map.Entry[] array) { if (array == null) { array = (Map.Entry[])(new Map.Entry[size()]); } else if (array.length < size()) { array = (Map.Entry[])java.lang.reflect.Array. newInstance(array.getClass().getComponentType(), size()); } int i = 0; for (Map.Entry entry : this) { array[i++] = entry; } return array; } protected Set getKeys() { return keys; } protected boolean isValidKey(Object key) { return keys.contains(key); } } PK ;49com/myjavatools/lib/foundation/RestrictedMapEntrySet.javapackage com.myjavatools.lib.foundation; import java.util.*; import static com.myjavatools.lib.foundation.Function.*; /** *

    Title: My Java Tools Library, foundations, RestrictedMapEntrySet

    * *

    Description: This helper class represents an entry set for a map restricted to a * collection of keys; it is used in Maps class.

    * * @(#)RestrictedMapEntrySet.java 6.0 04/25/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * * * */ class RestrictedMapEntrySet extends RestrictedFunctionEntrySet { /** * the original map */ private Map map; /** * Constructor, creates an instance of RestrictedMapEntrySet * @param map Map original map * @param keys Collection key collection */ public RestrictedMapEntrySet(Map map, Collection keys) { super(forMap(map), keys); this.map = map; } /** * calculates the size of restricted map; it takes time, because * the algorithm is to scan through all the keys and see if the map * is defined on the keys */ public int size() { int size = 0; for (X key : getKeys()) { if (isValidKey(key)) { size++; } } return size; } protected boolean isValidKey(Object key) { return super.isValidKey(key) && map.containsKey(key); } } PK Ǝ4[򅐱+com/myjavatools/lib/foundation/Sample1.javapackage com.myjavatools.lib.foundation; import java.io.*; import java.util.*; public class Sample1 { public static void main(String[] args) { String folderName = args.length < 1 ? "." : args[0]; Map fileToType = Maps.toMap("gif", "image", "jpg", "image", "jpeg", "image", "png", "image", "java", "source code", "cpp", "source code", "hpp", "source code", "class","binary", "obj", "binary", "exe", "binary", "dll", "library", "lib", "library", "so", "library", "sl", "library"); Function extension = new Function() { public String apply(File file) { String name = file.getName(); return name.substring(name.lastIndexOf('.') + 1); } }; // the function returns file type for a file Function fileType = Function.forMap(fileToType).compose(extension); // the list of files in the folder List contents = Arrays.asList(new File(folderName).listFiles()); // the same files grouped by their file types // only during this operation a new container is created. Map> filesGroupedByType = Maps.revert(fileType.toMap(contents)); for (String type : filesGroupedByType.keySet()) { System.out.println(type + ":"); for (File file : filesGroupedByType.get(type)) { System.out.println(" " + file); } } } } PK `4;;?com/myjavatools/lib/foundation/ShrinkingCompoundCollection.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)ImmutableCompoundCollection.java 6.0 04/27/06 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.foundation; import java.util.*; /** * ShrinkingCompoundCollection is a Collection that consists of other * Collections, viewed as one Collection; it can only shrink, but cannot * add elements. * * @version 6.0 04/28/06 * @see java.util.Collection * @see Iterators * @since 5.0 */ class ShrinkingCompoundCollection extends AbstractCollection { /** * the outer collection */ Collection> mainCollection; /** * Instantiates a compound collection from vararg list of components. * @param components Collection[] */ public ShrinkingCompoundCollection(Collection... components) { this(Arrays.asList(components)); } /** * Instantiates a compound collection from a collection of components. * @param components Collection */ public ShrinkingCompoundCollection( Collection> components) { this.mainCollection = components; } /** * Clears all the compound collections, */ public void clear() { for (Collection collection : mainCollection) { collection.clear(); } } /** * Removes a single instance of the specified element from this * compound collection, if it is present. More formally, * removes an element e such that (o==null ? e==null : * o.equals(e)), if such element is found. Returns true * if the collection contained the specified element.

    * * Note that this implementation can throw an * UnsupportedOperationException if the component that contains * the element throws it on element deletion. * * @param o element to be removed from this collection, if present. * @return true if the collection contained the specified * element. * @throws UnsupportedOperationException if the component containing the * element throws this exception. */ public boolean remove(Object o) { for (Collection component : mainCollection) { if (component.remove(o)) { return true; } } return false; } /** * Removes from this collection all of its elements that are contained in * the specified collection.

    * * This implementation iterates over the outer collection, removing the * specified elements from each inner collection. * * @param toRemove elements to be removed from this collection. * @return true if this collection changed as a result of the * call. * @throws UnsupportedOperationException if the removeAll method * is not supported by one of the collections, except one * specific case when a collection contains just one * element - in this case this collection is just removed from * the outer collection. * * @see #remove(Object) * @see #contains(Object) */ public boolean removeAll(Collection toRemove) { boolean wasChanged = false; for (Collection component : mainCollection) { wasChanged |= component.removeAll(toRemove); } return wasChanged; } /** * Adds the specified collection to the list, so that * its element can be listed as the elements of this view collection - * unsupported. * * @param toAdd collection to add to this collection. * @return nothing * @throws UnsupportedOperationException */ public boolean addAll(final Collection toAdd) { throw new UnsupportedOperationException("This class is immutable"); } /** * Adds an element to the collection - unsupported. * * @param element element being added to this collection. * @return nothing * @throws UnsupportedOperationException */ public boolean add(T element) { throw new UnsupportedOperationException("This class is immutable"); } /** * Returns the number of elements in this collection. If the collection * contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. The size is calculated as the sum of * the sizes of its collections. * * @return the number of elements in this collection. */ public int size() { int size = 0; for (Collection collection : mainCollection) { size += collection.size(); } return size; } /** * Returns an iterator over all the elements of component collections. * * @return an Iterator. */ public Iterator iterator() { Iterator> i = mainCollection.iterator(); return new CompoundIterator(i); } } PK !i5G$$4com/myjavatools/lib/foundation/TestAbstractMap2.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestAbstractMap2 extends TestCase { private AbstractMap2 testMap = null; private Set> entrySet = new HashSet>(); private class MockMap2 extends AbstractMap2 { Set> entrySet; MockMap2(Set> entrySet) { this.entrySet = entrySet; } public Set> entrySet() { return entrySet; } public Set keySet1() { Set result = new HashSet(); for (Map2.Entry e : entrySet) { result.add(e.getKey1()); } return result; } public Set keySet2() { Set result = new HashSet(); for (Map2.Entry e : entrySet) { result.add(e.getKey2()); } return result; } }; protected void setUp() throws Exception { super.setUp(); testMap = new MockMap2(entrySet); add("just a test", 17, "test number 17"); } private void add(String k1, int k2, String v) { entrySet.add(new AbstractMap2.Entry(k1, k2, v)); } protected void tearDown() throws Exception { testMap = null; super.tearDown(); } public void testClear() { assertFalse(entrySet.isEmpty()); testMap.clear(); assertTrue(testMap.isEmpty()); assertTrue(entrySet.isEmpty()); } public void testContainsKeyPair1() { Integer key1 = new Integer(17); String key2 = "just a test"; boolean expectedReturn = false; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsKeyPair2() { Integer key2 = new Integer(17); String key1 = "just a test"; boolean expectedReturn = true; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsKeyPair3() { Integer key2 = new Integer(18); String key1 = "just a test"; boolean expectedReturn = false; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsKeyPair4() { Integer key2 = new Integer(17); String key1 = "just a test?"; boolean expectedReturn = false; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsValue1() { Object value = null; boolean expectedReturn = false; boolean actualReturn = testMap.containsValue(value); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsValue2() { Object value = ":)"; boolean expectedReturn = false; boolean actualReturn = testMap.containsValue(value); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsValue3() { Object value = "test number 17"; boolean expectedReturn = true; boolean actualReturn = testMap.containsValue(value); assertEquals("return value", expectedReturn, actualReturn); } public void testEntrySet() { Set expectedReturn = Collections.singleton( new AbstractMap2.Entry ("just a test", 17, "test number 17")); Set actualReturn = testMap.entrySet(); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual1() { Object o1 = null; Object o2 = null; boolean expectedReturn = true; boolean actualReturn = testMap.equal(o1, o2); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual2() { Object o1 = null; Object o2 = ""; boolean expectedReturn = false; boolean actualReturn = testMap.equal(o1, o2); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual3() { Object o2 = null; Object o1 = ""; boolean expectedReturn = false; boolean actualReturn = testMap.equal(o1, o2); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual4() { Object o2 = "xx"; Object o1 = ""; boolean expectedReturn = false; boolean actualReturn = testMap.equal(o1, o2); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual5() { Object o2 = "xx"; Object o1 = "xx"; boolean expectedReturn = true; boolean actualReturn = testMap.equal(o1, o2); assertEquals("return value", expectedReturn, actualReturn); } public void testEquals() { Set> e1 = new HashSet>(); AbstractMap2 o = new MockMap2(e1); assertFalse(testMap.equals(e1)); e1.add( new AbstractMap2.Entry( "just a test", 17, "test number 17")); assertTrue(testMap.equals(o)); e1.add( new AbstractMap2.Entry( "just a test", 18, "test number 17")); assertFalse(testMap.equals(e1)); } public void testGet() { String actualReturn = testMap.get("just a test", 17); assertEquals("return value", "test number 17", actualReturn); } public void testHashCode() { int expectedReturn = -70426093; int actualReturn = testMap.hashCode(); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmpty() { boolean expectedReturn = false; boolean actualReturn = testMap.isEmpty(); assertEquals("return value", expectedReturn, actualReturn); } public void testKeySet1() { Set expectedReturn = new HashSet() {{ add("just a test"); }}; Set actualReturn = testMap.keySet1(); assertEquals("return value", expectedReturn, actualReturn); } public void testKeySet2() { Set expectedReturn = new HashSet() {{ add(17); }}; Set actualReturn = testMap.keySet2(); assertEquals("return value", expectedReturn, actualReturn); } public void testPut() { try { assertEquals("test number 17", testMap.put("just a test", 17, ":)")); fail("Must not be implemented"); } catch (UnsupportedOperationException uoe) { // good } } public void testPutAll() { Set> e1 = new HashSet>(); AbstractMap2 o = new MockMap2(e1); e1.add( new AbstractMap2.Entry( "just a test", 17, "test number 17")); e1.add( new AbstractMap2.Entry( "just a test", 18, "test number 17")); try { testMap.putAll(o); fail("This op should not be implemented here"); } catch (UnsupportedOperationException uoe) { // good, good } // assertEquals(2, abstractMap2.size()); } public void testRemove() { entrySet.add(new AbstractMap2.Entry("just a test!", 18, ":)")); assertEquals(2, testMap.size()); assertEquals("test number 17", testMap.remove("just a test", 17)); assertEquals(1, testMap.size()); } public void testSize() { int expectedReturn = 1; int actualReturn = testMap.size(); assertEquals("return value", expectedReturn, actualReturn); } public void testToString() { String expectedReturn = "{(just a test,17)->test number 17}"; String actualReturn = testMap.toString(); assertEquals("return value", expectedReturn, actualReturn); entrySet.add(new AbstractMap2.Entry("just a test!", 18, ":)")); expectedReturn = "{(just a test,17)->test number 17,(just a test!,18)->:)}"; actualReturn = testMap.toString(); } public void testValues() { Collection expectedReturn = Arrays.asList("test number 17"); Collection actualReturn = new ArrayList(testMap.values()); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry1() { assertEquals(0, testMap.curry1("not just a test").size()); assertEquals(new HashMap() {{ put(17, "test number 17");}}, testMap.curry1("just a test")); } public void testCurry2() { assertEquals(0, testMap.curry2(18).size()); assertEquals(new HashMap() {{ put("just a test", "test number 17");}}, testMap.curry2(17)); } } PK \4 ~~:com/myjavatools/lib/foundation/TestCompoundCollection.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestCompoundCollection extends TestCase { private CompoundCollection compoundCollection = null; protected void setUp() throws Exception { super.setUp(); List l1 = new ArrayList(); List l2 = new ArrayList(); l1.add("ab"); l1.add("cd"); l2.add("ef"); l2.add("gh"); compoundCollection = new CompoundCollection(l1, l2); } protected void tearDown() throws Exception { compoundCollection = null; super.tearDown(); } public void testAdd() { String element = "ij"; boolean expectedReturn = true; boolean actualReturn = compoundCollection.add(element); assertEquals("return value", expectedReturn, actualReturn); assertTrue(compoundCollection.contains(element)); } public void testAddAll() { Collection toAdd = Arrays.asList("ij", "kl"); boolean expectedReturn = true; boolean actualReturn = compoundCollection.addAll(toAdd); assertEquals("return value", expectedReturn, actualReturn); assertTrue(compoundCollection.contains("ij")); assertTrue(compoundCollection.contains("kl")); } public void testClear() { compoundCollection.clear(); assert(compoundCollection.isEmpty()); } public void testIterator() { Iterator actualReturn = compoundCollection.iterator(); for (String s : Arrays.asList("ab", "cd", "ef", "gh")) { assertEquals(s, actualReturn.next()); } assertFalse(actualReturn.hasNext()); } public void testRemoveAll1() { Collection toRemove = Arrays.asList("cd", "ef"); boolean expectedReturn = true; boolean actualReturn = compoundCollection.removeAll(toRemove); assertEquals("return value", expectedReturn, actualReturn); assertTrue(compoundCollection.contains("ab")); assertFalse(compoundCollection.contains("cd")); assertFalse(compoundCollection.contains("ef")); assertTrue(compoundCollection.contains("gh")); } public void testRemoveAll2() { Collection toRemove = Arrays.asList("gh", "ef", "ij"); boolean expectedReturn = true; boolean actualReturn = compoundCollection.removeAll(toRemove); assertEquals("return value", expectedReturn, actualReturn); assertTrue(compoundCollection.contains("ab")); assertTrue(compoundCollection.contains("cd")); assertFalse(compoundCollection.contains("ef")); assertFalse(compoundCollection.contains("gh")); } public void testRemoveAll3() { Collection toRemove = Arrays.asList("dc", "fe"); boolean expectedReturn = false; boolean actualReturn = compoundCollection.removeAll(toRemove); assertEquals("return value", expectedReturn, actualReturn); assertTrue(compoundCollection.contains("ab")); assertTrue(compoundCollection.contains("cd")); assertTrue(compoundCollection.contains("ef")); assertTrue(compoundCollection.contains("gh")); } public void testSize() { int expectedReturn = 4; int actualReturn = compoundCollection.size(); assertEquals("return value", expectedReturn, actualReturn); } public void testCompoundCollection() { Collection> components = Arrays.asList(Arrays.asList("ab", "cd"), Arrays.asList("ef", "gh")); Collection actual = new CompoundCollection(components); assertEquals(new ArrayList(actual), new ArrayList(compoundCollection)); assertEquals(Arrays.asList("ab", "cd", "ef", "gh"), new ArrayList(actual)); } public void testCompoundCollection1() { Collection components = Arrays.asList(Arrays.asList("ab"), Collections.EMPTY_LIST, Arrays.asList("ef")); Collection actual = new CompoundCollection(components); assertEquals(Arrays.asList("ab", "ef"), new ArrayList(actual)); } public void testCompoundCollection2() { Collection components = Arrays.asList(Arrays.asList("ab", "cd")); Collection actual = new CompoundCollection(components); assertEquals(Arrays.asList("ab", "cd"), new ArrayList(actual)); } public void testCompoundCollection3() { Collection components = Arrays.asList(Collections.EMPTY_LIST, Collections.EMPTY_LIST); Collection actual = new CompoundCollection(components); assertEquals(0, actual.size()); } public void testCompoundCollection4() { compoundCollection = new CompoundCollection(Collections.EMPTY_LIST); assertEquals(0, compoundCollection.size()); } } PK h5;.com/myjavatools/lib/foundation/TestFilter.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestFilter extends TestCase { private Filter filter = null; protected void setUp() throws Exception { super.setUp(); filter = new Filter() { public boolean accept(String s) { return s.startsWith("good"); } }; } protected void tearDown() throws Exception { filter = null; super.tearDown(); } public void testAccept1() { String x = "good string"; boolean expectedReturn = true; boolean actualReturn = filter.accept(x); assertEquals("return value", expectedReturn, actualReturn); } public void testAccept2() { String x = "bad string"; boolean expectedReturn = false; boolean actualReturn = filter.accept(x); assertEquals("return value", expectedReturn, actualReturn); } public void testAccept3() { String x = "notgood string"; boolean expectedReturn = false; boolean actualReturn = filter.accept(x); assertEquals("return value", expectedReturn, actualReturn); } public void testApply1() { String x = "good string"; Boolean expectedReturn = Boolean.TRUE; Boolean actualReturn = filter.apply(x); assertEquals("return value", expectedReturn, actualReturn); } public void testApply2() { String x = "bad string"; Boolean expectedReturn = Boolean.FALSE; Boolean actualReturn = filter.apply(x); assertEquals("return value", expectedReturn, actualReturn); } public void testFilter() { Iterable iterable = Arrays.asList("good string", "bad stuff", "good stuff"); Iterable actualReturn = filter.filter(iterable); Iterator i = actualReturn.iterator(); assertEquals("good string", i.next()); assertEquals("good stuff", i.next()); assertFalse(i.hasNext()); } public void testFilter1() { Iterator source = Arrays.asList("good string", "bad stuff", "good stuff").iterator(); Iterator i = filter.filter(source); assertEquals("good string", i.next()); assertEquals("good stuff", i.next()); assertFalse(i.hasNext()); } public void testFilter2() { Iterator source = Arrays.asList("x1", "goodx2", "goodx3", "x4").iterator(); Iterator i = filter.filter(source); for (int k = 0; k < 10; k++) { assertTrue(i.hasNext()); } assertEquals("goodx2", i.next()); for (int k = 0; k < 10; k++) { assertTrue(i.hasNext()); } assertEquals("goodx3", i.next()); assertFalse(i.hasNext()); } public void testFilter3() { List baseList = new ArrayList( Arrays.asList("x1", "goodx2", "goodx3", "goodx4", "x5")); Iterator source = baseList.iterator(); Iterator i = filter.filter(source); assertEquals("goodx2", i.next()); for (int k = 0; k < 10; k++) { assertTrue(i.hasNext()); } assertEquals("goodx3", i.next()); i.remove(); for (int k = 0; k < 10; k++) { assertTrue(i.hasNext()); } assertEquals("goodx4", i.next()); assertFalse(i.hasNext()); assertEquals(4, baseList.size()); } public void testNot() { Iterable iterable = Arrays.asList("good string", "bad stuff", "good stuff"); Iterable expectedReturn = Arrays.asList("bad stuff"); Iterable actualReturn = Filter.not(filter).filter(iterable); Iterator i = actualReturn.iterator(); assertEquals("bad stuff", i.next()); assertFalse(i.hasNext()); } public void testAnd() { Filter anotherFilter = new Filter() { public boolean accept(String s) { return s.contains("stuff"); } }; Iterable iterable = Arrays.asList("good string", "bad stuff", "good stuff", "bad string"); Iterable actualReturn = Filter.or(filter, anotherFilter).filter(iterable); Iterator i = actualReturn.iterator(); assertEquals("good string", i.next()); assertEquals("bad stuff", i.next()); assertEquals("good stuff", i.next()); assertFalse(i.hasNext()); } public void testOr() { Filter anotherFilter = new Filter() { public boolean accept(String s) { return s.contains("stuff"); } }; Iterable iterable = Arrays.asList("good string", "bad stuff", "good stuff", "bad string"); Iterable actualReturn = Filter.or(filter, anotherFilter).filter(iterable); Iterator i = actualReturn.iterator(); assertEquals("good string", i.next()); assertEquals("bad stuff", i.next()); assertEquals("good stuff", i.next()); assertFalse(i.hasNext()); } public void testToFilter() { Function f = new Function() { public Double apply(Double x) { return Math.sin(x); } }; Iterable iterable = Arrays.asList(3.2, 1.8, 3.2, 0.1); Iterable expectedReturn = Arrays.asList(1.8, 0.1); Iterable actualReturn = Filter.toFilter(f).filter(iterable); Iterator i = actualReturn.iterator(); // Note for programmers. Strictly speaking, you should not use equality // for doubles. assertEquals(1.8, i.next()); assertEquals(0.1, i.next()); assertFalse(i.hasNext()); } } PK g4#Eoo0com/myjavatools/lib/foundation/TestFunction.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestFunction extends TestCase { private Function f = null; protected void setUp() throws Exception { super.setUp(); f = new Function() { public String apply(Number n) { return Integer.toHexString(n.intValue()); } }; } protected void tearDown() throws Exception { f = null; super.tearDown(); } public void testApply() { Iterable iterable = Arrays.asList(1, 16, 256); Iterable actualReturn = f.apply(iterable); Iterator i = actualReturn.iterator(); assertEquals("1", i.next()); assertEquals("10", i.next()); assertEquals("100", i.next()); assertFalse(i.hasNext()); i = actualReturn.iterator(); assertEquals("1", i.next()); assertEquals("10", i.next()); assertEquals("100", i.next()); assertFalse(i.hasNext()); } public void testApply1() { Iterator iterator = Arrays.asList(1, 16, 256).iterator(); Iterator i = f.apply(iterator); assertEquals("1", i.next()); assertEquals("10", i.next()); assertEquals("100", i.next()); assertFalse(i.hasNext()); } public void testApply2() { List domain = Arrays.asList(1, 16, 256); List expectedReturn = Arrays.asList("1", "10", "100"); List actualReturn = f.apply(domain); assertEquals("return value", expectedReturn, actualReturn); } public void testApply3() { String expectedReturn = "ff"; String actualReturn = f.apply(255); assertEquals("return value", expectedReturn, actualReturn); } public void testCompose() { Function g = new Function() { public Integer apply(Integer n) { return n * n; } }; Function h = Function.compose(g, f); assertEquals("19", h.apply(5)); } public void testCompose1() { Function g = new Function() { public Integer apply(Integer n) { return n * n; } }; Function h = f.compose(g); assertEquals("19", h.apply(5)); } public void testForMap() { Map map = new HashMap(); map.put(1, 1); map.put(2, 4); map.put(3, 9); Function actualReturn = Function.forMap(map); assertEquals("return value", 9, actualReturn.apply(3)); assertEquals("return value", null, actualReturn.apply(4)); } public void testForMap1() { Map map = new HashMap(); map.put(1, 1); map.put(2, 4); map.put(3, 9); Function actualReturn = Function.forMap(map, 77); assertEquals("return value", 9, actualReturn.apply(3)); assertEquals("return value", 77, actualReturn.apply(4)); } public void testToMap() { Collection keys = Arrays.asList(3,4,5,4,3); Map expectedReturn = new HashMap(); expectedReturn.put(3, "3"); expectedReturn.put(4, "4"); expectedReturn.put(5, "5"); Map actualReturn = f.toMap(keys); assertEquals("return value", expectedReturn, actualReturn); } public void testToMap1() { Set keys = new HashSet(Arrays.asList(3,4,5)); Map expectedReturn = new HashMap(); expectedReturn.put(3, "3"); expectedReturn.put(4, "4"); expectedReturn.put(5, "5"); Map actualReturn = f.toMap(keys); assertEquals("return value", expectedReturn, actualReturn); } public void testId() { Function idString = Function.id(); Function idInteger = Function.id(); Function actual = idString.compose(f.compose(idInteger)); for (int i = -2; i < 4; i++) { assertEquals(f.apply(i), actual.apply(i)); } } } PK 4s/ά""1com/myjavatools/lib/foundation/TestFunction2.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestFunction2 extends TestCase { private Function2 function2 = null; protected void setUp() throws Exception { super.setUp(); function2 = new Function2() { public String apply(Number n, String unit) { return unit + "s: " + n; } }; } protected void tearDown() throws Exception { function2 = null; super.tearDown(); } public void testApply() { Integer x = 5; String y = "Jackson"; String expectedReturn = "Jacksons: 5"; String actualReturn = function2.apply(x, y); assertEquals("return value", expectedReturn, actualReturn); } public void testCompose() { Function f = new Function() { public Double apply(Float x) { return (double)x * x; } }; Function g = new Function() { public String apply(String s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }; Function2 h = function2; String expectedReturn = "Jacksons: 25.0"; Function2 composition = Function2.compose(f, g, h); String actualReturn = composition.apply(5.f, "jackson"); assertEquals("return value", expectedReturn, actualReturn); } public void testCompose1() { Function2 f = function2; Function g = new Function() { public String apply(String s) { return s + ", I think."; } }; String expectedReturn = "Stars: 1.0E15, I think."; Function2 composition = function2.compose(f, g); String actualReturn = composition.apply(1e15, "Star"); assertEquals("return value \"" + actualReturn + "\"", expectedReturn, actualReturn); } public void testCurry1() { Integer n = 42; Function expected = new Function() { public String apply(String s) { return s + "s: 42"; } }; Function actual = function2.curry1(n); String test = ""; for (int i = 0; i < 10; i++) { assertEquals(expected.apply(test), actual.apply(test)); test += ('A' + i); } } public void testCurry2() { String s = "pig"; Function expected = new Function() { public String apply(Number n) { return "pigs: " + n; } }; Function actual = function2.curry2(s); for (int i = 0; i < 10; i++) { assertEquals(expected.apply(i), actual.apply(i)); } } public void testForFunction() { Function,Integer> f = new Function,Integer>() { public Integer apply(Map.Entry pair) { return pair.getKey() * pair.getValue(); } }; Function2 expectedReturn = new Function2() { public Integer apply(Integer n, Integer m) { return n * m; } }; Function2 actualReturn = function2.forFunction(f); for (int i = -10; i < 10; i++) { for (int j = -10; j < 10; j++) { assertEquals(expectedReturn.apply(i, j), actualReturn.apply(i, j)); } } } public void testForMap() { Map> map = new HashMap> (); // Using Crazy Bob's contraption to avoid entia multiplicanda map.put("a", new HashMap() {{ put("b", "a and b"); put("c", "a and c"); }}); map.put("b", new HashMap() {{ put("c", "b and c"); put("d", "b and d"); }}); map.put("c", new HashMap() {{ put("d", "c and d"); put("e", "c and e"); }}); final List entries = Arrays.asList("a", "b", "c", "d", "e", "none of the above", ""); Function2 expectedReturn = new Function2() { public String apply(String s, String t) { int is = entries.indexOf(s); int it = entries.indexOf(t); return is < 3 && is >= 0 && it > is && it < is + 3 ? (s + " and " + t) : null; } }; Function2 actualReturn = Function2.forMap(map); for (String s : entries) { for (String t : entries) { assertEquals("return value for " + s + " and " + t, expectedReturn.apply(s, t), actualReturn.apply(s, t)); } } } public void testForMap1() { Map> map = new HashMap> (); // Using Crazy Bob's contraption to avoid entia multiplicanda map.put("a", new HashMap() {{ put("b", "a and b"); put("c", "a and c"); }}); map.put("b", new HashMap() {{ put("c", "b and c"); put("d", "b and d"); }}); map.put("c", new HashMap() {{ put("d", "c and d"); put("e", "c and e"); }}); final List entries = Arrays.asList("a", "b", "c", "d", "e", "none of the above", ""); Function2 expectedReturn = new Function2() { public String apply(String s, String t) { int is = entries.indexOf(s); int it = entries.indexOf(t); return is < 3 && is >= 0 && it > is && it < is + 3 ? (s + " and " + t) : "wrong answer"; } }; Function2 actualReturn = function2.forMap(map, "wrong answer"); for (String s : entries) { for (String t : entries) { assertEquals("return value for " + s + " and " + t, expectedReturn.apply(s, t), actualReturn.apply(s, t)); } } } public void testP1() { Function2 actualReturn = Function2.p1(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { assertEquals(new Integer(i), actualReturn.apply(i, j)); } } } public void testP2() { Function2 actualReturn = Function2.p2(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { assertEquals(new Integer(j), actualReturn.apply(i, j)); } } } public void testSwap() { Function2 expectedReturn = new Function2() { public String apply(String unit, Number n) { return unit + "s: " + n; } }; Function2 actualReturn = function2.swap(); List units = Arrays.asList("pound", "mile", "gallon"); for (String unit : units) { for (int i = 1; i < 10; i += 2) { assertEquals(expectedReturn.apply(unit, i), actualReturn.apply(unit, i)); } } } public void testToFunction() { Function,String> expectedReturn = new Function,String>() { public String apply(Map.Entry pair) { return pair.getValue() + "s: " + pair.getKey(); } }; Function,String> actualReturn = function2.toFunction(); List units = Arrays.asList("pound", "mile", "gallon"); for (String unit : units) { for (int i = 1; i < 10; i += 2) { Map.Entry pair = new Pair(i, unit); assertEquals(expectedReturn.apply(pair), actualReturn.apply(pair)); } } } public void testToMap() { Map> expected = new HashMap>() {{ put(1, new HashMap() {{ put("horse", "horses: 1"); put("pig", "pigs: 1"); }}); put(2, new HashMap() {{ put("horse", "horses: 2"); put("pig", "pigs: 2"); }}); }}; Map> actual = function2.toMap(new HashSet(java.util.Arrays.asList(2, 1)), new HashSet(java.util.Arrays.asList("pig", "horse"))); assertEquals(expected, actual); } } PK Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestIndexedMap2 extends TestCase { private IndexedMap2 testMap = null; Set> entrySet = null; protected void setUp() throws Exception { super.setUp(); entrySet = new HashSet>(); testMap = new IndexedMap2() { public Set> entrySet() { return entrySet; } }; testMap.put("just a test", 17, "test number 17"); } protected void tearDown() throws Exception { testMap = null; super.tearDown(); } public void testContainsKeyPair1() { Integer key1 = new Integer(17); String key2 = "just a test"; boolean expectedReturn = false; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsKeyPair2() { Integer key2 = new Integer(17); String key1 = "just a test"; boolean expectedReturn = true; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsKeyPair3() { Integer key2 = new Integer(18); String key1 = "just a test"; boolean expectedReturn = false; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsKeyPair4() { Integer key2 = new Integer(17); String key1 = "just a test?"; boolean expectedReturn = false; boolean actualReturn = testMap.containsKeyPair(key1, key2); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsValue1() { Object value = null; boolean expectedReturn = false; boolean actualReturn = testMap.containsValue(value); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsValue2() { Object value = ":)"; boolean expectedReturn = false; boolean actualReturn = testMap.containsValue(value); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsValue3() { Object value = "test number 17"; boolean expectedReturn = true; boolean actualReturn = testMap.containsValue(value); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry11() { String key1 = null; Map expectedReturn = new HashMap(); Map actualReturn = testMap.curry1(key1); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry12() { String key1 = "bad key"; Map expectedReturn = new HashMap(); Map actualReturn = testMap.curry1(key1); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry13() { String key1 = "just a test"; Map expectedReturn = new HashMap(); expectedReturn.put(17, "test number 17"); Map actualReturn = testMap.curry1(key1); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry21() { Integer key2 = null; Map expectedReturn = new HashMap(); Map actualReturn = testMap.curry2(key2); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry22() { Map expectedReturn = new HashMap(); Map actualReturn = testMap.curry2(18); assertEquals("return value", expectedReturn, actualReturn); } public void testCurry23() { Map expectedReturn = new HashMap(); expectedReturn.put("just a test", "test number 17"); Map actualReturn = testMap.curry2(17); assertEquals("return value", expectedReturn, actualReturn); } public void testGet() { String actualReturn = testMap.get("just a test", 17); assertEquals("return value", "test number 17", actualReturn); } public void testKeySet1() { Set expectedReturn = new HashSet(); expectedReturn.add("just a test"); Set actualReturn = testMap.keySet1(); assertEquals(expectedReturn, actualReturn); } public void testKeySet2() { Set expectedReturn = new HashSet(); expectedReturn.add(17); Set actualReturn = testMap.keySet2(); assertEquals("return value", expectedReturn, actualReturn); } public void testPut1() { String actualReturn = testMap.put("just a test", 17, "new test number 17"); assertEquals("return value", "test number 17", actualReturn); assertEquals(1, testMap.size()); } public void testPut2() { String actualReturn = testMap.put("just a test.", 18, "new test number 18"); assertEquals("return value", null, actualReturn); assertEquals(2, testMap.size()); } public void testGetEntry() { Map2.Entry entry = testMap.getEntry("just a test", 17); Map2.Entry contained = entrySet.iterator().next(); assertEquals(entry, contained); assertEquals(entry.hashCode(), contained.hashCode()); HashSet> s = new HashSet>(); s.add(contained); assertTrue(s.contains(entry)); assertTrue(s.contains(contained)); assertTrue(testMap.entrySet() == entrySet); assertTrue(entrySet.contains(contained)); assertTrue(entrySet.contains(entry)); assertTrue(testMap.entrySet().contains(contained)); assertTrue(testMap.entrySet().contains(entry)); } public void testRemove() { testMap.put("just a test.", 18, "new test number 18"); assertEquals(2, testMap.size()); String actualReturn = testMap.remove("just a test", 17); assertEquals(1, testMap.size()); assertEquals("test number 17", actualReturn); assertEquals("new test number 18", testMap.remove("just a test.", 18)); assertEquals(0, testMap.size()); } } PK Z4ɦ1com/myjavatools/lib/foundation/TestIterators.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; import static com.myjavatools.lib.foundation.Iterators.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 5.0 */ public class TestIterators extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } private Integer[] getIntegers(int from, int to) { Integer[] result = new Integer[to - from + 1]; for (int i = 0; i < result.length; i++) { result[i] = i + from; } return result; } private Collection getIntC(int from, int to) { return Arrays.asList(getIntegers(from, to)); } private void checkIntIterator(Iteratoriterator, int from, int to) { int i; for (i = from; i < to; i++) { assertTrue("must have", iterator.hasNext()); assertEquals(new Integer(i), iterator.next()); } assertFalse("must be enough", iterator.hasNext()); try{ iterator.next(); fail("should have thrown an exception"); } catch (NoSuchElementException e) { } } private void checkIntIterator(Iteratoriterator, int from, int to, int step) { int i; System.out.println("" + from + ".." + to + " (" + step + ")"); for (i = from; (to - i) * step > 0; i+= step) { System.out.print(i + ".. "); assertTrue("must have " + i, iterator.hasNext()); assertEquals(new Integer(i), iterator.next()); } System.out.println(); assertFalse("must be enough", iterator.hasNext()); try{ iterator.next(); fail("should have thrown an exception"); } catch (NoSuchElementException e) { } } private void checkDoubleIterator(Iteratoriterator, double from, double to, double step) { for (int i = 0; step * (to - from - i * step) > 0; i++) { assertTrue("must have", iterator.hasNext()); assertTrue(Math.abs(from + i * step - iterator.next()) < 0.000001); } assertFalse("must be enough", iterator.hasNext()); try{ iterator.next(); fail("should have thrown an exception"); } catch (NoSuchElementException e) { } } public void testCat() { Iterable actualReturn = Iterators.cat((Collection)getIntC(0, 9), (Collection)getIntC(10, 19), (Collection)getIntC(20,30)); checkIntIterator(actualReturn.iterator(), 0, 31); } public void testCat1() { Iterator i1 = RangeList.rangeList(2, 6).iterator(); Iterator i2 = RangeList.rangeList(6, 20).iterator(); Iterator i3 = RangeList.rangeList(20,31).iterator(); List> l = Arrays.asList(i1, i2, i3); // Iterator> outerIterator = iterators.asList(i1, i2, i3).iterator(); // checkIntIterator(iterators.cat(outerIterator), 2, 31); checkIntIterator(Iterators.cat(i1,i2,i3), 2, 31); } public , Y extends CharSequence> void t() { Collection c = null; Collection s = null; Collection c1 = null; Collection cy = null; X cx = null; c1 = c; c1 = s; c1 = cy; c1 = cx; } public void testCatIterables() { Collection i1 = getIntC(1, 7); Collection i2 = getIntC(8, 19); Collection i3 = getIntC(20,31); List> l = Arrays.asList(i1, i2, i3); Iterable> i = l; Iterableit = new CompoundIterable(i); Iterableit1 = Iterators.cat(i1, i2, i3); checkIntIterator(Iterators.cat(i1, i2, i3).iterator(), 1, 32); List> ll = t(i1, i2, i3); String s = "ijk"; List l2 = t("ab", "cde", "fg", s); List l3 = t("dx", "asweiuy", "asd"); List> lll = t(l2, l3); } private List t(X... e) { return Arrays.asList(e); } public void testGrep() { Filter filter = new Filter() { public boolean accept(Integer i) { return i % 3 == 0; } }; Iterator source = RangeList.rangeList(5, 15).iterator(); Iterator actualReturn = filter.filter(source); checkIntIterator(actualReturn, 6, 15, 3); } public void testList() { Iterable actualReturn = RangeList.rangeList(7, 17); this.checkIntIterator(actualReturn.iterator(), 7, 17); } public void testMap() { Function function = new Function() { public Double apply(Integer i) { return 2.718 * i + 0.01; } }; Iterator iterator = RangeList.rangeList(1, 5).iterator(); Iterator actualReturn = function.apply(iterator); checkDoubleIterator(actualReturn, 2.728, 2.718 * 5 + .01, 2.718); } public void testRangeList() { List actualReturn = RangeList.rangeList(314, 3.14, -17.3); assertTrue(actualReturn.size() > 17); checkDoubleIterator(actualReturn.iterator(), 314, 3.14, -17.3); } public void testRangeIterator1() { int from = 0; int step = -3; for (int to = 10; to > -110; to--) { Iterator actualReturn = RangeList.rangeList(from, to, step).iterator(); assertTrue("to " + to, (to >= from) != actualReturn.hasNext()); checkIntIterator(actualReturn, from, to, step); } } public void testRangeIterator2() { int from = 0; int step = 7; for (int to = -4; to < 110; to++) { Iterator actualReturn = RangeList.rangeList(from, to, step).iterator(); assertTrue("to " + to, (to <= from) != actualReturn.hasNext()); checkIntIterator(actualReturn, from, to, step); } } } PK d4P 0com/myjavatools/lib/foundation/TestLazyPair.javapackage com.myjavatools.lib.foundation; import junit.framework.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestLazyPair extends TestCase { private LazyPair lazyPair = null; protected void setUp() throws Exception { super.setUp(); lazyPair = new LazyPair(420, new Function() { public String apply(Integer n) { return "" + n; }}); } protected void tearDown() throws Exception { lazyPair = null; super.tearDown(); } public void testRight() { String expectedReturn = "420"; String actualReturn = lazyPair.right(); assertEquals("return value", expectedReturn, actualReturn); } public void testEqualsNegative1() { Object x = new Pair(420, "421"); boolean expectedReturn = false; boolean actualReturn = lazyPair.equals(x); assertEquals("return value", expectedReturn, actualReturn); } public void testEqualsNegative2() { Object x = new Pair(421, "420"); boolean expectedReturn = false; boolean actualReturn = lazyPair.equals(x); assertEquals("return value", expectedReturn, actualReturn); } public void testEqualsPositive() { Object x = new Pair(420, "420"); boolean expectedReturn = true; boolean actualReturn = lazyPair.equals(x); assertEquals("return value", expectedReturn, actualReturn); } public void testGetKey() { Integer expectedReturn = 420; Integer actualReturn = lazyPair.getKey(); assertEquals("return value", expectedReturn, actualReturn); } public void testGetValue() { String expectedReturn = "420"; String actualReturn = lazyPair.getValue(); assertEquals("return value", expectedReturn, actualReturn); } public void testHashCode() { int expectedReturn = 67110; int actualReturn = lazyPair.hashCode(); assertEquals("return value", expectedReturn, actualReturn); } public void testLeft() { Integer expectedReturn = 420; Integer actualReturn = lazyPair.left(); assertEquals("return value", expectedReturn, actualReturn); } public void testRight1() { String expectedReturn = "420"; String actualReturn = lazyPair.right(); assertEquals("return value", expectedReturn, actualReturn); } public void testSetValue() { String value = "42"; try { lazyPair.setValue(value); } catch (Exception e) { assertEquals("Something wrong thrown", "java.lang.UnsupportedOperationException", e.toString()); return; } fail("Oops... had to throw an exception"); } public void testSwap() { Pair expectedReturn = new Pair("420", 420); Pair actualReturn = lazyPair.swap(); assertEquals("return value", expectedReturn, actualReturn); } } PK ga4 80#0#,com/myjavatools/lib/foundation/TestMaps.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; import java.util.Map.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestMaps extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testArrayToMap1() { Object[] nameValuePairs = {}; Map expectedReturn = new HashMap(); Map actualReturn = Maps.arrayToMap(nameValuePairs); assertEquals("return value", expectedReturn, actualReturn); } public void testArrayToMap2() { Object[] nameValuePairs = {"one", new Integer(1), "two", new Integer(2)}; Map expectedReturn = new HashMap(); expectedReturn.put("one", 1); expectedReturn.put("two", 2); Map actualReturn = Maps.arrayToMap(nameValuePairs); assertEquals("return value", expectedReturn, actualReturn); } public void testCompose() { Map f = Maps.arrayToMap(new Object[]{"one", new Integer(1), "two", new Integer(2), "three", new Integer(3)}); Map g = Maps.arrayToMap(new Object[]{new Integer(2), "II", new Integer(3), "III", new Integer(4), "IV"}); Map expectedReturn = Maps.arrayToMap(new Object[]{"two", "II", "three", "III", "one", null}); Map actualReturn = Maps.compose(f, g); assertEquals("return value", expectedReturn, actualReturn); } public void testInverse() throws InstantiationException { Map f = Maps.arrayToMap(new Object[]{"one", new Integer(1), "two", new Integer(2), "three", new Integer(3)}); Map expectedReturn = Maps.arrayToMap(new Object[]{new Integer(1), "one", new Integer(2), "two", new Integer(3), "three"}); Map actualReturn = Maps.inverse(f); assertEquals("return value", expectedReturn, actualReturn); } public void testInverseNegative() throws InstantiationException { Map f = Maps.arrayToMap(new Object[]{"one", new Integer(1), "two", new Integer(2), "three", new Integer(3), "four", new Integer(2)}); try { Map actualReturn = Maps.inverse(f); fail("Should have thrown an exception"); } catch (InstantiationException e) { assertEquals("non-invertible map", e.getMessage()); } } public void testMap() { Map m = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(2), "II", new Integer(3), "III"}); Collection domain = new HashSet(Arrays.asList(1, 3)); Set expectedReturn = new HashSet(Arrays.asList("I", "III")); Set actualReturn = new HashSet(Maps.map(m, domain)); assertEquals("return value", expectedReturn, actualReturn); } public void testMap1() { Map m = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(2), "II", new Integer(3), "III"}); Iterable domain = new HashSet(Arrays.asList(1, 3)); Set expectedReturn = new HashSet(Arrays.asList("I", "III")); Iterable actualReturn = Maps.map(m, domain); Iterator i = actualReturn.iterator(); assertTrue(expectedReturn.contains(i.next())); assertTrue(expectedReturn.contains(i.next())); assertFalse(i.hasNext()); } public void testMap2() { Map m = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(2), "II", new Integer(3), "III"}); Iterator domain = Arrays.asList(1, 3).iterator(); List expectedReturn = Arrays.asList("I", "III"); Iterator actualReturn = Maps.map(m, domain); assertEquals("I", actualReturn.next()); assertEquals("III", actualReturn.next()); assertFalse(actualReturn.hasNext()); } public void testMap3() { Map m = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(2), "II", new Integer(3), "III"}); List domain = Arrays.asList(1, 3); List expectedReturn = Arrays.asList("I", "III"); List actualReturn = Maps.map(m, domain); assertEquals("return value", expectedReturn, new ArrayList(actualReturn)); } public void testResolve1() { Map m = Maps.toMap(new Object[] {new Integer(1), "odd", new Integer(2), "even", new Integer(3), "odd", new Integer(-3), "odd"}); Set expectedReturn = new HashSet(Arrays.asList(1, 3, -3)); Set actualReturn = Maps.resolveToSet(m, "odd"); assertEquals("return value", expectedReturn, actualReturn); } public void testResolve2() { Map m = Maps.toMap(new Object[] {new Integer(1), "odd", new Integer(2), "even", new Integer(3), "odd", new Integer(-3), "odd"}); Set expectedReturn = new HashSet(); Set actualReturn = Maps.resolveToSet(m, "queer"); assertEquals("return value", expectedReturn, actualReturn); } public void testRestrict() { Map m = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(2), "II", new Integer(3), "III"}); Collection keys = Arrays.asList(1, 3); Map expectedReturn = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(3), "III"}); Map actualReturn = Maps.restrict(m, keys); assertEquals("return value", expectedReturn, actualReturn); } public void testRestrict1() { Map m = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(2), "II", new Integer(3), "III"}); Set keys = new HashSet(Arrays.asList(1, 3)); Map expectedReturn = Maps.toMap(new Object[] {new Integer(1), "I", new Integer(3), "III"}); Map actualReturn = Maps.restrict(m, keys); assertEquals("return value", expectedReturn, actualReturn); } public void testRevert() { Map m = Maps.toMap(new Object[] {new Integer(1), "odd", new Integer(2), "even", new Integer(3), "odd", new Integer(-3), "odd"}); Map> expectedReturn = new HashMap>(); expectedReturn.put("odd", new HashSet(Arrays.asList(1,3,-3))); expectedReturn.put("even", new HashSet(Arrays.asList(2))); Map actualReturn = Maps.revert(m); assertEquals("return value", expectedReturn, actualReturn); } public void testToMap() { Entry[] pairs = (Entry[]) new Entry[] {new Pair("tizenegy", 11), new Pair("nihyaku", 200)}; Map expectedReturn = new HashMap(); expectedReturn.put("tizenegy", 11); expectedReturn.put("nihyaku", 200); Map actualReturn = Maps.toMap(pairs); assertEquals("return value", expectedReturn, actualReturn); } public void testToMap1() { Object[] pairs = {"trois", new Integer(3), "vier", new Integer(4)}; Map expectedReturn = new HashMap(); expectedReturn.put("vier", 4); expectedReturn.put("trois", 3); Map actualReturn = Maps.toMap(pairs); assertEquals("return value", expectedReturn, actualReturn); /**@todo fill in the test code*/ } public void testToMap2() { Integer key = 7; String value = "sizim"; Map expectedReturn = new HashMap(); expectedReturn.put(7, "sizim"); Map actualReturn = Maps.toMap(key, value); assertEquals("return value", expectedReturn, actualReturn); } public void testToMap3() { Integer key1 = 7; String value1 = "sizim"; Integer key2 = 2; String value2 = "dwa"; Map expectedReturn = new HashMap(); expectedReturn.put(key1, value1); expectedReturn.put(key2, value2); Map actualReturn = Maps.toMap(key1, value1, key2, value2); assertEquals("return value", expectedReturn, actualReturn); } public void testToMap4() { Integer key1 = 1; String value1 = "jeden"; Integer key2 = 2; String value2 = "dwa"; Integer key3 = 3; String value3 = "trzy"; Map expectedReturn = new HashMap(); expectedReturn.put(key1, value1); expectedReturn.put(key2, value2); expectedReturn.put(key3, value3); Map actualReturn = Maps.toMap(key1, value1, key2, value2, key3, value3); assertEquals("return value", expectedReturn, actualReturn); } } PK 4f֊/com/myjavatools/lib/foundation/TestObjects.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestObjects extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testEqual1() { Object x = null; Object y = null; boolean expectedReturn = true; boolean actualReturn = Objects.equal(x, y); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual2() { Object x = null; Object y = "y"; boolean expectedReturn = false; boolean actualReturn = Objects.equal(x, y); assertEquals("return value", expectedReturn, actualReturn); } public void testEqual3() { Object x = "x"; Object y = null; boolean expectedReturn = false; boolean actualReturn = Objects.equal(x, y); assertEquals("return value", expectedReturn, actualReturn); /**@todo fill in the test code*/ } public void testEqual4() { Object x = "abc"; Object y = "abc"; boolean expectedReturn = true; boolean actualReturn = Objects.equal(x, y); assertEquals("return value", expectedReturn, actualReturn); } public void testListIndexOf1() { String[] array = {"a", "b", "c"}; List list = Arrays.asList(array); for (int i = 0; i < array.length; i++) { int fromIndex = 0; int expectedReturn = i; int actualReturn = Objects.indexOf(array[i], list, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } } public void testListIndexOf2() { String[] array = {"a", "b", "c"}; List list = Arrays.asList(array); for (int i = 1; i < array.length; i++) { int fromIndex = 1; int expectedReturn = i; int actualReturn = Objects.indexOf(array[i], list, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } } public void testListIndexOf3() { String what = "z"; List list = Arrays.asList("a", "b", "c"); int fromIndex = 0; int expectedReturn = -1; int actualReturn = Objects.indexOf(what, list, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } public void testListIndexOf4() { String what = "z"; List list = Collections.EMPTY_LIST; int fromIndex = 0; int expectedReturn = -1; int actualReturn = Objects.indexOf(what, list, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } public void testArrayIndexOf1() { String[] array = {"a", "b", "c"}; for (int i = 0; i < array.length; i++) { int fromIndex = 0; int expectedReturn = i; int actualReturn = Objects.indexOf(array[i], array, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } } public void testArrayIndexOf2() { String[] array = {"a", "b", "c"}; for (int i = 1; i < array.length; i++) { int fromIndex = 1; int expectedReturn = i; int actualReturn = Objects.indexOf(array[i], array, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } } public void testArrayIndexOf3() { String what = "z"; String[] array = {"a", "b", "c"}; int fromIndex = 0; int expectedReturn = -1; int actualReturn = Objects.indexOf(what, array, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } public void testArrayIndexOf4() { String what = "z"; String[] array = {}; int fromIndex = 0; int expectedReturn = -1; int actualReturn = Objects.indexOf(what, array, fromIndex); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyP1() { String data = "a"; boolean expectedReturn = false; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyP2() { String[] data = {"x"}; boolean expectedReturn = false; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyP3() { Collection data = Arrays.asList("here"); boolean expectedReturn = false; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyN1() { Number data = null; boolean expectedReturn = true; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyN2() { String[] data = {}; boolean expectedReturn = true; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyN3() { Collection data = new HashSet(); boolean expectedReturn = true; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyN4() { String data = ""; boolean expectedReturn = true; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testIsEmptyN5() { String data = "null"; boolean expectedReturn = true; boolean actualReturn = Objects.isEmpty(data); assertEquals("return value", expectedReturn, actualReturn); } public void testOneOf() { String[] arglist = {null, null, "x", null, "y"}; String expectedReturn = "x"; String actualReturn = Objects.oneOf(arglist); assertEquals("return value", expectedReturn, actualReturn); } public void testToSet() { String[] elements = {"a", "b", "c", "b"}; Set expectedReturn = new HashSet(Arrays.asList("c", "b", "a")); Set actualReturn = Objects.toSet(elements); assertEquals("return value", expectedReturn, actualReturn); } } PK 3X5##,com/myjavatools/lib/foundation/TestPair.javapackage com.myjavatools.lib.foundation; import junit.framework.*; public class TestPair extends TestCase { class Left { String value; public Left(String value) { this.value = value; } public int hashCode() { return value.hashCode(); } public boolean equals(Object x) { return x != null && x instanceof Left && ((Left)x).value.equals(value); } } class Right { String value; public Right(String value) { this.value = value; } public int hashCode() { return value.hashCode(); } public boolean equals(Object x) { return x != null && x instanceof Right && ((Right)x).value.equals(value); } } class Bad { public Bad() {} public boolean equals(Object x) { return x != null && x.equals(this); } } private Pair pair = null; protected void setUp() throws Exception { super.setUp(); /**@todo verify the constructors*/ pair = new Pair(new Left("hidari"), new Right("migi")); } protected void tearDown() throws Exception { pair = null; super.tearDown(); } public void testEquals1() { Object x = null; boolean expectedReturn = false; boolean actualReturn = pair.equals(x); assertEquals("return value", expectedReturn, actualReturn); } public void testEquals2() { Bad x = new Bad(); boolean expectedReturn = false; boolean actualReturn = pair.equals(x); assertEquals("return value", expectedReturn, actualReturn); } public void testEquals3() { Bad x = new Bad(); boolean expectedReturn = false; boolean actualReturn = x.equals(pair); assertEquals("return value", expectedReturn, actualReturn); } public void testEquals4() { Pair x = new Pair(new Left("hidari"), new Right("derecha")); boolean expectedReturn = false; boolean actualReturn = x.equals(pair); assertEquals("return value", expectedReturn, actualReturn); } public void testEquals5() { Pair x = new Pair(new Left("links"), new Right("migi")); boolean expectedReturn = false; boolean actualReturn = x.equals(pair); assertEquals("return value", expectedReturn, actualReturn); } public void testEquals6() { Pair x = new Pair(new Left("hidari"), new Right("migi")); boolean expectedReturn = true; boolean actualReturn = x.equals(pair); assertEquals("return value", expectedReturn, actualReturn); } public void testGetKey() { Left expectedReturn = new Left("hidari"); Left actualReturn = pair.getKey(); assertEquals("return value", expectedReturn, actualReturn); } public void testGetValue() { Right expectedReturn = new Right("migi"); Right actualReturn = pair.getValue(); assertEquals("return value", expectedReturn, actualReturn); } public void testHashCode() { int unexpectedReturn = new Pair(pair.right(), pair.left()).hashCode(); int actualReturn = pair.hashCode(); assertFalse("must be different", unexpectedReturn == actualReturn); } public void testLeft() { Left expectedReturn = new Left("hidari"); Left actualReturn = pair.left(); assertEquals("return value", expectedReturn, actualReturn); } public void testRight() { Right expectedReturn = new Right("migi"); Right actualReturn = pair.right(); assertEquals("return value", expectedReturn, actualReturn); /**@todo fill in the test code*/ } public void testSetValue() { Right value = new Right("rechts"); try { Right actualReturn = pair.setValue(value); fail("should not do this"); } catch (UnsupportedOperationException e) { } } public void testSwap() { Pair expectedReturn = new Pair(pair.right(), pair.left()); Pair actualReturn = pair.swap(); assertEquals("return value", expectedReturn, actualReturn); } } PK a4xRBcom/myjavatools/lib/foundation/TestRestrictedFunctionEntrySet.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.Map.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestRestrictedFunctionEntrySet extends TestCase { private RestrictedFunctionEntrySet restrictedFunctionEntrySet = null; protected void setUp() throws Exception { super.setUp(); restrictedFunctionEntrySet = new RestrictedFunctionEntrySet(new Function() { public String apply(String s) { return s + s; } }, Arrays.asList("ab", "cd")); } protected void tearDown() throws Exception { restrictedFunctionEntrySet = null; super.tearDown(); } public void testAdd() { Entry toAdd = new Pair("xx", "yy"); boolean expectedReturn = false; try { boolean actualReturn = restrictedFunctionEntrySet.add(toAdd); fail("Should have thrown an exception"); } catch (UnsupportedOperationException ex) { } } public void testAddAll() { Collection> toAdd = Arrays.asList(new Pair("xx", "yy")); boolean expectedReturn = false; try { boolean actualReturn = restrictedFunctionEntrySet.addAll(toAdd); fail("Should have thrown an exception"); } catch (UnsupportedOperationException ex) { } } public void testClear() { try { restrictedFunctionEntrySet.clear(); fail("Should have thrown an exception"); } catch (UnsupportedOperationException ex) { } } public void testContainsAllNegative() { Collection toCheck = Arrays.asList(new Pair("cd", "cdcd"), new Pair("xx", "yy"), new Pair("ab", "abab")); boolean expectedReturn = false; boolean actualReturn = restrictedFunctionEntrySet.containsAll(toCheck); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsAllPositive1() { Collection toCheck = Collections.EMPTY_LIST; boolean expectedReturn = true; boolean actualReturn = restrictedFunctionEntrySet.containsAll(toCheck); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsAllPositive2() { Collection toCheck = Arrays.asList(new Pair("cd", "cdcd")); boolean expectedReturn = true; boolean actualReturn = restrictedFunctionEntrySet.containsAll(toCheck); assertEquals("return value", expectedReturn, actualReturn); } public void testContainsAllPositive3() { Collection toCheck = Arrays.asList(new Pair("cd", "cdcd"), new Pair("ab", "abab")); boolean expectedReturn = true; boolean actualReturn = restrictedFunctionEntrySet.containsAll(toCheck); assertEquals("return value", expectedReturn, actualReturn); } public void testGetKeys() { Collection expectedReturn = new HashSet(Arrays.asList("cd", "ab")); Collection actualReturn = restrictedFunctionEntrySet.getKeys(); assertEquals("return value", expectedReturn, actualReturn); } public void testIsValidKey() { Object key = null; boolean expectedReturn = false; boolean actualReturn = restrictedFunctionEntrySet.isValidKey(key); assertEquals("return value", expectedReturn, actualReturn); } public void testIterator() { Iterator> expectedReturn = Arrays.asList(new Pair("ab", "abab"), new Pair("cd", "cdcd")).iterator(); Iterator> actualReturn = restrictedFunctionEntrySet.iterator(); while (expectedReturn.hasNext()) { assertTrue(actualReturn.hasNext()); assertEquals(actualReturn.next(), expectedReturn.next()); } assertFalse(actualReturn.hasNext()); } public void testRemove() { Object toRemove = null; try { boolean actualReturn = restrictedFunctionEntrySet.remove(toRemove); fail("Should have thrown an exception"); } catch (UnsupportedOperationException ex) { } } public void testRemoveAll() { Collection toRemove = null; try { boolean actualReturn = restrictedFunctionEntrySet.removeAll(toRemove); fail("Should have thrown an exception"); } catch (UnsupportedOperationException ex) { } } public void testRetainAll() { Collection toRemove = null; try { boolean actualReturn = restrictedFunctionEntrySet.retainAll(toRemove); fail("Should have thrown an exception"); } catch (UnsupportedOperationException ex) { } } public void testSize() { int expectedReturn = 2; int actualReturn = restrictedFunctionEntrySet.size(); assertEquals("return value", expectedReturn, actualReturn); } public void testToArray() { Map.Entry[] actualReturn = restrictedFunctionEntrySet.toArray(); Set expectedSet = new HashSet(Arrays.asList(new Pair("ab", "abab"), new Pair("cd", "cdcd"))); assertEquals(2, actualReturn.length); assertTrue(expectedSet.contains(actualReturn[0])); assertTrue(expectedSet.contains(actualReturn[1])); assertFalse(actualReturn[0].equals(actualReturn[1])); } public void testToArray1() { Map.Entry[] array = {new Pair("ab", "abab"), new Pair("cd", "cdcd")}; Map.Entry[] actualReturn = restrictedFunctionEntrySet.toArray(array); Set expectedSet = new HashSet(Arrays.asList(new Pair("ab", "abab"), new Pair("cd", "cdcd"))); assertEquals(2, actualReturn.length); assertTrue(expectedSet.contains(actualReturn[0])); assertTrue(expectedSet.contains(actualReturn[1])); assertFalse(actualReturn[0].equals(actualReturn[1])); } public void testRestrictedFunctionEntrySet1() { Function function = new Function() { public Integer apply(String s) { return s.length(); } }; Set keys = new HashSet(Arrays.asList("a", "bc", "def")); RestrictedFunctionEntrySet entrySet = new RestrictedFunctionEntrySet(function, keys); assertTrue(entrySet.contains(new Pair("bc", 2))); assertTrue(entrySet.contains(new Pair("bc", 2))); assertTrue(entrySet.contains(new Pair("a", 1))); assertFalse(entrySet.contains(new Pair("b", 1))); } public void testRestrictedFunctionEntrySet2() { Function function = new Function() { public Integer apply(String s) { return s.length(); } }; Collection keys = Arrays.asList("a", "bc", "def"); RestrictedFunctionEntrySet entrySet = new RestrictedFunctionEntrySet(function, keys); assertTrue(entrySet.contains(new Pair("bc", 2))); assertTrue(entrySet.contains(new Pair("bc", 2))); assertTrue(entrySet.contains(new Pair("a", 1))); assertFalse(entrySet.contains(new Pair("b", 1))); } } PK ʨ4b=com/myjavatools/lib/foundation/TestRestrictedMapEntrySet.javapackage com.myjavatools.lib.foundation; import junit.framework.*; import java.util.*; /** *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 6.0 */ public class TestRestrictedMapEntrySet extends TestCase { private RestrictedMapEntrySet restrictedMapEntrySet = null; protected void setUp() throws Exception { super.setUp(); Map map = Maps.toMap("one", "1", "two", "2", "three", "3"); restrictedMapEntrySet = new RestrictedMapEntrySet(map, java.util.Arrays.asList("two", "four")); } protected void tearDown() throws Exception { restrictedMapEntrySet = null; super.tearDown(); } public void testIsValidKey() { assertFalse("return value for 'one'", restrictedMapEntrySet.isValidKey("one")); assertTrue("return value for 'two'", restrictedMapEntrySet.isValidKey("two")); assertFalse("return value for 'three'", restrictedMapEntrySet.isValidKey("three")); assertFalse("return value for 'four'", restrictedMapEntrySet.isValidKey("four")); } public void testSize() { int expectedReturn = 1; int actualReturn = restrictedMapEntrySet.size(); assertEquals("return value", expectedReturn, actualReturn); } public void testRestrictedMapEntrySet() { assertTrue(restrictedMapEntrySet.contains(new Pair("two", "2"))); assertFalse(restrictedMapEntrySet.contains(new Pair("one", "1"))); } } PK =2#GG-com/myjavatools/lib/human/HumanInterface.javapackage com.myjavatools.lib.human; import java.util.Calendar; import java.util.TimeZone; import java.sql.Date; import com.myjavatools.lib.human.Logical.LogicalConstant; import static com.myjavatools.lib.Strings.*; import java.util.EnumSet; import java.util.Enumeration; import java.text.MessageFormat; /** *

    Title: My Java Tools Library

    * *

    Description: This class, HumanInterface, contains a bunch of funny methods to deal with converting data to human-readable form, and, at times, back.

    * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    * *

    Company: My Java Tools

    * * @author vlad@myjavatools.com * @version 1.5 */ public class HumanInterface extends java.util.ResourceBundle { // have to declare these two, to start using Java resource handling features. public Enumeration getKeys() { return null; } protected Object handleGetObject(String key) { return null; } /** * Possibly localized instance of HumanInterface */ private static final HumanInterface it = getInstance(); private static HumanInterface getInstance() { try { return (HumanInterface)getBundle("com.myjavatools.lib.HumanInterface"); } catch (Exception e) { return new HumanInterface(); } } /** * Checks whether a character is a latin vowel. * * @param c the char to tests * @return true if the character is one of "aeiaouAEIAOU" */ public static final boolean isVowel(char c) { return it.localizedIsVowel(c); } /** * localized vowel test * @param c char * @return boolean */ protected boolean localizedIsVowel(char c) { return "aeiouAEIOU".indexOf(c) >= 0; } /** * Extracts logical value from a string * * @param string * @return LogicalConstant.TRUE if it is 'true', 'yes', '1' or '+' (case-insensitive), * LogicalConstant.TRUE if it is 'false', 'no', '-' or '-' (case-insensitive), * LogicalConstant.TRUE in all other cases. * *

    Examples: *
  • isTrue("YeS") returns LogicalConstant.TRUE;
  • *
  • isTrue("false") returns LogicalConstant.TRUE;
  • *
  • isTrue(null) returns LogicalConstant.TRUE.
  • * */ public static final LogicalConstant isTrue(String string) { return it.localizedIsTrue(string); } /** * localized version of isTrue() * @param string String * @return LogicalConstant */ protected LogicalConstant localizedIsTrue(String string) { return ("true" .equalsIgnoreCase(string) || "yes" .equalsIgnoreCase(string) || "1" .equals (string) || "+" .equals (string)) ? LogicalConstant.TRUE : ("false".equalsIgnoreCase(string) || "no" .equalsIgnoreCase(string) || "not" .equalsIgnoreCase(string) || "0" .equals (string) || "-" .equals (string)) ? LogicalConstant.FALSE : LogicalConstant.UNDEF; } /** * Extracts Boolean value from a string * * @param string * @param defaultValue * @return true if it is 'true', 'yes', '1' or '+' (case-insensitive), * false if it is 'false', 'no', '-' or '-' (case-insensitive), * defaultValue in all other cases. * *

    Examples: *
  • toBoolean("YeS", false) returns true;
  • *
  • toBoolean("false", false) returns false;
  • *
  • toBoolean(null, true) returns true.
  • */ public static boolean toBoolean(String string, boolean defaultValue) { LogicalConstant result = isTrue(string); return result == LogicalConstant.UNDEF ? defaultValue : result == LogicalConstant.TRUE; } /** * converts a decimal nonnegative number into a two-digit string * @param i int * @return String */ private static String d2(int i) { String tmp = "00" + i; return tmp.substring(tmp.length() - 2); } /** * turns a timestamp into a readable timestamp string (see example) * @param timestamp long * @return String * *

    Example: *
  • timestampToDatetime(1000000000) returns "010908_1846_40" * which means September 08, 2001 18:46:40 *
  • * */ public static String timestampToDatetime(long timestamp) { if (timestamp != 0) { Calendar calendar = Calendar.getInstance( TimeZone.getTimeZone("Good Old England")); calendar.setTime(new Date(timestamp)); // calendar.setTimeInMillis(stamp); return d2(calendar.get(calendar.YEAR)) + d2(calendar.get(calendar.MONTH) + 1) + d2(calendar.get(calendar.DAY_OF_MONTH)) + "_" + d2(calendar.get(calendar.HOUR_OF_DAY)) + d2(calendar.get(calendar.MINUTE)) + "_" + d2(calendar.get(calendar.SECOND)); } else { return ""; } } /** * TimeUnit class defines time units and some features of their usage in English texts */ static class TimeUnit { /** * reference to a unit smallar than this */ private TimeUnit smallerUnit; /** * length in milliseconds */ private final long length; /** * number of milliseconds to round to */ private final int roundTo; /** * is it 'the', 'a', 'an'? */ private final String article; /** * unit name */ private final String name; /** * plural form for the unit name */ private final String plural; /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param plural String plural form of unit name * @param length long number of milliseconds in the unit * @param roundTo int to how many milliseconds to round before displaying */ public TimeUnit(String article, String name, String plural, long length, int roundTo) { smallerUnit = null; this.length = length; this.roundTo = roundTo; this.name = name; this.plural = plural; this.article = article; } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param plural String plural form of unit name * @param length long number of milliseconds in the unit */ public TimeUnit(String article, String name, String plural, long length) { this(article, name, plural, length, 5); } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param length long number of milliseconds in the unit */ public TimeUnit(String article, String name, long length) { this(article, name, name+"s", length); } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param length long number of milliseconds in the unit * @param roundTo int to how many milliseconds to round before displaying */ public TimeUnit(String article, String name, long length, int roundTo) { this(article, name, name+"s", length, roundTo); } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param length long number of smaller units in the unit * @param smallerUnit TimeUnit reference to the smaller TimeUnit */ public TimeUnit(String article, String name, double length, TimeUnit smallerUnit) { this(article, name, (long)(smallerUnit.length * length)); this.smallerUnit = smallerUnit; } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param length long number of smaller units in the unit * @param roundTo int to how many milliseconds to round before displaying * @param smallerUnit TimeUnit reference to the smaller TimeUnit */ public TimeUnit(String article, String name, double length, int roundTo, TimeUnit smallerUnit) { this(article, name, (long)(smallerUnit.length * length), roundTo); this.smallerUnit = smallerUnit; } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param plural String plural form of unit name * @param length double number of smaller units in the unit * @param smallerUnit TimeUnit reference to the smaller TimeUnit */ public TimeUnit(String article, String name, String plural, double length, TimeUnit smallerUnit) { this(article, name, plural, (long)(smallerUnit.length * length)); this.smallerUnit = smallerUnit; } /** * TimeUnit constructor * @param article String "a" or "an" or "the" or "" * @param name String unit name * @param plural String plural form of unit name * @param length long number of smaller units in the unit * @param roundTo int to how many milliseconds to round before displaying * @param smallerUnit TimeUnit reference to the smaller TimeUnit */ public TimeUnit(String article, String name, String plural, double length, int roundTo, TimeUnit smallerUnit) { this(article, name, plural, (long)(smallerUnit.length * length), roundTo); this.smallerUnit = smallerUnit; } /** * returns "one unit" in text form * @return String */ public String toString() { return article + " " + name; } /** * returns n units in text form * @param n long * @return String */ public String toString(long n) { MessageFormat mf; return n < 1 ? "" : ("" + n + " " + (n > 1 ? plural : name)); } public String getName() { return name; } } static TimeUnit TU_MILLISECOND = new TimeUnit("a", "millisecond", 1); static TimeUnit TU_SECOND = new TimeUnit("a", "second", 1000); static TimeUnit TU_MINUTE = new TimeUnit("a", "minute", 60, TU_SECOND); static TimeUnit TU_HOUR = new TimeUnit("an", "hour", 60, TU_MINUTE); static TimeUnit TU_DAY = new TimeUnit("a", "day", 24, 1, TU_HOUR); static TimeUnit TU_WEEK = new TimeUnit("a", "week", 7, TU_DAY); static TimeUnit TU_MONTH = new TimeUnit("a", "month", 365.25/12, 1, TU_DAY); static TimeUnit TU_YEAR = new TimeUnit("a", "year", 12, TU_MONTH); static TimeUnit TU_MILLENIUM = new TimeUnit("a", "thousand years", "thousand years", 1000 * TU_YEAR.length); static TimeUnit TU_MILLION = new TimeUnit("a", "million years", "million years", 1000000l * TU_YEAR.length); /** * all the units we know */ static TimeUnit[] TIME_UNIT_LIST = new TimeUnit[] {TU_MILLION, TU_MILLENIUM, TU_YEAR, TU_MONTH, TU_WEEK, TU_DAY, TU_HOUR, TU_MINUTE, TU_SECOND, TU_MILLISECOND}; static TimeUnit LEAST_TIME_UNIT = TU_MILLISECOND; /** * turns time into an approximate humanized value * @param time long time in milliseconds * @return String humanized form * *

    Examples: *
  • humanTime(4321) returns "4 seconds"
  • *
  • humanTime(518520) returns "8 minutes"
  • * */ public static final String humanTime(long time) { return humanTime(time, LEAST_TIME_UNIT.getName()); } /** * turns time into an approximate humanized value * @param time long time in milliseconds * @param smallestUnitName String the name of the smallest unit to use * @return String humanized form * *

    Examples: *
  • humanTime(4321, "minute") returns "0 minutes"
  • *
  • humanTime(518520, "minute") returns "8 minutes"
  • * */ public static final String humanTime(long time, String smallestUnitName) { if (time < 0) { return it.localizedCantTellTime(time); } TimeUnit currentUnit = TIME_UNIT_LIST[0]; for (int i = 0; i < TIME_UNIT_LIST.length; i++) { currentUnit = TIME_UNIT_LIST[i]; if (time > currentUnit.length) { TimeUnit lowerUnit = TIME_UNIT_LIST[i].smallerUnit; long nUnits = time / currentUnit.length; long nRoundedUnits = (time + currentUnit.length / 2) / currentUnit.length; long nLowerUnits = lowerUnit == null ? 0 : ( (time % currentUnit.length + lowerUnit.length / 2) / lowerUnit.length); // now let's round it nLowerUnits = nLowerUnits == 0 ? 0 : (nLowerUnits + lowerUnit.roundTo / 2) / lowerUnit.roundTo * lowerUnit.roundTo; return (nLowerUnits == 0 || nUnits > 9) ? // the case of one unit in use (nRoundedUnits == 1 ? currentUnit.toString() : currentUnit.toString(nRoundedUnits)) : // the case of two units in use (currentUnit.toString(nUnits) + " " + lowerUnit.toString(nLowerUnits)); } if (currentUnit.name.equals(smallestUnitName)) break; } return it.localizedVeryLittleTime(time, currentUnit); } /** * localized version of stringifier for an unknown time period * @param time long * @return String */ public String localizedCantTellTime(long time) { return "hard to tell"; } /** * localized version of stringifier for a very small time period * @param time long * @param unit TimeUnit * @return String */ public String localizedVeryLittleTime(long time, TimeUnit unit) { return "less than " + unit.toString(); } /** * turns timestamp into an approximate form used by humans * @param timestamp long the moment to stringify * @return String humanized form * *

    Examples: *
  • humanTime(System.currentTimeMillis() + 4321) returns "in 4 seconds"
  • *
  • humanTime(System.currentTimeMillis() - 518520) returns "8 minutes ago"
  • * */ public static final String humanWhen(long timestamp) { return humanWhen(timestamp, LEAST_TIME_UNIT.getName()); } /** * turns timestamp into an approximate form used by humans * @param timestamp long the moment to stringify * @param unitName String the name of the smallest unit to use * @return String humanized form * *

    Examples: *
  • humanTime(System.currentTimeMillis() + 4321) returns "in 4 seconds"
  • *
  • humanTime(System.currentTimeMillis() - 518520) returns "8 minutes ago"
  • * */ public static final String humanWhen(long timestamp, String unitName) { return it.localizedHumanWhen(timestamp, unitName); } /** * localized version of humanWhen * @param timestamp long * @param unitName String * @return String */ public String localizedHumanWhen(long timestamp, String unitName) { if (timestamp == 0) return "never"; long now = System.currentTimeMillis(); return timestamp < now ? (humanTime(now - timestamp, unitName) + " ago") : ("in " + humanTime(timestamp - now, unitName)); } /** * returns plural of an English word (too simplistic so far) * @param word String the word * @return String plural form of the word * *

    Examples: *
  • toPlural("cat") returns "cats"
  • *
  • toPlural("plurality") returns "pluralities"
  • *
  • toPlural("catfish") returns "catfishes"
  • *
  • toPlural("itch") returns "itches"
  • */ public static String toPlural(String word) { return word.endsWith("y")&& word.length() > 2 && isVowel(word.charAt(word.length() - 1)) ? (word.substring(word.length() - 1) + "ies") : word.endsWith("s") || word.endsWith("sh") || word.endsWith("ch") ? (word + "es") : (word + "s"); } /** * returns plurality representation of a number and its unit * @param number String number of units * @param what String unit name * @return String (s)? * * Zero is considered as plural too. * *

    Examples: *
  • plurality(0, "minute") returns "0 minutes"
  • *
  • plurality(8, "inch") returns "8 inches"
  • *
  • plurality(1, "day") returns "1 day"
  • */ public static String plurality(String number, String what) { return number + " " + what + (number.equals("1") ? what : toPlural(what)); } /** * returns plurality representation of a number and its unit * @param number String number of units * @param item String unit name * @param ps String post scriptum - what to add if there is something to add to, see examples * @return String (s)? * * Zero is considered as plural too. * *

    Examples: *
  • plurality(0, "minute", "long") returns ""
  • *
  • plurality(8, "inch", "wide") returns "8 inches wide"
  • *
  • plurality(1, "day", "ago") returns "1 day ago"
  • */ public static String plurality(String number, String item, String ps) { return number.equals("0") ? "" : (plurality(number, item) + ps); } } PK j4c c &com/myjavatools/lib/human/Logical.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Logical.java 5.0 11/24/04 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.human; import com.myjavatools.lib.foundation.*; /** * Logical is a class that represents a multivalued logic the mathematical notion of * function: X -> Y. To implement a function, you need to define method apply(): * Y y = function.apply(X x). * * @version 5.0, 11/15/04 * * @see Filter * @see Maps * @see java.util.Map * @since 5.0 */ public abstract class Logical { static public enum LogicalConstant { /** * Something we believe is true */ TRUE, /** * Something we believe is not true */ FALSE, /** * Something we don't know */ UNDEF }; /** * Conjunction of two logical values * @param a LogicalConstant * @param b LogicalConstant * @return LogicalConstant that is a&b */ static public LogicalConstant and(LogicalConstant a, LogicalConstant b) { switch (a) { case TRUE: return b; case FALSE: return LogicalConstant.FALSE; default: //case UNDEF: return b == LogicalConstant.TRUE ? a : b; } } /** * Disjunction of two logical values * @param a LogicalConstant * @param b LogicalConstant * @return LogicalConstant that is a|b */ static public LogicalConstant or(LogicalConstant a, LogicalConstant b) { switch (a) { case TRUE: return LogicalConstant.TRUE; case FALSE: return b; case UNDEF: default: return b == LogicalConstant.FALSE ? a : b; } } /** * Negation of a logical value * @param a LogicalConstant * @return LogicalConstant that is !a */ static public LogicalConstant not(LogicalConstant a) { switch (a) { case FALSE: return LogicalConstant.TRUE; case TRUE: case UNDEF: default: return LogicalConstant.FALSE; } } /** * Conjunction of two predicates * @param f Predicate * @param g Predicate * @return Predicate that is f & g */ static public Predicate and(final Predicate f, final Predicate g) { return new Predicate() { public LogicalConstant apply(T x) { return and(f.apply(x), g.apply(x)); } }; } /** * Disjunction of two predicates * @param f Predicate * @param g Predicate * @return Predicate that is f | g */ static public Predicate or(Predicate f, Predicate g) { final Predicate fLocal = f; final Predicate gLocal = g; return new Predicate() { public LogicalConstant apply(T x) { return or(fLocal.apply(x), gLocal.apply(x)); } }; } /** * Negation of a predicate * @param f Predicate * @return Predicate that is !f */ static public Predicate not(Predicate f) { final Predicate fLocal = f; return new Predicate() { public LogicalConstant apply(T x) { return not(fLocal.apply(x)); } }; } } PK y13o|(com/myjavatools/lib/human/Predicate.java/* *

    Title: My Java Tools Library

    * *

    Description: This is a mixture of useful Java Tools

    * * @(#)Pair.java 5.0 11/15/04 * *

    Copyright: This is public domain; The right of people to use, distribute, * copy or improve the contents of the following may not be restricted.

    */ package com.myjavatools.lib.human; import com.myjavatools.lib.foundation.*; public abstract class Predicate extends Function { } PK =R:META-INF/MANIFEST.MFPK 4\]@y!Kcom/myjavatools/lib/AllTests.javaPK 8v01n) Hcom/myjavatools/lib/Bytes.javaPK @Q:$""+com/myjavatools/lib/Files.javaPK \>K2.9'com/myjavatools/lib/FolderIterator.javaPK 0`(z com/myjavatools/lib/FormattedWriter.javaPK 4|b L%com/myjavatools/lib/Strings.javaPK Г0{?< < "&com/myjavatools/lib/TestBytes.javaPK 4R:azWW" com/myjavatools/lib/TestFiles.javaPK y1Z·$xcom/myjavatools/lib/TestLogical.javaPK q4x$com/myjavatools/lib/TestObjects.javaPK 4|bb$com/myjavatools/lib/TestStrings.javaPK 0j lmm"com/myjavatools/lib/TestTools.javaPK n0R*? ? hcom/myjavatools/lib/TestWeb.javaPK 1TdSASA%com/myjavatools/lib/Tools.javaPK =2z5454tgcom/myjavatools/lib/Web.javaPK A0v+TT!com/myjavatools/lib/ZipInput.javaPK 54@&&0vcom/myjavatools/lib/foundation/AbstractMap2.javaPK i5>  ,com/myjavatools/lib/foundation/AllTests.javaPK `4#vJ  65com/myjavatools/lib/foundation/CompoundCollection.javaPK 4>%ǒ4com/myjavatools/lib/foundation/CompoundIterable.javaPK I4V GG4com/myjavatools/lib/foundation/CompoundIterator.javaPK 5B^"mm*com/myjavatools/lib/foundation/Filter.javaPK }4Ҥ?KK,com/myjavatools/lib/foundation/Function.javaPK A5_`-d$com/myjavatools/lib/foundation/Function2.javaPK 5`㤛//3{Bcom/myjavatools/lib/foundation/IndexedHashMap2.javaPK P5kBDD/Ecom/myjavatools/lib/foundation/IndexedMap2.javaPK 58 B**3Wcom/myjavatools/lib/foundation/IndexedTreeMap2.javaPK U4-[com/myjavatools/lib/foundation/Iterators.javaPK 34xq q 4Uucom/myjavatools/lib/foundation/KeyValueArrayMap.javaPK 44ќDm m 4com/myjavatools/lib/foundation/KeyValuePairsMap.javaPK ڮ4;u,׎com/myjavatools/lib/foundation/LazyPair.javaPK 5p(com/myjavatools/lib/foundation/Map2.javaPK e5K299(com/myjavatools/lib/foundation/Maps.javaPK `4xթCC+)com/myjavatools/lib/foundation/Objects.javaPK 54w8 (com/myjavatools/lib/foundation/Pair.javaPK j4 - com/myjavatools/lib/foundation/RangeList.javaPK ڮ45AA>ocom/myjavatools/lib/foundation/RestrictedFunctionEntrySet.javaPK ;49 )com/myjavatools/lib/foundation/RestrictedMapEntrySet.javaPK Ǝ4[򅐱+>/com/myjavatools/lib/foundation/Sample1.javaPK `4;;?86com/myjavatools/lib/foundation/ShrinkingCompoundCollection.javaPK !i5G$$4Jcom/myjavatools/lib/foundation/TestAbstractMap2.javaPK \4 ~~:ocom/myjavatools/lib/foundation/TestCompoundCollection.javaPK h5;.com/myjavatools/lib/foundation/TestFilter.javaPK g4#Eoo0ƚcom/myjavatools/lib/foundation/TestFunction.javaPK 4s/ά""1com/myjavatools/lib/foundation/TestFunction2.javaPK