Junit file path - maven

I am passing a filePath to JUnit as follows
public static void copyFile() throws IOException
{
String inputFileName = "myproj/src/test/resources/list.csv";
File file = new File(inputFileName);
File newFile = new File(new File("/tmp"), file.getName());
FileUtils.copyFile(file, newFile);
}
The package Structure is as follows.
I am running Test.java from IDE (IntelliJ) and it runs fine but when I do mvn clean install i get the below exception
java.io.FileNotFoundException: Source 'myproj/src/test/resources/list.csv' does not exist
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1004)
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:968)
at ......copyFile(Test.java:21)
Can some one please let me know how am i suppose to give path name in the JUnit.

The exception is a strong hint to the problem... the file does not exist at that path.
In your IDE the working directory is set such that your relative path (myproj/src/test/resources/list.csv) resolves correctly.
The Maven task is running from a different working directory, presumably from myproj, so the file path cannot be resolved.
You have a couple of possibilities:
Use an absolute path
Load the resource from the classpath instead, using getResourceAsStream https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
Build different relative paths based on the environment (this is a bad solution)

Related

giving Freemarker resource folder in deployed application for spring boot

I'm trying to give resource folder for Freemarker template below is my bean config
Configuration freeMarkerConfig() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDirectoryForTemplateLoading(new ClassPathResource("ftl").getFile());
return cfg;
}
and I have ftl folder in the resources folder
-- java
-- resources
-- ftl
-- template.ftl
while deploying it works fine in my local machine but fails in my docker container with exception
java.io.FileNotFoundException: class path resource [ftl] cannot be resolved to absolute file
path because it does not reside in the file system: jar:file:!/BOOT-INF/classes!/ftl
I need to keep ftl in the resources folder and give the directory path to configuration. I don't know how to debug further.
Property spring.freemarker.template-loader-path is available.
spring.freemarker.template-loader-path=classpath:/ftl/
Or, use setTemplateLoaderPath("classpath:/ftl/") instead of setDirectoryForTemplateLoading().
I found the issue after repeated searching. Issue is because of this
Classpath resource not found when running as jar

How to load resource file in jenkins plugin?

I am trying to load a resource file which is in src/main/resources folder as part of Jenkins plugin. It is always giving me FileNotFoundException. Can someone please explain how to make it work?
Exception message:
java.io.FileNotFoundException: file:/var/lib/jenkins/plugins/Report/WEB -INF/lib/Report.jar!/properties.txt (No such file or directory)
The question is asked long back but I just thought to share my answer in case it helps someone out there who faced this issue similar to me.
Follow these steps: It works in my case:
Place your file in the "resources" folder thats typically on the
path "src/main/resources". In IntelliJ IDE, mark the resources
directory as "resource root".
As the file(s) are placed inside resources, they are in a directory
thats on the build path so maven should be able to load this without
setting additional build path.
Let say the file name is "application-env.properties". Following code block should
pull the file from resource folder at jenkins plugin run time.
InputStream inputStream = null;
try{
String resourceName = "application-env.properties";
Properties props = new Properties();
ClassLoader cl = <NameOfThisClass>.class.getClassLoader();
try (InputStream stream = cl.getResourceAsStream(resourceName)) {
props.load(stream);
}
//read props or return the same to the caller
}
finally {
if (inputStream != null) {
inputStream.close();
}
}

Classpath resource not resolving in spring boot

I am using spring boot and I have a file in resources folder. I am using digital ocean machine and when i run the application using java -jar mywebapp.war, I am unable to access the file from classpath. I am accessing it using following standard syntax:
File file = new ClassPathResource("mfile").getFile();
I am getting error that class path resource cannot be resolved to absolute path. The problem I see is that it is showing the path with ! marks as follows:
/home/u/webapp/target/mywebapp.war!/WEB-INF/classess!/mfile
What am I doing wrong here?
Since you're running it with java -jar you should build it as a JAR file instead of WAR.
Read more: https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html
Get file does not work while running as jar.you should get it as a resource Stream.
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("/file.xsd") ;
File file = File.createTempFile("file", ".xsd");
try {
FileUtils.copyInputStreamToFile(inputStream, file);
} finally {
IOUtils.closeQuietly(inputStream);
it gets you a file. if the requirement is to get as a file.

File cannot be opened because it does not exist

In my java spring application, I used a data-set.sql file to populate data for testing
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = ConsultationWebApplication.class)
#Sql(scripts="requests-dataset.sql")
#DirtiesContext(classMode= ClassMode.AFTER_EACH_TEST_METHOD)
#ActiveProfiles("test")
public class StatisticsTest {
//bla
//bla
//bla
}'
But when i push my code to the repository, the travis continuous integration
complains with:
org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from class path resource [ee/avok/consultation/service/requests-dataset.sql]; nested exception is java.io.FileNotFoundException: class path resource [ee/avok/consultation/service/requests-dataset.sql] cannot be opened because it does not exist
The point is that, the test runs and pass in the localhost, but it fails the CI
It seems that the CI cannot find the file,but the file is in the test package.
In my experience such errors occur when you are developing under Windows and the CI server works under Unix.
My guess is that you have named some folder within the path to your SQL file with an uppercase letter in Windows. Windows doesn't care for upper or lower case and finds the file in any case. Unix distinguishes between upper and lower case and thus does not find the file.
Search for an uppercase character somewhere in the path to your SQL file.

