package main;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @author ssoul
*
*/
public class BWImportFinder {
public static final String Import_Not_Found = "No such Class found!";
private static final String _sSystemLibraries = System.getProperty("sun.boot.class.path");
private static final String _sUserLibraries = System.getProperty("java.class.path");
private static ArrayList<String> _Jars;
private BWImportFinder() {
}
/**
* Search through available Packages the given Classname.
*
* @param cClassname
* @return Import Tag for given Classname.
*/
public static String searchImport(String cClassname) {
getAllJars();
try {
String sTemp;
for (String s : _Jars) {
if (s.endsWith(".jar")) {
File f = new File(s);
if (f.exists()) {
JarFile temp = new JarFile(f);
sTemp = searchClass(temp, cClassname);
if (!sTemp.equals(Import_Not_Found)) {
return sTemp;
} else {
continue;
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
return Import_Not_Found;
}
return Import_Not_Found;
}
private static void getAllJars() {
List<String> tempfiles;
_Jars = new ArrayList<String>();
try {
// Get UserLibraries
tempfiles = Arrays.asList(_sUserLibraries.split(";"));
for (String s : tempfiles) {
if (s.endsWith(".jar")) {
_Jars.add(s);
}
}
} catch (Exception ex1) {
ex1.printStackTrace();
System.out.println("Couldnt load Userlibraries!");
}
try {
// Get SystemLibraries
tempfiles = Arrays.asList(_sSystemLibraries.split(";"));
for (String s : tempfiles) {
if (s.endsWith(".jar")) {
_Jars.add(s);
}
}
} catch (Exception ex2) {
ex2.printStackTrace();
System.out.println("Couldnt load Systemlibraries");
}
}
private static String searchClass(JarFile Jar, String sClass) {
String temp;
Enumeration<JarEntry> e = Jar.entries();
while (e.hasMoreElements()) {
String s = e.nextElement().toString();
if (s.endsWith(".class")) {
temp = s;
if (temp.contains("$")) {
temp = temp.substring(0, temp.indexOf("$"));
} else {
temp = temp.substring(0, temp.lastIndexOf("."));
}
String stemp = temp.substring(temp.lastIndexOf("/") + 1);
if (stemp.equals(sClass)) {
return "import " + temp.replace("/", ".") + ";";
}
}
}
return Import_Not_Found;
}
}