Relative Path FileNotFoundException - java

i have created two different java projects on project is depend on other and
like A project and B project A project has logs folder and in log4j.xml i have given relative path of log files
now i am using A project as api in B project and i have created executable jar of B project when i am calling B it is giving me FileNotFoundException.
Please suggest me .............
log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException: ..\Framework\logs\log.log (The system cannot find the path specified)
at java.io.FileOutputStream.openAppend(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at org.apache.log4j.FileAppender.setFile(FileAppender.java:273)
at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:152)
at org.apache.log4j.DailyRollingFileAppender.activateOptions(DailyRollingFileAppender.java:206)
at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:247)
at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:210)
at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:140)
at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:153)
at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:415)
at org.apache.log4j.xml.DOMConfigurator.parseRoot(DOMConfigurator.java:384)
at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:783)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:666)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:616)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:602)
at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:460)
at org.apache.log4j.LogManager.<clinit>(LogManager.java:113)
at com.netapp.ca.framework.logger.LogImpl.<init>(LogImpl.java:35)
log4j:ERROR Either File or DatePattern options are not set for appender [allLog].
log4j:ERROR setFile(null,true) call failed.

I think you are executing from a jar, and therefore (of course) the path is wrong because you can't save log files (normally) within a jar.
I've had the same problem and worked it out writing the following method to receive a path where my application can work:
String applicationPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
applicationPath = applicationPath.replace('\\', '/');
if (applicationPath.startsWith("file:")) applicationPath = applicationPath.substring(5);
if (applicationPath.contains(".jar")) {
String[] parts = applicationPath.split("/");
applicationPath = applicationPath.replaceAll(parts[parts.length - 1], "");
}
I don't know how your application is structured but I think this code could help you. Simply write the "applicationPath" to the console and you know what's wrong with the path. I bet it is something like the jar-problem.

It is unclear what you are trying to do, but in simple terms it appears that Log4J cannot find the logfile which you specified in the log4j.xml config.
It is best to use absolute paths when specifying the logging directory for Log4J, but if you insist in using relative paths then make sure you are absolutely sure which directory is the "working directory" for your application.
You can log the working directory for your application with the following code (put this in your Java executable, main method):
System.out.println(System.getProperty("user.dir"));
Once you know the working directory, you can update the logfile path in your log4j.xml config.

Related

Using relative path in a maven project

I have a maven project with these standard directory structures:
src/main/java
src/main/java/pdf/Pdf.java
src/test/resources
src/test/resources/files/x.pdf
In my Pdf.java,
File file = new File("../../../test/resources/files/x.pdf");
Why does it report "No such file or dirctory"? The relative path should work. Right?
Relative paths work relative to the current working directory. Maven does not set it, so it is inherited from whatever value it had in the Java process your code is executing in.
The only reliable way is to figure it out in your own code. Depending on how you do things, there are several ways to do so. See How to get the real path of Java application at runtime? for suggestions. You are most likely looking at this.getClass().getProtectionDomain().getCodeSource().getLocation() and then you know where the class file is and can navigate relative to that.
Why does it report "No such file or dirctory"? The relative path should work. Right?
wrong.
Your classes are compiled to $PROJECT_ROOT/target/classes
and your resources are copied to the same folder keeping their relative paths below src/main/resources.
The file will be located relative to the classpath of which the root is $PROJECT_ROOT/target/classes. Therefore you have to write in your Pdf.java:
File file = new File("/files/x.pdf");
Your relative path will be evaluated from the projects current working directory which is $PROJECT_ROOT (AFAIR).
But it does not matter because you want that to work in your final application and not only in your build environment. Therefore you should access the file with getClass().getResource("/path/to/file/within/classpath") which searches the file in the class path of which the root is $PROJECT_ROOT/target/classes.
No the way you are referencing the files is according to your file system. Java knows about the classpath not the file system if you want to reference something like that you have to use the fully qualified name of the file.
Also I do not know if File constructor works with the classpath since it's an abstraction to manage the file system it will depend where the application is run from. Say it is run from the target directory at the same level as source in that case you have to go one directory up and then on src then test the resources the files and finally in x.pdf.
Since you are using a resources folder I think you want the file to be on the classpath and then you can load a resource with:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("<path in classpath>");
Then you can create a FileInputStream or something to wrap around the file. Otherwise use the fully qualiefied name and put it somewere like /home/{user}/files/x.pdf.

