The resource files are not found when creating jar - java

I have a file called command.xml, when I work with NetBeans everything works fine.
But when I create the jar file I have an exception that the file is not found.
Example I have replaced this assignment:
String commandPath = "command.xml";
with this:
String commandPath = getClass().getResources("command.xml").getPath();
but it does not work.

I supose that "command.xml" right now is in your project folder (same level where src/ is). To use the resource loading you should move the file in the same folder where the class of the object is that invokes getClass().
Consider you have this class
package my.package
public class Test {
public Test() {
String commandPath=getClass().getResources("command.xml").getPath();
}
}
command.xml should be in
src/my/package/

Related

A class from external jar throws exception while loading Resource

Hi I am working on a Maven project having dependency on a external jar which has a class ConfigLoader having following loader() method.
public class ConfigLoader {
public void initialize() {
loader();
}
private static void loader() {
URL configURL = ConfigLoader.getClass().getResource("runtimeConfiguration.xml");
//some other method calls to which configURL is an argument.
}
//other methods of ConfigLoader class
}
and the directory structure is like this -
src
|...main
|.......java
|.......resources
|................dev
|................prod
both dev and prod have a file named runtimeConfiguration.xml
and the code which uses this class is
public class Application {
private Application application;
public static void main(String []args){
application = new Application();
application.invokeConfigLoader();
//additional code
}
private void invokeConfigLoader() {
configLoader.initialize();
}
}
The error I get is
could not find: runtimeConfiguration.xml
and the exception is thrown at the getResource() line in the class from jar.
I have tried adding the dev folder to classpath but still the same error. I want to run this code from linux terminal, and the command I am giving from trunk directory (where all my exernal jars and resource folder sits after maven build) is -
java -cp /resources/dev/*:configuration-loader.jar
I am using intelliJ 2017.2 and also tried to add the resources/dev folder as module dependency, but I keep on getting the same error. The resources folder is added as a library via project structure settings. I tried to search a lot but have not found any question with this issue. Kindly help me out as I am new to this environment based development.
Thanks!
ConfigLoader.getClass().getResource("runtimeConfiguration.xml"); will try to get runtimeConfiguration.xml from the same package a the ConfigLoader is defined and not from the root of classpath. Try appending / to runtimeConfiguration.xml.
This should work ConfigLoader.getClass().getResource("/runtimeConfiguration.xml"); or ConfigLoader.getClass().getResource("/dev/runtimeConfiguration.xml"); depending how you are adding resources to your classpath.
See javadoc for more.

How to read file from src/main/resources relative in a JUnit test?

I have a junit testcase and a file that I want to load during that test. The file is placed under src/main/resources, whereas the packages are named same as the java testfile:
src/test/java/my/path/to/FileTest.java
src/test/resource/my/path/to/test.txt
Usage:
public class FileTest {
#Test
public void testRead() {
String content = IOUtils.toString(this.getClass().getResourceAsStream("test.txt"), Charset.defaultCharset());
System.out.println(content);
}
}
Exception when running the testcase in IDE:
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:113)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:2272)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:1041)
What might be wrong here?
I ended placing the testfiles directly into /src/main/resources without subpackage, and using.
PropertiesLoaderUtils.loadProperties(new ClassPathResource(filename));

How to keep a jar file external but still use its classes in my Android project?

I need to have a jar file located in a main/assets directory within an Android project. It is important the jar file is located there.
With my main Android project is there a way to reference this jar file in my code and to use its classes?
To be clear I don't want to add the jar to the main project once compiled.
EDIT: I have tried the link below and it seems to load the Class file I've stated. But I'm strugging how to define constructor arguments for the dynamically loaded Class.
android-custom-class-loading-sample
EDIT2
Nearly there. I've confirmed the class is loaded from my classes.jar. I'm stuck instantiating it though.
On the licenseValidatorClazz.getConstructor line I get the error below. I'm guessing I'm missing something from my Interface file?
java.lang.NoSuchMethodException: [interface com.google.android.vending.licensing.Policy, interface com.google.android.vending.licensing.DeviceLimiter, interface com.google.android.vending.licensing.LicenseCheckerCallback, int, class java.lang.String, class java.lang.String]
public Class licenseValidatorClazz = null;
public LicenseValidator validator;
...
// Initialize the class loader with the secondary dex file.
DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(),
null,
mContext.getClassLoader());
try {
// Load the library class from the class loader.
licenseValidatorClazz = cl.loadClass("com.google.android.vending.licensing.LicenseValidator");
validator = (LicenseValidator) licenseValidatorClazz.getConstructor(Policy.class,DeviceLimiter.class,LicenseCheckerCallback.class,int.class,String.class,String.class).newInstance(ddd, new NullDeviceLimiter(),
callback, generateNonce(), mPackageName, mVersionCode);
} catch (Exception exception) {
// Handle exception gracefully here.
exception.printStackTrace();
}
I have an Interface which contains the functions to pass to the loaded class.
public interface LicenseValidator
{
public LicenseCheckerCallback getCallback();
public int getNonce();
public String getPackageName();
public void verify(PublicKey publicKey, int responseCode, String signedData, String signature);
public void handleResponse(int response, ResponseData rawData);
public void handleApplicationError(int code);
public void handleInvalidResponse();
}
TO use an external jar to be associated with your application and use it during runtime, it needs to be in dalvik format since normal jars cannot work under dalvikVM.
Convert your files using the dx tool
using aapt cmd , add those classes.dex to your jar file.
Now this jar which contains files in dalvik format can be loaded into our project.
Here is a post which explains the procedure to accomplish it.
There are steps to accomplish this.
You have to make a copy of your JAR file into the private internal storage of your aplication.
Using the dx tool inside the android folder, you have to generate a classes.dex file associated with the JAR file. The dx tool will be at the location /android-sdks/build-tools/19.0.1 (this file is needed by the Dalvik VM, simply jar can not be read by the dalvik VM))
Using the aapt tool command which is also inside the same location, you have to add the classes.dex to the JAR file.
This JAR file could be loaded dynamically using DexClassLoader.
If you are making a JAR from any one your own library, you have to do this steps (1-4) every time when there is a change in your library source code. So you can automate this steps by creating a shell script(in Mac/Linux/Ubuntu) or batch scripts(in Windows). You can refere this link to understand how to write shell scripts.
Note : One situation for implementing this method is, when it is impossible to add the JAR files directly to the build path of core project and need to be loaded dynamically at run time. In normal cases the JAR files could be added to the build path.
please check this link for the detailed code and implementation.
How to load a jar file at runtime
Android: How to dynamically load classes from a JAR file?
Hope this helps!!
You should try out the Services API - java.util.ServiceLoader
You define a service interface and its implementations in your jar.
package com.my.project;
public interface MyService { ... }
public class MyServiceBarImpl implements MyService { ... }
public class MyServiceFooImpl implements MyService { ... }
Then you define the services contained within the jar file in the META-INF/services/ directory. For instance, in the file 'META-INF/services/com.my.project.MyService', you list the provider classes.
# Known MyService providers.
com.my.project.MyServiceBarImpl # The original implementation for handling "bar"s.
com.my.project.MyServiceFooImpl # A later implementation for "foo"s.
Then, in your main codebase, you can instantiate a MyService instance with the ServiceLoader:
for (MyService service : ServiceLoader.load(MyService.class)) {
//Perform some test to determine which is the right MyServiceImpl
//and then do something with the MyService instance
}
These examples are taken more-or-less straight from the API, although I've changed the package names to make them slightly less annoying to read.

Classloader and loading a class whose location does not equal its package

I'd like to be able to load a class(es) from a known directory whenever a compiled .class file appears in that particular directory. However the I'd like the .class to be loaded regardless of what the package decleration is in its .java file. For example I have this class which I wish to load:
package com.javaloading.test;
public class SomeClassInPackage {
private String name = "The name of this Class is SomeClass.";
public String getName(){
return name;
}
}
And it is in the package com.javaloading.test. I then want to load it using this class:
public class GetPackage {
public static void main(String[] args){
new GetPackage().loadMyClass();
}
public void loadMyClass(){
// Get the current class loader
ClassLoader cl = getClass().getClassLoader();
try {
Object o = cl.loadClass("SomeClassInPackage");
System.out.println("Class loaded!");
} catch (ClassNotFoundException ex){
System.out.println("Could not load class");
}
}
}
If I put the .class files of both the above Classes into the same directory and run GetPackage it results in the error
Exception in thread "main" java.lang.NoClassDefFoundError:
SomeClassInPackage (wrong name:
com/javaloading/test/SomeClassInPackage
I need to be able to load a class (from a file) regardless of it's declared package and without having to actually know its package. I would then examine the loaded class for its package information. Is this possible using the System ClassLoader or a custom ClassLoader or is it impossible without having knowledge of the package structure? If it's possible any advice is appreciated.
It is impossible to load the class without its respective package structure, means if you want to load the class then it must be placed in the folder that is correspond to its packages name or that class is in a jar file but in same folder structure.
But lets say you want to load the classes which is external means not in the class path where this program gets executed from and you want to load it in current class loader during execution. Refer to this link How to load the classes at runtime. This will also gives answer to your next question where you want to load the classes which is selected by the program based on its name or package.

Where to put a text file in Grails, and how to get the path

I need to read in a .txt file into a groovy class in order to interrogate it line by line. But I am not sure what folder I put it into in my grails app, and how to get the path to it?
So far I have tried placing it under src and also in a new folder web-app/txt
and I have tried the the following to read it in
fileIn = new File('/lexicon.txt').text
and
fileIn = new File('txt/lexicon.txt').text
to no avail.
Any body have any pointers?
Grails is a Java Web Application, so it will be compiled into a sigle file .war, with all files/classes/etc inside. Most Web containers do unpack war, but there are no any guaranteee, so it's not a good idea to use File to access this file as a file.
Btw, you can place your file into grails-app/conf, at this case it will be placed into classpath, and you'll be able to access it by using:
InputStream lexicon = this.class.classLoader.getResourceAsStream('lexicon.txt')
You could also put this file into a subdirectory, like grails-app/conf/data and load it as ***.getResourceAsStream('data/lexicon.txt')
You can put your file under web-app/
Example:
web-app/lexicon.txt
And then in your controller or service use grailsApplication:
class MyService {
def grailsApplication
public myMethod() {
File myFile = grailsApplication.mainContext.getResource("lexicon.txt").file
}
}
Hope this helps
You can use Spring's resource loading to access the file. With this method you can access the file from a Spring bean, which means Grails can autowire the resource in to its artifacts.
See below for the following steps examples
Place the file in grails-app/conf/.
Make a resource holder class in src/groovy
Add the resource holder as a Spring bean in grails-app/spring/resources.groovy
Then autowire and use the resource wherever you need it
Step 2:
package resource
import org.springframework.core.io.Resource
class ResourceHolder {
Resource lexicon
}
Step 3:
beans = {
lexiconHolder(resource.ResourceHolder) {
lexicon = 'classpath:lexicon.txt'
}
}
Step 4:
class AnyGrailsService {
def lexiconHolder
void aMethodUsingTheLexicon() {
File lexicon = lexiconHolder.lexicon.file
/* Do stuff with the lexicon */
}
In Grails 2, you can use the Grails Resource Locator
class MyService {
def grailsResourceLocator
myMethod() {
def fileIn = grailsResourceLocator.findResourceForURI('/txt/lexicon.txt').file
}
}
Handy tip: to mock this in Spock, use GroovyPageStaticResourceLoader
#TestFor(MyService)
class MyServiceSpec extends Specification {
def setup() {
service.grailsResourceLocator = Mock(GroovyPageStaticResourceLocator)
}
}

Categories

Resources