Can't access to my war file - java

I have an application which is a ear file which contains war and some jar file. I want to access my war's web-inf folder using java code. I tried a lot but could not found anything that can help me to access my war file.
I extracted my ear file in folder structure according to jboss forums but still cant access web-inf folder.
i tried this code but it is returning the jboss bin folder not deployment folder
org.jboss.vfs.VirtualFile vFile = org.jboss.vfs.VFS.getChild("WEB-INF/config/custom.xml");
org.jboss.vfs.VirtualFile vFile1 = org.jboss.vfs.VFS.getRootVirtualFile();
I also tried using JNDI but could not solve the main problem.
InitialContext ic;
try {
ic = new InitialContext();
String moduleName = (String) ic.lookup("java:module/MyModule");
String appName = (String) ic.lookup("java:app/devcenter");
System.out.println("app name is : " + appName);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Can anyone help me? How can I access my WEB-INF folder so that I can change my xml content at runtime?

The simple answer is you can't. An EAR is an archive which means you'd have to know the path, uncompress the archive (or at least the file from the archive), change it and compress the archive again. This would likely require or trigger (can't recall if it happens automatically) a redeploy.
If you have a file you're using for configuration I would suggest you store it in a known path you add to the paths in the server configuration.

You can't access it that way. What you can do is include that in your build path. Then you can access it like you would access any resource files. So copy them over to a folder inside your source folder. For example - src\main\resources\config\custom.xml. Your java classes will be inside src\main\java\ and your resource files will be there.

Related

How to get the path of .key file from spring application programmatically?

I need to get the path of a key file that i have placed in the root folder of my spring application. Everything works as expected when i run it locally. But when i deploy the application to the server i get a FileNotFoundException.
File file = new File("testfile.key");
String path = file.getAbsolutePath();
I have tried placing the file in the resource folder as well.
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource("testfile.key").getFile());
Just need to pass the file path to another method (3rd party library) which will read the content.
Any help would be much appreciated.
This should be a resource, placed in the resource folder (if using maven).
You can access it using
this.getClass().getResource("testfile.key");
The root for accessing files can change between environments but the root for resources is a directory that's specified during compilation. For maven driven projects this is:
src/main/resources

How to set relative path for a folder in Maven java web application?

I am creating a Maven web application which stores many policy files in policy folder. My source folder layout looks like :
I tried to set the folder path as policyLocation as shown below:
try {
// InputStream aa =
// Accesscontrol.class.getClass().getResource(aa);
String AbsolutePath = new File("/").getAbsolutePath();
String policyLocation = (new File("."))
.getCanonicalPath() + File.separator + "policy";
System.setProperty(
FileBasedPolicyFinderModule.POLICY_DIR_PROPERTY,
policyLocation);
} catch (IOException e) {
System.err.println("Can not locate policy repository");
}
But this is returning my Eclipse folder. Is there anyway I can get the policy folder that is not inside Resource folder (cause it can't be included inside Resource) in java web application?
Please keep in mind that your application has more than 1 way to run:
from within IDE (Eclipse) where certain things are done automatically for you (like compilation on the fly)
when you build your web application using maven, do you build it as jar, war, or perhaps ear ? Once built, how do you deploy and run it?
Firstly you have to ensure that your build process (maven) includes the policy files in the distributable (e.g. in the war file) in a known location which you can reference. Then you can modify the classpath within the jar or war and to ensure that your policy files are on the classpath.
With such setup all you have to do is to address it as a resource as per this answer

Tomcat7 deploying app with custom files

This is the content of my netBeans project:
To use the folder called "ErrorSet" i use this line:
File file = new File("ErrorSet/error_list.xml");
It is necessary to import this file because it contains custom error codes, to the point:
When you want to import something in a netbeans project, the default "root" from where you use the files is the project name folder like [projectName]/ErrorSet/error_list.xml ...
Where do i need to place the ErrorSet folder when deploying the [projectName].war from dist folder in tocmat7 so that i can use new File properly? What does the File("ErrorSet/error_list.xml") parent directory become since its in tomcat7?
Keep in mind that Web Pages and Source packages are different things.
To use the classes inside Source packages with custom files, you have to place your files inside a Package and use getClass().gerResource() like this:
In case the ErrorSet folder is a folder inside another package use this:
File file = new File(getClass().getResource("ErrorSet/error_list.xml").toURI());
And if the error_list.xml is in the same package as the class, simply use getResource("error_list.xml").
Don't use java.io.File.
Instead, use a stream that you can get from the ClassLoader, like this:
InputStream in = null;
try {
in = request.getServletContext().getResourceAsStream("/WEB-INF/ErrorSet/error_list.xml");
if(null != in) {
// read the XML
}
} finally {
if(null != in) try { in.close(); }
catch (IOException ioe) { /* log this */ }
}
Now, put your file into /WEB-INF/ErrorSet/error_list.xml in your deployment.
This will work whether the file is on the file system or packaged up in an unexploded WAR file. It will also work in environments with a SecurityManager installed that won't allow the web application to read files, because the servlet container probably does have privileges to read those files.

How to reference a resource file correctly for JAR and Debugging?

I have a nasty problem referencing resources when using a Maven project and Jar files...
I have all my resources in a dedicated folder /src/main/resources which is part of the build path in Eclipse. Files are referenced using
getClass().getResource("/filename.txt")
This works fine in Eclipse but fails in the Jar file - there the resources are located in a folder directly below the jar's root...
Does anyone know a 'best practice' to reference a file both in the JAR and (!) in Eclipse?
Edit:
The problem is that while the resources actually are located in the JAR in a folder "resources" at the top level, the above method fails to find the file...
Once you pack the JAR, your resource files are not files any more, but stream, so getResource will not work!
Use getResourceAsStream.
To get the "file" content, use https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html:
static public String getFile(String fileName)
{
//Get file from resources folder
ClassLoader classLoader = (new A_CLASS()).getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream(fileName);
try
{
if (stream == null)
{
throw new Exception("Cannot find file " + fileName);
}
return IOUtils.toString(stream);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
I had a similar problem.
After a full day of trying every combination and debugging I tried getClass().getResourceAsStream("resources/filename.txt") and got it to work finally.
Nothing else helped.
The contents of Maven resource folders are copied to target/classes and from there to the root of the resulting Jar file. That is the expected behaviour.
What I don't understand is what the problem is in your scenario. Referencing a Resource through getClass().getResource("/filename.txt") starts at the root of the classpath, whether that (or an element of it) is target/classes or the JAR's root. The only possible error I see is that you are using the wrong ClassLoader.
Make sure that the class that uses the resource is in the same artifact (JAR) as the resource and do ThatClass.class.getResource("/path/with/slash") or ThatClass.class.getClassLoader().getResource("path/without/slash").
But apart from that: if it isn't working, you are probably doing something wrong somewhere in the build process. Can you verify that the resource is in the JAR?
If you add the resources directory in the jar file (so it is under the /resources folder in the jar, and if /src/main is in your build path in eclipse, then you should be able to reference your file as:
getClass().getResource("/resources/filename.txt");
Which should work in both environments.
The problem is that within the IDE the getClass().getResource("Path"); String is not CASE SENSITIVE when accessing a file but when running from a jar it is. Check your Capitalisation on directory compared to file. It does work. Also if you try new File(getClass().getResource("Path"); the file won't be readable outside IDE.
Maybe this method can help for some situations.
public static File getResourceFile(String relativePath)
{
File file = null;
URL location = <Class>.class.getProtectionDomain().getCodeSource().getLocation();
String codeLocation = location.toString();
try{
if (codeLocation.endsWith(".jar"){
//Call from jar
Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath).normalize();
file = path.toFile();
}else{
//Call from IDE
file = new File(<Class>.class.getClassLoader().getResource(relativePath).getPath());
}
}catch(URISyntaxException ex){
ex.printStackTrace();
}
return file;
}
Just copy the file to a temporary directory.
String tempDir = System.getProperty("java.io.tmpdir");
File file = new File(tempDir.getAbsolutePath(), "filename.txt");
if (!file.exists()) {
InputStream is = (getClass().getResourceAsStream("/filename.txt"));
Files.copy(is, file.getAbsoluteFile().toPath());
}

Using external properties files in weblogic

I am working on deploying a J2ee application that I have previously been deploying in JBOSS into Weblogic 10.3.1.0. I am running into an issue with external properties files. In Jboss I can just put the properties files into $JBOSS_HOME/server/default/conf, and they are loaded onto the system classpath and I can access them without any problems. I was able to put shared libraries into $MIDDLEWAREHOME/user_projects/domains/mydomain/lib and they were loaded into the system classpath without any problems but I am unable to load properties files.
Does anyone know how to include external properties files in Weblogic?
Thanks,
I figured this out and have it working the way I would expect. First I did try the suggestions as above. If i added a folder to my classpath, or put the properties files in a folder on my classpath, the jars in the file were picked up, but not properties files. If i put my properties files in a jar, and put them in a folder on my classpath everything worked. But I did not want to have jar my files everytime a change was made. The following works in my env.
If i place the properties files in %WEBLOGIC_HOME%/user_projects/domains/MYDOMAIN then they are getting picked up, without having to be placed in a jar file.
In weblogic jars will be loaded from the lib and the non jar files will be loaded from the domain folder
There are ways to read properties file in Java from weblogic classpath
One (Properties file located in the weblogic domain): Drop the properties file inside the Domain directory. This way the properties file is added to the weblogic classpath automatically and we can read from Java using resourceAsStream.
Two (Properties file from a User defined location):The advantage with this approach is that the property file can reside outside the JAR or EAR file and can be modified conveniently.
package com.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyFileExample {
private static Properties prop;
public static void myMethod() {
InputStream is = null;
try {
prop = new Properties();
String propFilePath = System.getProperty(“propFileLocation“);
InputStream iStream = PropertyFileExample.class.getClassLoader().getResourceAsStream(propFilePath);
//Note that the propFilePath is a -Dparam defined below in the setDomainEnv
prop.load(iStream);
prop.getProperty(“dbuser”);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the weblogic setDomainEnv (under bin) => we need to pass the location of the property file as a -D argument to JAVA_OPTIONS
set JAVA_OPTIONS=%JAVA_OPTIONS% -DpropFileLocation =/dev/file/properties/some.properties
You can set a directory on the classpath and Place your custom properties file in that folder/directory. So that, the entire directory along with property file will be on classpath.
To set the directory on the classpath in weblogic 10.3.x
Create a folder in %DOMAIN_HOME%\config\ folder. example appConfig.
Place your custom property file (Let's say config.properties) in appConfig directory/folder.
Modify the setDomainEnv.cmd (Windows) to include appConfig in the classpath by setting %DOMAIN_HOME%\config\appConfig as value to EXT_POST_CLASSPATH(this variable is already defined in the setDomainEnv.cmd file) variable as below:
set EXT_POST_CLASSPATH=%EXT_POST_CLASSPATH%;%DOMAIN_HOME%\config\appConfig
You can access that file in you java code as below:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream ("config.properties");
Properties prop = new Properties();
prop.load(inputStream);
String value = prop.getProperty("key");
Hope this helps.
The most flexible way is to use weblogic deployment plans and Generic File Loading overrides
External properties file with Weblogic
http://docs.oracle.com/cd/E21764_01/web.1111/e13702/config.htm#DEPGD188
Although it may be a little extra effort, if you put the files into a JAR before dropping them into that lib directory, that should work.
You can look at your setDomainEnv.cmd (Windows) or setDomainEnv.sh (Unix/Linux) script in your domain files and see what locations are added in the CLASSPATH for your domain. Then just choose one folder and place the properties file there, if you want a specific location for your properties file just edit the script.
that was my solution:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
InputStream is = null;
String urlExte = System.getenv("DOMAIN_HOME")+"/properties/SmsBalanceadoWS/";
org.springframework.core.io.Resource resource = ctx.getResource( "file:"+urlExte+"/application.properties");
try {
is = resource.getInputStream();
} catch (IOException e) {
LOGGER.debug("ERROR"+ e.getMessage());
}

Categories