package test;

import java.io.*;
import java.util.*;
import java.util.jar.*;

public class JarList {

	/**
	 * Return true if the given name ends with ".jar"  (Case is ignored.)
	 */
	private static boolean isJar(String name) {
		int dotIndex = name.lastIndexOf('.');
		String ext = name.substring(dotIndex + 1).toLowerCase();

		return ext.equals("jar");
	}

	/**
	 * List the contents of a JAR, prefixed with the name of the JAR on each line
	 * so that it's easy to GREP.
	 */
	private static void displayContents(File file) {
		try {
			JarFile jar = new JarFile(file);
			String jarName = file.getName();

			for (Enumeration e = jar.entries(); e.hasMoreElements();) {
				System.out.println(jarName + " : " + e.nextElement());
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * Users may optionally specify a JAR file or a directory containing zero or more JAR files.
	 * Subdirectories are not parsed.
	 */
	public static void main(String [] args) {
		// if they didn't specify a file, then use the current directory
		String path = (args.length >= 1 ? args[0] : ".");

		File source = new File(path);

		if (source.exists()) {
			if (source.isDirectory()) {
				// if it's a directory, enumerate its files
				FilenameFilter myFilter = new FilenameFilter() {
							public boolean accept(File dir, String name) {
								return isJar(name);
							}
						};

				File [] files = source.listFiles(myFilter);

				System.out.println("Enumerating the contents of " + files.length + " JAR files.");

				for (File file : files) {
					displayContents(file);
				}

				// enumerate each file's contents
			} else if (isJar(source.getName())) {
				// if it's a jar file, just enumerate its contents
				displayContents(source);
			} else {
				System.err.println("Error: File \"" + path + "\" is not a JAR.");
			}
		} else {
			System.err.println("Error: Path \"" + path + "\" not found.");
		}
	}

}

