I am trying to load jsoup using JavaLoader but I am getting an initiation error:
<cfscript>
// An Array with absolute file paths of the referred jar files.
paths = expandPath("jars/jsoup-1.7.3.jar");
//Creating a java loader object by passing in the array containing the file paths -
loaderObj =createObject("component","javaloader.JavaLoader").init([expandPath('jars/jsoup-1.7.3.jar')]);
//So now, we can simply create a instance of an object from the 'bmw' and 'pulsar' class.
writedump(loaderObj);
abort;
jsoup = loaderObj.create("org.jsoup.Jsoup");
</cfscript>
Object Instantiation Exception.
Class not found: org.jsoup.Jsoup
The error "Class not found" means that Javaloader could not find the requested class.
This suggests that expandPath('jars/jsoup-1.7.3.jar') is not resolving to the correct location for that file.
To see where it is looking, just dump it out:
writeDump( expandPath('jars/jsoup-1.7.3.jar') );
That will tell you where JavaLoader is being told to look, so you can then either move the existing jsoup jar file to that location, or update the path to point to where the jar file currently is.
Depending on your application, you may find it useful to setup /jars as a mapping, so you can refer to /jars/jsoup-1.7.3.jar and know that the mapping will be used to resolve the path.
Related
I'm working on an application that needs to be able to do some analysis on Java code; some through the text and some through reflection. The user should be able to input a directory and the program will pull all .java and .class files from it. I have no problem with the .java files but when I try getting the class of the .class file it doesn't work.
I've looked at using ClassLoader with URL. What I've been able to find so far has given me this
URL url = this.openFile().toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass(this.path);
return cls;
path is just a string containing the actual path of the .class file in question, e.g. Users/me/Documents/Application/out/production/MyPackage/MyClass.class. From what I understand from my own reading, this method ties me to knowing the package structure of the input, but in general I don't. All I have is the absolute path of the .class file. Is there a way, just using this path (or some simple transformation of it) that I can load into my program the actual MyClass class object and start doing reflection on it?
You have 2 options:
Use a byte code library to first read the file, so you can find out what the actual class name is.
E.g. in your example it is probably MyPackage.MyClass, but you can't know that from the fully qualified file name.
Implement your own ClassLoader subclass, and call defineClass(byte[] b, int off, int len).
Recommend using option 2.
I am taking the Coursera OOP in Java class. In the module 4 assignment, I run the code that the course provides in EarthquakeCityMap.java,
and I get an error as "The file "countries.geo.json" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.
Exception in thread "Animation Thread" java.lang.NullPointerException"
I tried to set countryFile as
"../data/countries.geo.json",
"data/countries.geo.json",
and the complete path of countries file,
but still didn't solve the problem.
//this error points to the code
private String countryFile = "countries.geo.json";
List<Feature> countries = GeoJSONReader.loadData(this, countryFile);"
//the countries file is saved in data folder.
Poject folder listing
"countries.geo.json" (unless changed in GeoJSONReader manipulates this path) will be relative to the compiled java .class files in the IntelliJ's project out folder.
If this in GeoJSONReader.loadData(this, countryFile); is a PApplet instance you can use sketchPath() to make that path relative to the folder from which the sketch runs:
List<Feature> countries = GeoJSONReader.loadData(this, this.sketchPath("data"+File.separator+countryFile));
The above snippet is based on an assumption so the syntax in your code might be slightly different, but hopefully this illustrates how you'd use sketchPath().
Additionally there's a dataPath() as well which you can test from your main PApplet in setup() as a test:
String fullJSONPath = dataPath("countries.geo.json");
println("fullJSONPath: " + fullJSONPath);//hopefully this prints the full path to the json file on your machine
println(new File(fullJSONPath).exists());//hopefully this prints true
If you specified the full path and it didn’t work, you probably forgot to escape the \ character with another backslash. The backslash character is special and needs to be doubled for windows path to be interpreted properly. For instance “c:\\users\\...”. You can also specify / instead of \ and it would work : “c:/users/...”
That said, the path resolution of a file when relative (IE not being absolute to the file system root) is relative to the working directory of the executed app. Typically, in an IDE without any special configuration, the working directory would be the root path of the project. So in order to get the relative file path resolved properly, you would have to specify the path as “data/countries.geo.json”.
You can also find out what path you are in when you run the app by doing a System.out.println(new java.io.File(“.”).getAbsolutePath()) and craft the relative path according to this folder.
When I create ImageIcon class objects I use the following code:
iconX = new ImageIcon (getClass().getResource("imageX.png"))
The above code works correctly either in an applet or a desktop app when the .png is in the same folder of the class.
The question is: how to avoid a NullPointerException when the .Png is in another folder? Or how load the image in the object ImageIcon when it is in a different location to the class?
I don't understand how this method works, if anyone can help me I appreciate it. Thanks!!
Take a look at this - Class#getResource(java.lang.String)
Please click the link above and read the docs and follow to understand what's going on.
It says -
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
and
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
So, if this object (where you call getResource) is in package /pkg1 (/ meaning pkg1 is right under the root of the classpath) and you used "imageX.png" then the result would be pkg1/imageX.png which is correct because that's where the image is located at.
But, if we moved the resource (imageX.png) to some other package /pkg2 and you called the method same way then the result would still be pkg1/imageX.png but this time it would be incorrect because the resource is actually located in /pkg2. That's when you end up with NPE.
It's good to explicitly specify the full path of the resource starting from the root of the classpath. (e.g. "/pkg/imageX.png").
Hope this helps.
Simply supply the path to the resource.
So, if you put the image in "/resources/images" within your Jar, you would simply use
iconX = new ImageIcon(getClass().getResource("/resources/images/imageX.png"))
Essentially what you're saying is, class loader, please search your class path for the following resource.
If the image is internal (you want a location relative to your project, or perhaps packaged into your jar), do what mad programmer said:
iconX = new ImageIcon(getClass().getResource("/path/imageX.png"))
The path is relative, so path/ will be a folder in the same folder as your project (or packaged into your jar).
If you want an external image, simply hand ImageIcon constructor the path (ex. "C:/.../file.png"). This isn't recommended though, as it's better to use it as a resource.
For more info on the ImageIcon constructor, see here. for more info on loading class resources, see here (Javadoc links)
My program reads in a document from a location that is not the project root directory. The doc contains a relative path. When the program applies that path, it does start from the project's root directory. How can I make it apply the path from the document's original location?
Here are the details. Kind of long, but pretty straightforward.
I have a Java project in Eclipse located at
C:\one\two\three\four\five
The program runs an XSL transform that takes a Schematron schema as input and produces a new XSLT stylesheet as output. The schema is located at
C:\one\two\three\four\five\six\S\P\schema.sch
It contains this line, and several more like it:
<sch:let name="foo" select="document('../../C/P/bar.xml')"/>
If you start from the location of the schema and apply that relative path, you end up with
C:\one\two\three\four\five\six\C\P\bar.xml
which is the correct location of bar.xml. However, when I run my program, I get a number of errors, which all seem to be similar or related to this one:
Recoverable error on line 1262
FODC0002: I/O error reported by XML parser processing
file:/C:/one/two/three/C/P/bar.xml:
C:\one\two\three\C\P\bar.xml (The system cannot find the path specified)
FODC0002 is the error code for "Error retrieving resource." That makes sense, because this is not the correct location of bar.xml. It seems that the relative path is being applied to the project's root directory. This is the relevant code:
void compileToXslt(byte[] schema) throws Exception {
XsltCompiler comp = Runtime.getSaxonProcessor().newXsltCompiler();
comp.setURIResolver(resolver);
Source source = resolver.resolve("iso_svrl_for_xslt2.xsl", null);
XsltExecutable executable = comp.compile(source);
XsltTransformer transformer = executable.load();
transformer.setSource(new StreamSource(new ByteArrayInputStream(schema)));
Serializer serializer = new Serializer();
serializer.setOutputStream(new ByteArrayOutputStream());
transformer.setDestination(serializer);
transformer.transform(); // Errors appear in logs during this line
// ...
Source is javax.xml.transform.Source. The XSL-related classes are all from SAXON (Javadoc).
What can I do to fix this? Moving bar.xml to the location where the program is looking for it, and editing style.xsl, are not options for me, because both files belong to a third-party library.
UPDATE:
Further research has led me to believe that I need to set the system ID of the StreamSource. I tried replacing the transformer.setSource(... line with this:
StreamSource strSrc = new StreamSource(new ByteArrayInputStream(schema));
strSrc.setSystemId(new
File("C:\\one\\two\\three\\four\\five\\six\\S\\P\\schema.sch").toURI()
.toURL().toExternalForm());
transformer.setSource(strSrc);
but I'm getting the same results. Am I using setSystemId() incorrectly? Am I going down the wrong path entirely?
I don't have java installed but I would assume you you need to change resolver, to find the path you are looking for.
You don't show how you get it. Of course you can do the quick and dirty and just change the working directory in your debug configurations under the arguments tab. But I assume you don't want to do that
I need to get a resource image file in a java project. What I'm doing is:
URL url = TestGameTable.class.getClass().
getClassLoader().getResource("unibo.lsb.res/dice.jpg");
The directory structure is the following:
unibo/
lsb/
res/
dice.jpg
test/
..../ /* other packages */
The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue.
Any hint?
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
leading slash to denote the root of the classpath
slashes instead of dots in the path
you can call getResource() directly on the class.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
if you are calling from static method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located