How do I load test/resources instead of main/resources? - java

[ I asked this question on 29JUL2014, but on 31JUL2014 everything just started working again, and I didn't make any changes. ]
In a Java project (in IntelliJ), I have marked:
src/main/java as Sources Root
src/test/java as Test Sources Root
src/main/resources as Resources Root
src/test/resources as Test Resources Root
I have a file: test/java/Test1.java
in which I try to load a config.properties file that's in src/test/resources, but what gets loaded is the config.properties that's in src/main/resources. I've had other projects where my test resources file loaded correctly. I'm not sure why in this project I'm not making that happen. I do have elsewhere in the project a PropertiesUtil.loadProperties static method that does this:
String filename = "config.properties";
input = PropertiesUtil.class.getClassLoader().getResourceAsStream(filename);
Is that why I'm not getting the correct config.properties file? How do I load the test config.properties?

Related

How to put resources outside of classes package tree?

I want to deploy (create myapp.jar and from this .jar create myapp.exe file for installer) a java swing application.
I have a some packages:
resource package (net.myapp.ui.resource) inside i have .png, .wav, ... files)
output report package (net.myapp.ui.jasper.output.report) inside i have exported files (report1.pdf, report2.pdf, etc.)
config package (ne.myapp.ui.config) which contain config.properties file which can by updated after app have been installed because this file contain **persistence.xml** properties to create an EntityManagerFactory dynamically depending on the database server info.
From NetBeans IDE i can run app and it's work without problem; but when I build app, a .jar file is created: in dist directory i only have :
--> myapp.jar
--> lib folder
So i'm unable to access config.properties to setup database server IP and other parameters to be used in persistence.xml at runtime.
The question is : How do not put resources, output report, config ... in the classes package tree, but outside and access every resource from code using getResources() or getResourceAsStream() or ClassLoader ?
I want this strucure (after netbeans project build):
dist (folder)
/myApp.jar
/lib/lots-of-jar’s
/config/config.properties
/resources/my_cat.jpg
/output/report/report1.pdf, ...
....
Thank you for your help.

Files cannot be found when relative to property file in Java/Gradle

My Java project uses Gradle. I'd like to include a configuration folder conf when distributing the application with the task distZip.
This is an excerpt from my current project structure.
src
|-- dist
|-- conf
|-- application.properties
|-- keystore.jks
|-- truststore.jks
The conf folder is successfully distributed.
In my main() I load the properties with new File("src/dist/conf/application.properties") which works fine.
The application.properties contains two properties:
keystore.location = ./keystore.jks
truststore.location = ./truststore.jks
When starting the application from IntelliJ it works finde but when starting the distribution it cannot find the keystore.jks and truststore.jks because src/dist/conf does not exist but only conf.
How can I make sure that these files are found?
Your src/dist/conf folder is no resource folder for the java gradle plugin (and IntelliJ). It is just picked up by the application plugin (distZip task). IntelliJ sets the execution directory to the root path of the project. So it is just a coincidence that the src/dist/conf/application.properties can be read.
Move the files in from conf/dist folder to src/main/resources and they will be found by the processResources task and this folder should also be recognized by IntelliJ as a resource folder. Your classpath will have the resource node as root, so that you can use an absolute classpath to get to your files. (straight-forward sample: new File(YourClass.class.getResource("/dist/application.properties").getFile()))
I think that it will take much more effort to read the files in the conf/dist folders, because they are not part of the classpath.

Filepath in war

I created sigleton ApplicationConfig for settigs, that reads xml config file. But every time it fails on path to file.
hierarchy:
META-INF
src
--application
----config.xml
--engine
----ApplicationConfig
web
--WEB-INF
----web.xml
I've tried File f = new File("../application/config.xml"); but it gives C:\WebLogic\application\config.xml
It's usually a bad idea to store your configs in 'src'. It's better to separate your code and configuration. I suggest you to read about maven (or gradle).
Basic maven app has pretty simple structure:
src
--main
----java
----resources
where in 'java' folder you store your code, and in the 'resource' folder you store your configs. And now you have problem, because jvm is trying to find your file relatively WebLogic base folder.
And if you use maven, you could just write:
ApplicationConfig.class.getResourceAsStream("/config.xml")
Of course, in this case you should put your config into 'resources' folder.

