Loading context from within a Jar - java

I need some clarification; I have a jar that I built and inside of the jar it has a custom application-context.xml file that I need to load. I load the file within a class inside of the jar. When I am setting the url of this application-context.xml, is the directory specific to my jar's classpath, or still the project that is using the jar-'s classpath?
For example --
Jar's classpath:
src > main > META-INF > application-custom-context.xml
Project's classpath:
src > Libraries > myjar.jar > src > main > META-INF > application-custom-context.xml
I know these url's aren't accurate :P -- But, inside of my context creation, which directory structure would I follow. This is all theoretical. Somebody asked me this today, and I have no clue how to answer it. I would think that if you call a class from a jar, the classpath should be relative to the contents of that jar.. But, what I think is far from always right :)

The "path" to the Spring context is relative to the classpath. If the jar is included in your classpath (it's in web-inf/lib for example), then it would be treated just as if it was in your project (web-inf/classes).
In other words, if your context file is in "META-INF\spring\context.xml" inside your jar file, anyone who includes your jar file can reference it in the same manner.

Related

Load config file from a war

I have a Maven project that I'm trying to package as both a war and a jar. As part of my application / servlet initialisation (depending on whether I'm running the jar or the war), I need to read a file called server.ini. I've put the file in src/main/resources/server.ini and am trying to load it like so:
System.class.getResourceAsStream("server.ini");
However, this always results in null. What am I doing wrong?
The server.ini file should be in the root of a resources directory.
By placing it in the webapp you're making the file available via http, but you need it accessible on the classpath, which means that you should place it in the resources directory.
There's a good chance web.xml or context.xml is better suited to what you're trying to do, but...
Try putting server.ini in WEB-INF/classes, or do something like this.
The issue was that I was using the System classloader with an unqualified path, so it was expecting to find my server.ini in the java.lang package.
Since my file is in src/main/resources, I should just use the classloader of my current class, with an absolute path:
getClass().getResourceAsStream("/server.ini")
This works in both the war and the jar.
The "Preferred way of loading resources in Java" question has a great explanation of resource loading.

Where to place config files in JARs?

My JAR currently has the following structure:
myapp.jar
META-INF
MANIFEST.MF
net
myapp
MyAppDriver.class (fully qualified as net.myapp.MyAppDriver)
<lots of other classes>
My app requires the need to read a file from the runtime classpath, and configure itself based on the contents of the file (simplelogger.properties from the SLF4J framework).
Where do I place simplelogger.properties in the JAR? Do I need to set anything inside MANFIEST.MF as well?
Thanks in advance!
You can place the file in any JAR anywhere you would like. If you want it to live alongside MyAppDriver.class, for example, you could then call getClassLoader().getResourceAsStream("net/myapp/simplelogger.properties") to get an InputStream to that file. You don't need a manifest for this to work.

Read specific resource from classpath

I have a maven project and in class-path (resources folder according to maven standard layout) I have several log4j.xml files, like this:
-resources
-log4j.xml
-folder1
-log4j.xml
-folder2
-log4j.xml
How I can read log4j.xml located at root? I think the following code doesn't guarantee that I will get log4j.xml from root:
Thread.currentThread().getContextClassLoader().getResourceAsStream("log4j.xml")
Unless some other jar file is in the classpath of the current thread(s classloader, before yours, and also contains a log4j.xml file at the root, your code will do what you expect it to do.
To get the other one you would use "folder1/log4j.xml" as path.

Can't find bundle for base name /Bundle, locale en_US

I'm using a library that has a dependency on JSF.
When I try to run my project, it show following exception massage..
java.util.MissingResourceException: Can't find bundle for base name /Bundle, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:705)
Any ideas ?
The exception is telling that a Bundle_en_US.properties, or Bundle_en.properties, or at least Bundle.properties file is expected in the root of the classpath, but there is actually none.
Make sure that at least one of the mentioned files is present in the root of the classpath. Or, make sure that you provide the proper bundle name. For example, if the bundle files are actually been placed in the package com.example.i18n, then you need to pass com.example.i18n.Bundle as bundle name instead of Bundle.
In case you're using Eclipse "Dynamic Web Project", the classpath root is represented by src folder, there where all your Java packages are. In case you're using a Maven project, the classpath root for resource files is represented by src/main/resources folder.
See also:
Maven and JSF webapp structure, where exactly to put JSF resources
maven-tomcat-plugin
If you start the Project using the maven-tomcat-plugin / maven-tomcat7-plugin, you must place the Bundle.properties, or even the Resource.properties in src/main/webapp/WEB-INF/classes. Dont ask why, its because how the plugin fake a tomcat.
If you are running the .java file in Eclipse you need to add the resource path in the build path .
after that you will not see this error
In my case the problem was using the language tag "en_US" in Locale.forLanguageTag(..) instead of "en-US" - use a dash instead of underline!
Also use Locale.forLanguageTag("en-US") instead of new Locale("en_US") or new Locale("en_US") to define a language ("en") with a region ("US") - but new Locale("en") works.
I had the same problemo, and balus solution fixed it.
For the record:
WEB-INF\faces-config is
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<message-bundle>
Message
</message-bundle>
</application>
</faces-config>
And had Message.properties under WebContent\Resources (after mkyong's tutorial)
the pesky exception appeared even when i renamed the bundle to "Message_en_us" and "Message_en". Moving it to src\ worked.
Should someone post the missing piece to make bundles work under resources,it would be a beautiful thing.
In my case I was dealing with SpringBoot project and I got the same exception.
Solution is made by adding env.properties file into classpath (i.e. src/main/resource folder). What was making the issue is that in log4j configuration there was property like
<Property name="basePath">${bundle:env:log.file.path}</Property>
The Bundle.properties file must be in the directory of the .class files. If it is located in the src directory then you need to make sure to copy it to the bin (output) directory in the same package.
Bundle names have to be fully qualified, like if your bundle Bundle.properties
is inside x.y.z package, then you have to write ResourceBundle.getBundle("x.y.z.Bundle");
I had the same problem using Netbeans. I went to the project folder and copied the properties file. I think clicked "build" and then "classes." I added the properties file in that folder. That solved my problem.
I use Eclipse (without Maven) so I place the .properties file in src folder that also contains the java source code, in order to have the .properties file in the classes folder after building the project. It works fine.
Take a look at this post: https://www.mkyong.com/jsf2/cant-find-bundle-for-base-name-xxx-locale-en_us/
Hope this help you.
The problem must be that the resource-bunde > base-name attribute at the faces-config.xml file has a different path to your properties. This happened to me on the firstcup Java EE tutorial, I gave a different package name on then project creation and then Glassfish was unable to find the properties folder which is on "firstcup.web".
I hope it helps.
Make sure you didn't add the properties files in the wrong resources folder as there is one under 'Web Pages' and one under 'Other Sources/...'. They needed to be under 'Other Sources/...'.
I was able to resolve the issue, the resource was in my project directories but when the junit utility tries to load it, it was returning an error of MissingResourceException. And the reason was the resource was in the not on the classpath of the test class package so when I added the cfg/ folder to my classpath path entry in eclipse and set the output directory in the build conf to the same class package the issue was resolved.
When you try this approach just make sure, the classpath conf file shows the classpath entry of the resource directory (eg. cfg/)
In maven, folder resources, create the same package structure where the configuration files are located and copy them there

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