How to inject a Resource from classpath in Spring?

I want to inject a file from src/main/resources like this:
#Value("classpath:myfile.txt")
private Resource res;
When I run this from eclipse it works fine.
But from a standalone folder, the file is not found:
Caused by: java.io.FileNotFoundException: class path resource [myfile.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/myapp/myapp-1.0.0.jar!/myfile.txt
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:212) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
How can I tell spring that the file to be injected is actually in the root of the jar, not an absolute path?
Same result if I try to load it programmatically.
res = new ClassPathResource("myfile.txt");
It turned out the injection itself did work, BUT I accessed the file using res.getFile() which threw the NPE.
When just retrieving the URL and fetching the file explicit with File file = ResourceUtils.getFile(res.getURL().getFile()); it worked as expected.
Though I'm not sure wether this is a bug or works as expected.
You said this works in eclipse:
#Value("classpath:myfile.txt")
private Resource res;
Now try this in eclipse (notice the *), if it works, standalone should be ok:
#Value("classpath*:myfile.txt")
private Resource res;
When deploying outside eclipse, make sure myfile.txt is on the classpath; the best location is in the root directory where Java class file packages are located (com, org)

Unable to read applicationContext.xml when executing the spring class as a runnable jar

I have a spring class with main method. Inside the class am trying to read the values applicationContext.xml . My intention is to jar this main class along with its dependant jars,property files and applicationContext.xml .
But when i try to run the jar file via unix command prompt, it looks like the applicationContext file is not getting loaded.
The applicationContext.xml is seen inside the jar file and am able to see the sysouts inside my class.The code used to read the applicationContext.xml is
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath*:**/applicationContext.xml");
When i print context it is giving me the below message.
org.springframework.context.support.ClassPathXmlApplicationContext#89fbe3: start
up date [Mon Oct 01 15:07:43 IST 2012]; root of context hierarchy
When i try to print context.getBeanDefinitionCount() -- it gives me 0.
But am able to successfully excute this via eclipse . It is able able to read the applicationContext.xml and giving me the bean count as 13.
Not sure why it is not working when i run it as a jar.Please help me with your comments.
How did you get the .jar package? Did you use Eclipse export wizard? It's likely that you have put the "applicationContext.xml" in "/resources" folder. Make sure you fix the "Java Build Path" in Eclipse. Remove all the exclude tags that may be present on "/src/main/resources" folder. The resource folder should be considered a classpath, not just a folder with some xml files in the .jar package. Hope that helps.
A quote from the Spring documentation (emphasis mine):
Please note that "classpath*:" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like "classpath*:*.xml" will not retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK's ClassLoader.getResources() method which only returns file system locations for a passed-in empty string (indicating potential roots to search).
I have struggled with the same issue. I can run my application fine from inside Eclipse, but when I export it as an executable jar, it fails.
I have worked around the issue by:
going to the build path screen in Eclipse and removing the filters on the /resources folder. This causes the export to put the META-INF folder and its contents that are under /resources into the top level of the .jar file.
Remove all the wildcards from the application context path:
applicationContext = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/applicationContext*.xml");
becomes
applicationContext = new ClassPathXmlApplicationContext("classpath:META-INF/spring/applicationContext.xml");
I am sure this is due to some difference in the classloader between the Eclipse environment and my windows java environment. Figuring out how to resolve that will be the next task.

JavaFX 2 - Can´t import .css File