project layout and spring-test support issues

We have project layout as below.
src
src/test/java
src/test/resources
and we cant add src/main/(java, resources) for code, because of earlier developemnt done.
src/test/java is having both unit and integration tests in same package as class under test has in src folder.
unit tests are running fine in current setup but issues are with running integration tests.
integration tests run perfectly fine when test class and configuration files are along side class under test, in src folder and same package as class.
but when i put test class in src/test/java and config files in src/test/resources test fails to run because of context initialization issues.
please note following about env setup
1 build output folder for all the src , src/test/java and src/test/resources is src folder only.
2 i am using classpath*: to specify config location, as otherwise spring fails to locate config file in resource folder.
#ContextConfiguration(locations={"classpath*:applicationContext_getCorpAcctPrefDetailsSP.xml"})
3 tried both #Autowired and setter based DI for test classes
> (i). in case of #Autowired i get error for depedency saying
No unique bean of type GetCorpAccountPreferencesDetailsSP is defined expected at least 1 matching bean
also i am using base package scan
> (ii). in case of Setter based DI context get initialized and unit test run but all the dependencies injected are null in test class.
please expalin what can be reason for issue and any solution.
As everything is working fine when integration tests are in src folder alongside class under test.
i suspect differect source folders (src and test)creating issue when spring create context as class under test is not in same source folder as test.
thanks
nBhati
At run-time Spring doesn't care (or know) which folder your original source code is in. All that matters is the classpath - which compiled files and which resource folders are being put on the classpath. If you are getting errors about XML files that cannot be found when you run your tests, that strongly suggests that those XML files are not on the classpath when the tests run.

Where should I put the log4j.properties file?

