Discussions

EJB design: Which classpath OS sets accord. to ClassLoaders (complete Ex.)

  1. Hi all
    I hope you all will find this example fruitfull
    as this is a complete working example
    you can supply any class name without .class extension & can find out from where it is being loaded on the system
    Regards:
    Deep Singh

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FilenameFilter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Properties;
    import java.util.StringTokenizer;
    import java.util.jar.JarEntry;
    import java.util.jar.JarInputStream;

    /**
     * @author deep
     * this program will find out the classpath
     * according to the classLoader from the
     * system envoronment variables..
     *
     */
    public class JarUtil {
    /*
    * Getting the environment Variables
    */
    public static String classPath = System.getenv("Classpath");
    public static String pathSeperator =
    System.getProperty("path.seperator", ";");
    public static String fileSeperator =
    System.getProperty("file.seperator", "\"");
    public static int workingDirIndex = classPath.indexOf(pathSeperator) + 1;
    ArrayList retrievedContents = new ArrayList();

    public JarUtil(String clsName) throws IOException, ClassNotFoundException {
    //class name to be searched in the environment variables classPath
    String clName = clsName;
    // Splitting the classPath into tokens
    StringTokenizer tokens = new StringTokenizer(classPath, pathSeperator);

    while (tokens.hasMoreElements()) {
    File file = new File(tokens.nextToken());
    if (file.exists()) {
    if (file.isDirectory()) {

    System.out.println(file);
    try {
    checkDirContents(
    file,
    file.getAbsolutePath().length () + 1,clName);
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    } else {
    // assume that it is a Jar File
    System.out.println("File Is Not Dir " + file);
    try {
    checkJarFileContents(file, clName);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    }
    } //end constructor

    public ArrayList getRetrievedContents() {
    return retrievedContents;
    }

    /**
    * checks for the jar file in the classpath directory
    * @param jarFile
    * @param className
    * @throws IOException,ClassNotFoundException
    */

    public void checkJarFileContents(File jarFile, String className)
    throws IOException, ClassNotFoundException {

    System.out.println("Passed ClassName" + jarFile);
    InputStream inputStream =
    new BufferedInputStream(new FileInputStream(jarFile));
    JarInputStream jarInput = new JarInputStream(inputStream);
    /**
    * creating the jar entry object
    */
    JarEntry entry;
    while ((entry = jarInput.getNextJarEntry()) != null) {
    String clsName = entry.getName().replace('/', '.');
    System.out.println(
    "entery in check Jar Contents " + entry.getName());
    if (clsName.endsWith(".class")) {
    System.out.println( "classes that ends with the .class" + entry.getName());

    int lenTot = 0;
    //Total length of the passed class name
    int len = clsName.length();
    int len1 = 0;
    String newClassName = "";
    int startIndex = 0;
    String classExtension = "";
    /**
    * This Loop will extract the .class files
    */
    for (int totLen = clsName.length(); totLen >= 0; totLen--) {

    if (clsName.charAt(totLen - 1) == '.') {

    startIndex = totLen + 1;

    break;
    }

    }
    // Extraction of the File Extension
    classExtension = clsName.substring(startIndex - 1, len);

    System.out.println("Check for ClassExtension " + classExtension);

    //if it is a jar file direct it to the checkjarfile Contents
    if (classExtension.equals("class")) {
    clsName = clsName.substring(0, clsName.length() - 6);
    System.out.println("In Check Jar Contents" + clsName);
    lenTot = clsName.length();
    startIndex = 0;
    len1 = 0;
    for (len1 = (lenTot - 1); len1 >= 0; len1--) {
    //System.out.println("clsName.charAt("+ len1+ ") :"+ clsName.charAt(len1));
    if (clsName.charAt(len1) == '.') {
    System.out.println("Total Length " + lenTot);
    startIndex = len1;
    break;
    }
    }

    //Extracting the File name to match with the given/Passed File
    newClassName = clsName.substring((startIndex + 1), lenTot);
    /**
    * if the class name is equal to the searched className
    */
    if (newClassName.equals(className)) {
    System.out.println(
    "matches found for the classfile given");
    //replace all '/' with '.'
    clsName = clsName.replace('
    ', '.');
    retrievedContents.add(
    Class.forName(clsName,true, ClassLoader.getSystemClassLoader()));
    } else {
    System.out.println("matches Not Found");
    }

    }

    /*if (clsName.startsWith(className)) {
    clsName = clsName.substring(0, clsName.length() - 6);
    try {
    retrievedContents.add(
    Class.forName(
    clsName,
    true,
    ClassLoader.getSystemClassLoader()));
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    break;
    } else {

    }*/

    }
    }
    } //end of the checkJarContents
    /**
    * Check the directory contents for the .class files sub directories & jar files
    * @param dir
    * @param dirNameStart
    * @param className
    * @exception ClassNotFoundException, IOException
    */
    public void checkDirContents(File dir, int dirNameStart, String className)
    throws ClassNotFoundException, IOException {
    //check the directory for .class files and sub directories
    System.out.println("In check dir contents");

    File files[] = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
    //Defines the start index from where the class extension would be cut
    int startIndex = 0;
    // variables for the loop
    int lenTot = 0;
    int len = 0;
    String newClassName = "";
    String clsName = "";
    String classExtension = "";
    File fp = files[i];
    System.out.println("In check dir contents in for Loop");
    if (fp.exists()) {

    //check whether it is file or directory
    if (fp.isDirectory()) {
    System.out.println("check for directory in checkdir contents");
    checkDirContents(fp,(fp.getAbsolutePath().length()) + 1,className);
    }
    //the file is a .class file or any other file
    else {

    int totLen = 0;
    int len1 = 0;
    System.out.println("if it is a file");
    String filePath = fp.getPath();

    System.out.println(filePath);

    clsName =filePath.substring(workingDirIndex,filePath.length());

    System.out.println("Working dir index " + workingDirIndex);
    System.out.println(clsName);

    len = clsName.length();
    System.out.println("Length" + len);
    startIndex = 0;
    for (totLen = clsName.length(); totLen >= 0; totLen--) {

    if (clsName.charAt(totLen - 1) == '.') {
    startIndex = totLen + 1;
    break;
    }
    }
    classExtension = clsName.substring(startIndex - 1, len);

    System.out.println("Check for ClassExtension " +classExtension);

    //if it is a jar file direct it to the checkjarfile Contents
    if (classExtension.equals("jar")) {
    System.out.println(
    "class extension before directing it to checkjarfileconents"
    + classExtension);
    System.out.println(
    "Filename before directing it to checkjarfileconents"
    + fp);
    checkJarFileContents(fp, className);
    }
    // if the file is a class file then extract the Name & compare
    else if (classExtension.equals("class")) {

    //Extract the file name Except the .class extension
    clsName = clsName.substring(0, clsName.length() - 6);
    System.out.println("Hello BBBBB 2" + clsName);
    lenTot = clsName.length();
    // this index will be from where the actual file name
    //eg "com\thbs\deep1 " deep1 to be extracted
    startIndex = 0;
    len1 = 0;
    /**
    * this loop will check the occurence of the last '\'
    */
    for (len1 = (lenTot - 1); len1 >= 0; len1--) {
    System.out.println("clsName.charAt("+ len1+ "):"
    + clsName.charAt(len1));
    if (clsName.charAt(len1) == '
    ') {
    System.out.println ("Total Length " + lenTot);
    startIndex = len1;
    break;
    }
    }

    System.out.println("startIndex+1 "+ startIndex);
    System.out.println("lenTot-1 " + (lenTot - 1));



    /**
    * will extract the exact file name that has to be matched
    */
    newClassName =clsName.substring((startIndex + 1), lenTot);
    System.out.println("newClassName " + newClassName);
    System.out.println(clsName);
    System.out.println(className);
    /**
    * if the file name is equal then add the class loader to the array list
    * retrievedContents
    */

    if (newClassName.equals(className)){
    System.out.println(
    "matches found for the classfile given");

    clsName = clsName.replace('
    ', '.');
    retrievedContents.add(Class.forName(clsName,
    true,ClassLoader.getSystemClassLoader()));
    }
    /**
    * if .class has not matched the file name to be seaarched
    */
    else {
    System.out.println("matches Not Found");
    }
    }
    /**
    * if the file has not the .class * Extension
    */
    else {

    System.out.println("matches Not Found##########");
    }
    }
    }
    }
    } //end checkDirContents

    public static void main(String args[])
    throws IOException, ClassNotFoundException {

    BufferedReader bf =
    new BufferedReader(new InputStreamReader(System.in));
    String str = bf.readLine();
    str = str.trim();
    if (str != "") {

    JarUtil jarUtil = new JarUtil(str);
    Iterator it = jarUtil.getRetrievedContents().iterator();
    System.out.println("The Object found in");
    while (it.hasNext()) {
    Object objRetrieved = (Object) it.next();
    System.out.println(objRetrieved);
    }
    } else {
    System.out.println("Please Pass The FileName To Be Searched");
    //will wait and and read the input if null will exit

    System.out.println("Str : " + str);

    if (str == "")
    System.exit(0);
    }
    }

    } //end of class

    Threaded Messages (1)

  2. Why all the hard work?[ Go to top ]

    How is this any different/better than simply saying System.out.println(getClass().getResource("/foo/bar/FooBar.class")); ???