ClassPathXmlApplicationContext error, Spring framework - java

I have encountered a problem when it comes to the Springs framework, which leads to that the communication between the server and the database does not work.
The project that I created is a Spring project, then refactored to Maven.
At this line in the code:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("projectName/spring.xml");
I get this error:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [projectName/spring.xml]; nested exception is java.io.FileNotFoundException: class path resource [projectName/spring.xml] cannot be opened because it does not exist
But it does exist. And I've tried solutions for this problem such as writing ClassPathXmlApplicationContext("spring.xml") instead. This doesn't help however, since then Spring automatically looks in the folder src/main/resources. This doesn't work for me since my project structure doesn't allow me to add this folder and put a XML-file in it. If I try to create this folder, then it is automatically put inside the Java-resources folder, and Eclipse won't allow me to put XML in there.
This is how my project looks:
enter image description here
Is there a way for me to declare where Spring should look for this spring.xml-file?

The ClassPathXmlApplicationContext assumes that the file is on your classpath (Javy describes how to do load a resource from your classpath).
If you want to load the configuration from your file system (as you're doing), you might want to consider using FileSystemXmlApplicationContext instead. Using this mechanism to load your context you can pass a file system location as you're currently doing.

new ClassPathXmlApplicationContext(this.getClass().getResource("/spring.xml").getPath())
try the code above
hope that helped

Spring doesn't look at the src/main/resources, it looks at the classpath.
If you write projectName/spring.xml you need to have this file in bin/projectName/spring.xml or build/projectName/spring.xml. Where bin or build your build folder.
If you build a jar, this file should be in the jar!projectName/spring.xml.
For the web-application this file should be in the WEB-INF/classes/projectName/spring.xml.
If you add src/main/resources at the class path, then content of this folder will be in the build folder. Maven adds src/main/resources at the class path automatically.
Sometimes you should rebuild (clean) your project in the IDE to have such files in the build folder.

Use "FileSystemXmlApplicationContext" as
ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml");

Related

Java rest service with JSON file

I have done a project with a simple Java Rest service and Ajax calls.
Unfortanely if i set the path to the json file as something general (fileName.json), it will not open my file.
If i set a complete path like C:\Users\Username\workspace\RestApplication\fileName.json, it works but when i will submit the project for review, it wont have the same path on my teachers computer.
The file currently resides in the main folder of the project. How can i make a general path that will work on whatever computer opens the project?
Thanks!
you should put the file you want to load in the classpath.
The class path is the path that the Java runtime environment searches for classes and other resource files.
Put your file inside your src or resources folder (I don't know your project structure)
and try to load it with:
InputStream is = TestResource.class.getResourceAsStream("/fileName.json");
or put the file under WEB-INF
#Context ServletContext servletContext;
InputStream is = servletContext.getResourceAsStream("/WEB-INF/fileName.json");
Although numerous different options you most likely want to refer to it on the classpath. See https://en.wikipedia.org/wiki/Classpath_(Java)

Loading a jar's context.xml from classpath

I'm trying to load an application context which is inside a jar as a plugin. I use this to load the context:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:**my-context.xml");
When I load the jar through pom.xml, it works fine.
Then I add it directly in the classpath using eclipse instead of maven to avoid to compile every time (ultimate goal is the shared lib folder in tomcat, not working too). Now spring is unable to find it and return a default context (no exception)
I checked that it's correctly insert in the classpath using:
InputStream in1 = this.getClass().getClassLoader().getResourceAsStream("my-context.xml");
It works.
I checked logs. Using the pom.xml, spring is correctly searching in the jar
Searching directory [...target\classes\META-INF\maven\x.y.z] for files matching pattern [...\x.y.z/target/classes/**/my-context.xml]
Searching directory [...ehealth.poc.module1] for files matching pattern [D:/JRB/Projects/Vivates/workspaces/default/extcom/ehealth.poc.module1/target/classes/**/ecm-context.xml]
...
Resolved location pattern [classpath*:**/my-context.xml] to resources [file [...\target\classes\my-context.xml]]
Loading XML bean definitions from file [...\target\classes\my-context.xml]
...
In the second case, nothing in the log about my jar.
Why spring does not have the same behavior when I use maven or directly the classpath? I maven doing something else than simple adding dependencies location in the classpath?
Finally, we found the solution on eclipse.
The problem comes from the ** in
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:**my-context.xml");
It looks like ** doesn't scan the .jar files. Setting the direct path is working :
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:my-context.xml");

Resources folder in a Java EE application

I'm developing a simple mail sender as Java EE application.
The project structure is shown as follows:
To properly setup email contents, I need to read the *.vm files placed inside the resource folder, that I supposed to have as path classpath:/templates/mail/*.vm (as with Spring)... But my supposition is wrong!
Which is the right path to use?
Should I have to use the META-INF folder? Is this solution more
java-ee-compliant? In that case, where have I to put the META-INF folder inside my project structure?
Update:
I packaged the project as .war, then I putted the files in:
/src/main/webapp/WEB-INF/classes/templates/mail/
Then:
org.apache.velocity.Template t = myVelocityEngine.getTemplate("classpath:/templates/mail/account_to_confirm.vm",
"UTF-8");
Nonetheless, the app returns an error at runtime:
Unable to find resource 'classpath:/templates/mail/account_to_confirm.vm'
What am I doing wrong?
Just to better understand:
Supposing that I'd like to deploy this app as jar (removing the servlet class, of course): in that case, should I have to edit the folder layout in order to still use the same path into the source code?
I think the problem is due to the prefix classpath:: where did you find that you have to use it?
You might find useful understanding how to initialize VelocityEngine reading Loading velocity template inside a jar file and how Configuring Resource Loaders in Velocity.
If you can, use Classloader.getResourceAsStream("templates/mail/*.vm"); or similar getResourceAsURL method.
If not, take a look at where files from resources are placed inside WAR. In your case, the file should be in /WEB-INF/classes/templates/mail .

java, loading of resources fails: unable to resolve file:/my-jar.jar!/folder/my-file

From a java application i made, I build the corresponding jar file.
I copy all the resources in the jar file.
For example, if in src/main/resources there exists the following resource /folder/my-file, then it's copied in the jar with the same path.
But if i execute the jar, the loading of the resources fails.
Specifically, it throws an IOException like this
java.io.IOException: Unable to resolve
"file:/my-jar.jar!/folder/my-file" as either class path, filename or
URL
How should I load the resources?
If I run the java app in eclipse, all works fine, even the resources are loaded correctly.
EDIT:
I'm getting the path of the resource via:
MyClass.class.getResource("/folder/my-file").getPath();
The loading of the resource is made by an external library, what i have to d is just specify the path.
In that case, I would try:
YourClass.class.getClassLoader().getResourceAsStream("folder/my-file");
Which would return an InputStream to your resource independently of your execution environment .
if you have an structure like this:
src/main/Begin.java
src/main/folder/icon.png
Try this in the Begin.java:
Begin.getClass().getResource("/main/folder/icon.png");

Java (maven web app), getting full file path for file in resources folder?

I'm working with a project that is setup using the standard Maven directory structure so I have a folder called "resources" and within this I have made a folder called "fonts" and then put a file in it. I need to pass in the full String file path (of a file that is located, within my project structure, at resources/fonts/somefont.ttf) to an object I am using, from a 3rd party library, as below, I have searched on this for a while but have become a bit confused as to the proper way to do this. I have tried as below but it isn't able to find it. I looked at using ResourceBundle but that seemed to involve making an actual File object when I just need the path to pass into a method like the one below (don't have the actual method call in front of me so just giving an example from my memory):
FontFactory.somemethod("resources/fonts/somefont.ttf");
I had thought there was a way, with a project with standard Maven directory structure to get a file from the resource folder without having to use the full relative path from the class / package. Any advice on this is greatly appreciated.
I don't want to use a hard-coded path since different developers who work on the project have different setups and I want to include this as part of the project so that they get it directly when they checkout the project source.
This is for a web application (Struts 1.3 app) and when I look into the exploded WAR file (which I am running the project off of through Tomcat), the file is at:
<Exploded war dir>/resources/fonts/somefont.ttf
Code:
import java.io.File;
import org.springframework.core.io.*;
public String getFontFilePath(String classpathRelativePath) {
Resource rsrc = new ClassPathResource(classpathRelativePath);
return rsrc.getFile().getAbsolutePath();
}
In your case, classpathRelativePath would be something like "/resources/fonts/somefont.ttf".
You can use the below mentioned to get the path of the file:
String fileName = "/filename.extension"; //use forward slash to recognize your file
String path = this.getClass().getResource(fileName).toString();
use/pass the path to your methods.
If your resources directory is in the root of your war, that means resources/fonts/somefont.ttf would be a "virtual path" where that file is available. You can get the "real path"--the absolute file system path--from the ServletContext. Note (in the docs) that this only works if the WAR is exploded. If your container runs the app from the war file without expanding it, this method won't work.
You can look up the answer to the question on similar lines which I had
Loading XML Files during Maven Test run
The answer given by BobG should work. Though you need to keep in mind that path for the resource file is relative to path of the current class. Both resources and java source files are in classpath

Categories