I wrote a web service project using netbeans 6.7.1 with glassfish v2.1, put log4j.properties to the root dir of project and use:
static Logger logger = Logger.getLogger(MyClass.class);
in Constructor:
PropertyConfigurator.configure("log4j.properties");
and in functions:
logger.info("...");
logger.error("...");
// ...
but, it is error info(actually, I have tried to put it almost every dir that I could realize):
log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:297)
at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:315)
at com.corp.ors.demo.OrsDemo.main(OrisDemo.java:228)
log4j:ERROR Ignoring configuration file [log4j.properties].
log4j:WARN No appenders could be found for logger (com.corp.ors.demo.OrsDemo).
log4j:WARN Please initialize the log4j system properly.
the example project could be get from http://www.91files.com/?N3F0QGQPWMDGPBRN0QA8
I know it's a bit late to answer this question, and maybe you already found the solution, but I'm posting the solution I found (after I googled a lot) so it may help a little:
Put log4j.properties under WEB-INF\classes of the project as mentioned previously in this thread.
Put log4j-xx.jar under WEB-INF\lib
Test if log4j was loaded: add -Dlog4j.debug # the end of your java options of tomcat
Hope this will help.
rgds
As already stated, log4j.properties should be in a directory included in the classpath, I want to add that in a mavenized project a good place can be src/main/resources/log4j.properties
You can specify config file location with VM argument -Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"
You have to put it in the root directory, that corresponds to your execution context.
Example:
MyProject
src
MyClass.java
log4j.properties
If you start executing from a different project, you need to have that file in the project used for starting the execution. For example, if a different project holds some JUnit tests, it needs to have also its log4j.properties file.
I suggest using log4j.xml instead of the log4j.properties. You have more options, get assistance from your IDE and so on...
For a Maven Based Project keep your log4j.properties in src/main/resources. Nothing else to do!
If you put log4j.properties inside src, you don't need to use the statement -
PropertyConfigurator.configure("log4j.properties");
It will be taken automatically as the properties file is in the classpath.
Try:
PropertyConfigurator.configure(getClass().getResource("/controlador/log4j.properties"));
The file should be located in the WEB-INF/classes directory.
This directory structure should be packaged within the war file.
My IDE is NetBeans. I put log4j.property file as shown in the pictures
Root
Web
WEB-INF
To use this property file you should to write this code:
package example;
import java.io.File;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import javax.servlet.*;
public class test {
public static ServletContext context;
static Logger log = Logger.getLogger("example/test");
public test() {
String homeDir = context.getRealPath("/");
File propertiesFile = new File(homeDir, "WEB-INF/log4j.properties");
PropertyConfigurator.configure(propertiesFile.toString());
log.info("This is a test");
}
}
You can define static ServletContext context from another JSP file.
Example:
test.context = getServletContext();
test sample = new test();
Now you can use log4j.property file in your projects.
A few technically correct specific answers already provided but in general, it can be anywhere on the runtime classpath, i.e. wherever classes are sought by the JVM.
This could be the /src dir in Eclipse or the WEB-INF/classes directory in your deployed app, but it's best to be aware of the classpath concept and why the file is placed in it, don't just treat WEB-INF/classes as a "magic" directory.
I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.
I found that Glassfish by default is looking at [Glassfish install location]\glassfish\domains[your domain]\ as the default working directory... you can drop the log4j.properties file in this location and initialize it in your code using PropertyConfigurator as previously mentioned...
Properties props = System.getProperties();
System.out.println("Current working directory is " + props.getProperty("user.dir"));
PropertyConfigurator.configure("log4j.properties");
Your standard project setup will have a project structure something like:
src/main/java
src/main/resources
You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist
I don't know this is correct way.But it solved my problem.
put log4j.properties file in "project folder"/config and use PropertyConfigurator.configure("config//log4j.properties");
it will works with IDE but not when run the jar file yourself.
when you run the jar file by yourself just copy the log4j.properties file in to the folder that jar file is in.when the jar and property file in same directory it runs well.
Put log4j.properties in classpath.
Here is the 2 cases that will help you to identify the proper location-
1. For web application the classpath is /WEB-INF/classes.
\WEB-INF
classes\
log4j.properties
To test from main / unit test the classpath is source directory
\Project\
src\
log4j.properties
There are many ways to do it:
Way1: If you are trying in maven project without Using PropertyConfigurator
First:
check for resources directory at scr/main
if available,
then: create a .properties file and add all configuration details.
else
then: create a directory named resources and a file with .properties
write your configuration code/details.
follows the screenshot:
Way2: If you are trying with Properties file for java/maven project Use PropertyConfigurator
Place properties file anywhere in project and give the correct path.
say: src/javaLog4jProperties/log4j.properties
static{
PropertyConfigurator.configure("src/javaLog4jProperties/log4j.properties");
}
Way3: If you are trying with xml on java/maven project Use DOMConfigurator
Place properties file anywhere in project and give correct path.
say: src/javaLog4jProperties/log4j.xml
static{
DOMConfigurator.configure("src/javaLog4jProperties/log4j.xml");
}
For me, it worked when I put the file inside the resources folder.
Also, it was a war file for my project. My recommendation is to ensure that the name of the file is log4j.properties, as my project didn't recognize "log4j2.properties"
Actually, I've just experienced this problem in a stardard Java project structure as follows:
\myproject
\src
\libs
\res\log4j.properties
In Eclipse I need to add the res folder to build path, however, in Intellij, I need to mark the res folder as resouces as the linked screenshot shows: right click on the res folder and mark as resources.
You don't need to specify PropertyConfigurator.configure("log4j.properties"); in your Log4J class, If you have already defined the log4j.properties in your project structure.
In case of Web Dynamic Project: -
You need to save your log4j.properties under WebContent -> WEB-INF -> log4j.properties
I hope this may help you.
Open spark-shell
Then type System.getenv("SPARK_CONF_DIR")
That will print where your log4j.properties should go.

Categories

Resources