I´m currentl trying to get into JavaFX 2.0 but I can´t get .css Stylesheets to work within my application. I´ve followed the guide at http://docs.oracle.com/javafx/2/get_started/css.htm#BABBGJBI but whenever I try to import a .css file via
scene.getStylesheets().add(Login.class.getResource("loginform.css").toExternalForm());
I get the following Error:
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:399)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at Login.start(Login.java:68)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:315)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:174)
at com.sun.javafx.application.PlatformImpl$3.run(PlatformImpl.java:141)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$2$1.run(WinApplication.java:62)
... 1 more
The css path is located in my eclipse project path:
C:\Users\UserName\Dropbox\Documents\Eclipse\FirstExamples\loginform.css
I´d appreciate any help, I can´t get it working, not with absolute paths nor with relative ones like shown in the example.
Check the compiled output path of your eclipse project and ensure that loginform.css is in the same directory as Login.class
I´ve solved the problem by putting stylesheets into my src folder not
a very nice solution but going up by ../formm.css doesn´t seem to work
dunno why
You are requesting the css file via the class.getResource method, which will look for the resource in the same location the class is located. When you put the stylesheet in your src folder, then whatever build system you are using is copying the stylesheet to the same directory as Login.class during the build. When you don't place it in that src folder, then the copy is not occuring.
If you don't want to place the css file in the same directory as your Java source, then either set your build system up to copy it across from another directory OR don't use the classloader mechanism when you add a stylesheet, e.g. use an absolute file or http url or a file url based on the user.dir system property (current working directory) instead.
Really though, just placing leaving the stylesheet in the src folder and accessing it in the manner you are doing is fine and it also makes resource location easy when you deploy the app to different environments.
If you use anything as a resource, you have to prefix the name of it with "/" and that resource has to be on the classpath.
I have the setup with a directory e.g. resources, which contains the .css. Then I use this:
scene.getStylesheets().add(Login.class.getResource("/loginform.css").toExternalForm());
The directory 'resources' which contains the .css file is added to the classpath (in Eclipse, for example, just make it be a source folder).
It is however pity that the exception is totally useless; I've noticed that the .css was the problem when I added it for the first time.

Trying to Use ESAPI But getting Error