Spring - applicationContext.xml cannot be opened because it does not exist

I have a Spring MVC application and a problem with JUnit tests combined with the file applicationContext.xml.
In my JUnit test class I write:
final ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
service = (TestServiceImpl) context.getBean("testServiceImpl");
The error I get is that aplicationContect.xml can not be found:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
But it exists in the WEB-INF folder.
So, what's wrong here? Why does the file not exist for the JUnit test?
You should keep your Spring files in another folder, marked as "source" (just like "src" or "resources").
WEB-INF is not a source folder, therefore it will not be included in the classpath (i.e. JUnit will not look for anything there).
If you use maven, create a directory called resources in the main directory, and then copy your applicationContext.xml into it.
From your java code call:
ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
I got the same error.
I solved it moving the file applicationContext.xmlin a
sub-folder of the srcfolder. e.g:
context = new ClassPathXmlApplicationContext("/com/ejemplo/dao/applicationContext.xml");
The ClassPathXmlApplicationContext isn't going to find the applicationContext.xml in your WEB-INF folder, it's not on the classpath. You could copy the application context into your classpath (could put it under src/test/resources and let Maven copy it over) when running the tests.
I also found this problem. What do did to solve this is to copy/paste this file everywhere and run, one file a time. Finally it compiled and ran successfully, and then delete the unnecessary ones. The correct place in my situation is:
This is under the /src/ path (I am using Intellij Idea as the IDE). The other java source files are under /src/com/package/ path
Hope it helpes.
This happens to me from time to time when using eclipse
For some reason (eclipse bug??) the "excluded" parameter gets a value *.* (build path for my resources folder)
Just change the exclusion to none (see red rectangle vs green rectangle)
I hope this helps someone in the future because it was very frustrating to find.
Click on the src/main/java folder and right click and create the xml file. If you create the application.xml file in a subpackage other than /, it will not work.
Know your structure is look like this
package/
| subpackage/
| Abc.java
| Test.java
/application.xml
enter image description here
I was struggling since a couple of hours for this issue because i was putting that file under resources folder but it didn't help me, finally i realized my mistake.
Put it directly under src/main/java.
For me, it worked by keeping file(applicationContext.xml) in the resources folder
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
I placed the applicationContext.xml in the src/main/java folder and it worked
I solved it moving the file spring-context.xml in a src folder.
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
I fixed it by adding applicationContext.xml into jar/target/test-classes for Maven project. And use
XmlBeanFactory bf = new XmlBeanFactory( new ClassPathResource(
"/applicationContext.xml", getClass() ) )
instead of
XmlBeanFactory bf = new XmlBeanFactory( new ClassPathResource(
"/WEB-INF/applicationContext.xml", getClass() ) )
My solution:
If you have no folder WEB-INF please put the file applicationContext.xml into the folder source(src).
Then Java Project can read file applicationContext.xml -> getBean -> perform your business.
enter image description hereThe solution is to place the xml file in resources folder(src->main-> resources) and use this object creation new ClassPathXmlApplicationContext("applicationContext.xml");
Create a Directory at the bottom of main directory named resources. That solved my issue.
In Spring all source files are inside src/main/java.
Similarly, the resources are generally kept inside src/main/resources.
So keep your spring configuration file inside resources folder.
Make sure you have the ClassPath entry for your files inside src/main/resources as well.
In .classpath check for the following 2 lines. If they are missing add them.
<classpathentry path="src/main/java" kind="src"/>
<classpathentry path="src/main/resources" kind="src" />
So, if you have everything in place the below code should work.
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");
Please do This code - it worked
AbstractApplicationContext context= new ClassPathXmlApplicationContext("spring-config.xml");
o/w: Delete main method class and recreate it while recreating please uncheck Inherited abstract method its worked
I'm using Netbeans, i solved my problem by putting the file in: Other Sources default package, then i called it in this way:
ApplicationContext context =new ClassPathXmlApplicationContext("bean.xml");
resources folder
While working with Maven got same issue then I put XML file into src/main/java path and it worked.
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
You actually need to understand the ApplicationContext. It is an interface and it will have different implementations based on configuration.
As you are using new ClassPathXmlApplicationContext("applicationContext.xml"); , kindly pay attention to initial right hand-side , it says ClassPathXmlApplicationContext , so the XML must be present in the class path.
So drag your applicationContext.xml wherever it is to the src folder.
Gist: new ClassPathXmlApplicationContext as the name
[ClassPathXml]will look for the xml file in the src folder of your
project, so drag your xml file there only.
 ClassPathXmlApplicationContext—Loads a context definition from an XML
file located in the classpath, treating context definition files as classpath
resources.
 FileSystemXmlApplicationContext—Loads a context definition from an XML
file in the file system.
 XmlWebApplicationContext—Loads context definitions from an XML file contained
within a web application.
just change the containing package of your applicationContext.xml file.
applicationContext.xml must be in src package not in your project package.
e.g.
src(main package)
com.yourPackageName(package within src)
classes etc.
applicationContext.xml(within src but outside of yourPackage or we can say
parallel to yourPackage name)
your-module/src/applicationContext.xml
val context = ClassPathXmlApplicationContext("applicationContext.xml")
Check the directory path, the default path is /src/ and not /.
GL
I got the same issue while working on a maven project, so I recreate the configuration file spring.xml in src/main/java and it worked for me.
I solved it by moving the file applicationContext.xml in an src folder and main folder.
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");

Resources