0

I have a code which gets the list of class file in given package name. However, code return me list of class files available in given package (com.testscript) but when I run the jar with same code with package (src.com.testscript) it does not return me the list of class file available in folder and sub folder. I have placed this jar file under main folder which contain jar file and scr package. Below is my code which i use to get class list.

package com.generateUI.createXML;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
import org.testng.internal.ClassHelper;
import org.testng.internal.annotations.AnnotationHelper;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.annotations.JDK15AnnotationFinder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.setup.CreateMethodsList;

public class FindTestMethodsInTestClass {

    public boolean isMethodsListXMLReady() throws ClassNotFoundException, IOException, InterruptedException {
        FindTestMethodsInTestClass FTMITC = new FindTestMethodsInTestClass();
        boolean bool=false;
        boolean isXMLFileExist = false;
        Map<String,CreateMethodsList> aMap=new HashMap<String,CreateMethodsList>();
        Class[] classes=getClasses("com.testscript");
        IAnnotationFinder finder = new JDK15AnnotationFinder(new DummyTransformer());
        for(Class cls:classes){
            String temp=cls.toString();
            String[] className=temp.split("\\.");
            String[] classPaht=temp.split(" ");
            List<String> mNames=new ArrayList();
            Set<Method> allMethods = ClassHelper.getAvailableMethods(cls);
            if(!(allMethods==null)){
                for (Method eachMethod : allMethods) {
                    ITestAnnotation value = AnnotationHelper.findTest(finder, eachMethod);
                    if (value != null) {
                        mNames.add(eachMethod.getName());
                        bool=true;
                    }
                }
                if(bool){
                    int lastIndex=className.length-1;
                    aMap.put(className[lastIndex],new CreateMethodsList(mNames,classPaht[1]));
                }
            }
        }
        if(FTMITC.CreateXML(aMap)){
            isXMLFileExist=true;
        }
        return isXMLFileExist;
    }

    public static class DummyTransformer implements IAnnotationTransformer {

        @SuppressWarnings("rawtypes")
        @Override
        public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor,
                Method testMethod) {
        }
    }

    /**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     *
     * @param packageName The base package
     * @return The classes
     * @throws ClassNotFoundException
     * @throws IOException
     */
    private static Class[] getClasses(String packageName)  throws ClassNotFoundException, IOException {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        System.out.println("<URL> resources: "+resources);
        while (resources.hasMoreElements()) {
            URL resource = new URL( resources.nextElement().toString().replace("%20", " "));
            System.out.println("URL Resource: "+resources);
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class> classes = new ArrayList<Class>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        System.out.println("<Class> classes: "+resources);
        return classes.toArray(new Class[classes.size()]);
    }

    /**
     * Recursive method used to find all classes in a given directory and subdirs.
     *
     * @param directory   The base directory
     * @param packageName The package name for classes found inside the base directory
     * @return The classes
     * @throws ClassNotFoundException
     */
    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }

    public boolean CreateXML(Map map) throws InterruptedException{
        boolean bool=false;
        try {
            File file = new File(".\\MethodsList.xml");
            if(file.exists()){
                file.delete();
                Thread.sleep(2000);
            }
            Set<String> keys=map.keySet();
            List<String>methodsName=new ArrayList();
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("TestMethodsList");
            doc.appendChild(rootElement);
            for(String key:keys){
                //              System.out.println(key);
                // classname elements
                Element ClassName = doc.createElement(key);
                rootElement.appendChild(ClassName);
                methodsName=((CreateMethodsList) map.get(key)).getMehodsList();
                String path=((CreateMethodsList) map.get(key)).getClassPath();
                Element classPath = doc.createElement("classPath");
                classPath.appendChild(doc.createTextNode(path));
                ClassName.appendChild(classPath);
                for(String str:methodsName){
                    // methodName elements
                    Element methodName = doc.createElement("methodName");
                    methodName.appendChild(doc.createTextNode(str));
                    ClassName.appendChild(methodName);
                }
            }

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            String filePath=".\\MethodsList.xml";
            StreamResult result = new StreamResult(new File(filePath).toString().replace("%20", " "));
            //StreamResult result =  new StreamResult(System.out);
            transformer.transform(source, result);
            if(new File(".\\MethodsList.xml").exists()){
                bool=true;
            }
            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

        } catch (ParserConfigurationException pce) {
            bool=false;
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            bool=false;
            tfe.printStackTrace();
        }
        return bool;
    }

    public static void main(String arg[]) throws ClassNotFoundException, IOException, InterruptedException{
        FindTestMethodsInTestClass FTMITC=new FindTestMethodsInTestClass();
        System.out.println(FTMITC.isMethodsListXMLReady());
    }
}

I would appreciate if you could provide me your inputs.

eckes
  • 10,103
  • 1
  • 59
  • 71
Karim Narsindani
  • 434
  • 3
  • 14
  • 38
  • Try classLoader.getResourceAsStreamThe instead of classLoader.getResources .first uses the classloader to find the file which could be in a jar file, on a server (via URL) or on a local disk. The second only looks on the local disk. – M Sach Jan 05 '15 at 08:29
  • Do you want to list the files inside the Jar file or on the file system? – SubOptimal Jan 05 '15 at 08:51
  • possible duplicate of [How can I get a resource "Folder" from inside my jar File?](http://stackoverflow.com/questions/11012819/how-can-i-get-a-resource-folder-from-inside-my-jar-file) – Joe Jan 05 '15 at 08:53
  • We do not need the class files available in jar, but we need to read class file available outside the jar file, like projectTest has executable jar, and scr package. So when ever we run jar file, it will look into scr package and get available class from src.com.test package and subpackage of test – Karim Narsindani Jan 05 '15 at 09:08
  • Can you print some of the value to debug your code, so that you will get to know till what point your code in jar is working fine. – Naman Gala Jan 05 '15 at 10:52
  • I have updated complete code of class – Karim Narsindani Jan 05 '15 at 10:59
  • holy cow, thats a lot of code. – eckes Jan 05 '15 at 11:26
  • can anyone help me in this...? – Karim Narsindani Jan 05 '15 at 12:40

0 Answers0