I am trying to use ESAPI.jar for providing security to my web application.Basically I have just started using ESAPI.jar.
But problem is I am not able to run even a simple program using ESAPI.
The small code snippet is:
String clean = ESAPI.encoder().canonicalize("someString");
Randomizer r=ESAPI.randomizer();
System.out.println(r);
System.out.println(clean);
I get this error:
Attempting to load ESAPI.properties via file I/O.
Attempting to load ESAPI.properties as resource file via file I/O.
Not found in 'org.owasp.esapi.resources' directory or file not readable: D:\Eclipse-Workspace\Test\ESAPI.properties
Not found in SystemResource Directory/resourceDirectory: .esapi\ESAPI.properties
Not found in 'user.home' (C:\Documents and Settings\user.user) directory: C:\Documents and Settings\user.user\esapi\ESAPI.properties
Loading ESAPI.properties via file I/O failed. Exception was: java.io.FileNotFoundException
Attempting to load ESAPI.properties via the classpath.
ESAPI.properties could not be loaded by any means. Fail. Exception was: java.lang.IllegalArgumentException: Failed to load ESAPI.properties as a classloader resource.
Exception in thread "main" org.owasp.esapi.errors.ConfigurationException: java.lang.reflect.InvocationTargetException SecurityConfiguration class (org.owasp.esapi.reference.DefaultSecurityConfiguration) CTOR threw exception.
at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:129)
at org.owasp.esapi.ESAPI.securityConfiguration(ESAPI.java:184)
at org.owasp.esapi.ESAPI.encoder(ESAPI.java:99)
at org.rancore.testJasp.TestEsapi.main(TestEsapi.java:59)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:86)
... 3 more
Caused by: org.owasp.esapi.errors.ConfigurationException: ESAPI.properties could not be loaded by any means. Fail.
at org.owasp.esapi.reference.DefaultSecurityConfiguration.loadConfiguration(DefaultSecurityConfiguration.java:439)
at org.owasp.esapi.reference.DefaultSecurityConfiguration.<init>(DefaultSecurityConfiguration.java:227)
at org.owasp.esapi.reference.DefaultSecurityConfiguration.getInstance(DefaultSecurityConfiguration.java:75)
... 8 more
Caused by: java.lang.IllegalArgumentException: Failed to load ESAPI.properties as a classloader resource.
at org.owasp.esapi.reference.DefaultSecurityConfiguration.loadConfigurationFromClasspath(DefaultSecurityConfiguration.java:667)
at org.owasp.esapi.reference.DefaultSecurityConfiguration.loadConfiguration(DefaultSecurityConfiguration.java:436)
... 10 more
I have tried copying the 3 ESAPI properties files in my source folder and also configuring them on build path but still I have not succeeded. I have tried many permutations and combinations to no avail.
Please guide me.
The content of property file is:
# User Messages
Error.creating.randomizer=Error creating randomizer
This.is.test.message=This {0} is {1} a test {2} message
# Validation Messages
# Log Messages
The ESAPI.properties file should have more than 3 lines in it. See for example:
https://web.archive.org/web/20150904064147/http://code.google.com:80/p/owasp-esapi-java/source/browse/trunk/configuration/esapi/ESAPI.properties
In my experience the ESAPI.properties file either needs to be in the same folder as the esapi.jar or needs to be compiled into the jar in a resources directory.
/resources/ESAPI.properties
I believe that either one should work. If ESAPI does not find the file it one location it looks in others.
The code for that is here around line 620:
https://web.archive.org/web/20161005210258/http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/reference/DefaultSecurityConfiguration.java
I just struggled through this one myself.
I created a folder called esapi in my C:/users/myname/ directory and loaded up the ESAPI.properties, validation.properties, and the ESAPI-AccessControlPolicy.xml which got me past all the not finding files errors. ESAPI looks in several places for the files. I'm running Windows 7 64 bit by the way.
Then I had to update some of the jars. I should have done this from the beginning, but I didn't know it. I was getting this error:
AccessController class (org.owasp.esapi.reference.DefaultAccessController) CTOR threw exception.
for every jar that needed to be a newer version, like commons collections or log4j. At the bottom of the stack trace it would reference the offending jar.
When I added the newer jars from the esapi lib directory everything just worked!
I got this message at the end in my console:
ESAPI.accessController found: org.owasp.esapi.reference.DefaultAccessController#1cb8deef
Note: There is an ESAPI_en_US.properties file, but it's the one with only a few lines in it. Just use the file in: \esapi-2.1.0-dist\src\test\resources\esapi\ESAPI.properties. That is the full complete file.
After having this problem and looking at the installation documentation (esapi-x.x.x-dist\documentation\esapi4java-core-x-x-install-guide.pdf) I found a very useful section which detailed that the properties file can be anywhere, provided a vm flag (-Dorg.owasp.esapi.resources=path") points to a particular directory.
For example, if I stick the file in a "resources" folder at the root of my project directory, then the flag would be:
-Dorg.owasp.esapi.resources="path\to\project\root\resources"
The reference SecurityConfiguration manages all the settings used by the ESAPI in a single place. In this reference implementation, resources can be put in several locations, which are searched in the following order:
1) Inside a directory set with a call to SecurityConfiguration.setResourceDirectory( "C:\temp\resources" ).
2) Inside the System.getProperty( "org.owasp.esapi.resources" ) directory. You can set this on the java command line as follows (for example):
java -Dorg.owasp.esapi.resources="C:\temp\resources"
You may have to add this to the start-up script that starts your web server. For example, for Tomcat, in the "catalina" script that starts Tomcat, you can set the JAVA_OPTS variable to the -D string above.
3) Inside the System.getProperty( "user.home" ) + "/.esapi" directory (supported for backward compatibility) or inside the System.getProperty( "user.home" ) + "/esapi" directory.
4) The first ".esapi" or "esapi" directory on the classpath. (The former for backward compatibility.)
Can you put your file (with this name) in:
D:\Eclipse-Workspace\Test\ESAPI.properties
And show us the contents and exception again.
Extract the esapi jar
create a folder named resources under org.owasp.esapi
copy ESAPI.properties to the org.owasp.esapi.resources
Build and deploy
extract the jar
add properties file under resources folder.
initially getting same error, after updating properties file it worked for me
Thanks for providing the information
-Dorg.owasp.esapi.resources="path\to\project\root\resources"
This is a good source of information and has resolved my issue
I had the same problem too. I resolved it using a little bit of James Drinkard solution. What I basically did is created a new folder with name ESAPI and added ESAPI.properties file, Validation.properties, and the ESAPI-AccessControlPolicy.xml. And archived it into a jar file and added to the lib folder under WebContet/WEB-INF and build it to the path and it worked.
*To archive it into a jar file I used windows command move ESAPI ESAPI.jar
Look at the various scripts under 'src/examples/scripts' and they will show you one easy way to control where the ESAPI.properties files is found. (This is for ESAPI 2.0 or later.)
You will find a copy of the ESAPI.properties file will be under 'configuration/esapi'.

Categories

Resources