read class names from a jar file in eclipse plug-in - java

I need to read class names(just the simple name) from a jar file(OSGified). I've placed the jar file in the lib folder and it's added to class path. Here is the code I've written:
public void loadClassName() throws IOException {
JarFile jf = new JarFile("/lib/xxxx-1.0.0.jar");
List<String> list = new ArrayList<String>();
for (JarEntry entry : Collections.list(jf.entries())) {
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replace("/", ".").replace(".class", "");
list.add(className);
}
}
}
Somehow, I"m getting Filenotfound exception while constructing the jarfile object. Can somebody let me know how we should give the jar path to the JarFile constructor ?

try this:
JarFile jf = new JarFile("lib/xxxx-1.0.0.jar");

Thanks to the user #Perception. His answer has worked flawlessly.
This is the working code:
final InputStream jarStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lib/xxxxx-1.0.0.jar");
JarInputStream jfs = new JarInputStream(jarStream);
List<String> list = new ArrayList<String>();
JarEntry je = null;
while (true) {
je = jfs.getNextJarEntry();
if (je == null) {
break;
}
if (je.getName().endsWith(".class")) {
String className = je.getName().replace("/", ".").replace(".class", "");
list.add(className);
}
}

Related

Eclipse get linked resource path for file loading

In my Eclipse project I have a "src" folder that's linked from a one drive folder.
I have some other text files in the linked folder that I want to load with a FileReader.
How would I get this location, optimally in a way that's agnostic to whether the folder is linked or actually in the project folder. I've tried using
MyClass.class.getResource("");
But it returns me a path to the "bin" folder. I'm probably not using it right. The file I want to get is "src/de/lauch/engine/shaders/primitiveTestShader/vertexShader.vsh"
Thanks in advance!
You can create resources folder like that 'src\main\resources' and put the file after that you can run your same code . hopefully it will work.
I solved my particular issue for now but im still open to better solutions :)
public class LinkedResourceLocator {
private static Dictionary<String,String> locations;
public static String getPath(String path) {
if(locations==null) {
File projectLocal = new File(LinkedResourceLocator.class.getClassLoader().getResource("").getPath().replaceAll("%20", " ")).getParentFile();
File dotProject = new File(projectLocal.getAbsolutePath()+"\\.project");
locations = new Hashtable<String,String>();
File[] files = projectLocal.listFiles(new FileFilter(){
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (int i = 0; i < files.length; i++) {
locations.put(files[i].getName(), files[i].getAbsolutePath());
}
try {
BufferedReader br = new BufferedReader(new FileReader(dotProject));
StringBuilder fileContentBuilder = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
fileContentBuilder.append(line.trim());
}
String fileContents = fileContentBuilder.toString();
Pattern p = Pattern.compile("<link><name>(\\w*)</name><type>\\d*</type><location>([\\w/:]*)</location></link>");
Matcher m = p.matcher(fileContents);
while(m.find()) {
locations.put(m.group(1),m.group(2));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("Can't locate .project file");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Can't read .project file");
}
}
String locator = path.contains("/")?path.substring(0, path.indexOf("/")):path;
String restPath = path.substring(locator.length());
return locations.get(locator)+restPath;
}
}
This class gets the linked resource locations from the eclipse .project file and then converts project local paths like "src/de/lauch/engine/shaders/primitiveTestShader/vertexShader.vsh" to these linked locations.

Relative path to image folder java spring

I have a problem with a relative path to an image folder.
I want to list the images into a folder to add their urls to a list and show them in a jsp.
The code is this:
File carpetaImagenes = new File("../../../../../webapp/resources/img/maquinas/"+seleccion);
List<String> listaUrlImagenes = new ArrayList<String>();
/** Recorremos el directorio de imagenes de la maquina */
for(File imagen : carpetaImagenes.listFiles()){
String imageFileName = imagen.getName();
listaUrlImagenes.add(imageFileName);
}
The result of "carpetaImagenes.listFiles()" is always null. I suppose the path is bad.
Here you can see the image of the folder tree. The class is into "controlador" folder and the images are into "webbapp/resources/img/maquinas/1"
I haeve tried several paths with no luck.
Thank you very much.
User following method getImageList and it should work
relativeFilePath = "img/maquinas/"+seleccion;
This is a relative path from classpath. I assume ../../../../../webapp/resources is your actual folder where everyrthing is deployed .
private List getImageList(String relativeFilePath) {
List<String> listaUrlImagenes = new ArrayList<String>();
try {
InputStream in = getResourceAsStream(relativeFilePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String resource;
while ((resource = br.readLine()) != null) {
listaUrlImagenes.add(resource);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listaUrlImagenes;
}
private InputStream getResourceAsStream(String resource) {
final InputStream in = ClassLoader cl = this.getClass().getClassLoader().getResourceAsStream(
resource);
return in == null ? getClass().getResourceAsStream(resource) : in;
}
And in spring following should work.
ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
cl);
Resource[] resources = resolver.getResources("classpath:/img/maquinas/"+seleccion);// or *.png
for (Resource resource : resources) {
listaUrlImagenes.add(resource.getFilename());
}
Finally working!!
File carpetaImagenes = new ClassPathResource("imagenes/maquinas/"+seleccion).getFile();
File[] listaImagenes = carpetaImagenes.listFiles();

Retrieve the value of fields in a class loaded from a jar

I have to retrieve the value of all fields in a class loaded from a jar.
So I need an instance to do that :
field.get(gameClassInstance);
for each field.
Here the code that load the class and try to create an instance :
private Loader() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
File jarFile = new File(System.getProperty("user.dir")+File.separator+"games"+File.separator+gameName+".jar");
// Create the URLClassLoader
URL url = jarFile.toURI().toURL();
URL[] urls = new URL[]{url};
URLClassLoader cl = new URLClassLoader(urls);
// Search the class
JarFile jar = new JarFile(jarFile.toString());
Enumeration<JarEntry> e = jar.entries();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
if (je.getName().contains(gameName)){
String className = je.getName().substring(0,je.getName().length()-6); // Remove ".class"
className = className.replace('/', '.');
gameClass = cl.loadClass(className);
gameClassInstance = gameClass.newInstance(); // Create an instance of the class
}
}
jar.close();
cl.close();
}
Here the loaded class :
public class Solitaire {
public Board board = new Board("Board1", "");
public Layout layout = new Layout();
public Player player = new Player();
public Solitaire() {
}
}
There is a StackOverflowError at the line where I create an instance.
I found the solution to my problem, I just make the fields static and retrieve them with field.get(null)

return class names not working in Jar

I have used this code to get a list of class names from a package:
private List<String> getClasses()
{
List<String> classes = new ArrayList<String>();
String packageName = "algorithm/impl";
URL directoryUrl = Thread.currentThread().getContextClassLoader().
getResource(packageName);
File directory = new File(directoryUrl.getFile());
if(directory.exists())
{
String [] files = directory.list();
for(String filename : files)
{
classes.add(filename.substring(0, filename.lastIndexOf(".")));
}
}
return classes;
}
but this does not work when the app is packaged as an executable jar file. Why?
You can make use of this class JarFile.
JarFile file = new JarFile("YourFileName.jar");
for (Enumeration<JarEntry> enum = file.entries(); enum.hasMoreElements();) {
JarEntry entry = enum.next();
System.out.println(entry.getName());
}
Or if you want to search for particular class inside your jar you can use ZipFile class.
JarFile jar = new JarFile(YourJarFile);
ZipEntry e = jar.getEntry(CLASS_FILE_TO_FIND);
if (e == null) {
e = jar.getJarEntry(CLASS_FILE_TO_FIND);
if (e != null) {
foundIn.add(f.getPath());
}
} else {
foundIn.add(f.getPath());
}

Java Run TestClass from another Jar

I have a program that will start other JUnit test from a program. I will first tell you what it does:
1. Searching for the programma that are in the folder
2. Find the jar en searching through it for the test classes
Now I want to run that test class, but when I'm starts the class with this I get an error that he couldn't find the class:
for (String testclass: arrayList){
Class cl = Class.forName(testclass);
Logger.error(TestEnablerViewtool.class, "CL NAME : " + cl.getName());
JUnitTest test = new JUnitTest(cl.getName());
test.setTodir(new File(pathToReports));
task.addTest(test);
task.execute();
}
And I find the class with this piece of code:
public static List<String> getClasseNamesInPackage(String jarName, String packageName){
String s = "C:\\CMS\\CMS\\WEB-INF\\lib\\plugin-Login.jar";
jarName = "Login";
packageName = "test/" + jarName + "/deploy";
ArrayList<String> arrayList = new ArrayList<String> ();
packageName = packageName.replaceAll("\\." , "/");
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(s));
JarEntry jarEntry;
while(true) {
jarEntry=jarFile.getNextJarEntry();
if(jarEntry.getName() == null) {
break;
}
if((jarEntry.getName().startsWith (packageName)) &&
(jarEntry.getName().endsWith (".class")) ) {
arrayList.add(jarEntry.getName().replaceAll("/", "\\."));
}
}
}
catch( Exception e){
e.printStackTrace ();
}
return arrayList;
}
I hope the question is clear..

Categories