giving Freemarker resource folder in deployed application for spring boot - 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

Related

Give external path in #Value Spring annotation and Resource

In spring boot application how do I give an external windows path using #Value Spring annotation and Resource
The below example works fine that look into resources folder but I want to give the path outside of application like c:\data\sample2.csv
#Value("classPath:/sample2.csv")
private Resource inputResource;
...
#Bean
public FlatFileItemReader<Employee> reader() {
FlatFileItemReader<Employee> itemReader = new FlatFileItemReader<Employee>();
itemReader.setLineMapper(lineMapper());
itemReader.setLinesToSkip(1);
itemReader.setResource(inputResource);
and if I want to get the value from properties file in annotaion, whats the format to put the path in windows?
i tried these, none of them worked:
in code
#Value("${inputfile}")
in properties file:
inputfile="C:\Users\termine\dev\sample2.csv"
inputfile="\\C:\\Users\\termine\\dev\\sample2.csv"
inputfile="C:/Users/termine/dev/sample2.csv"
inputfile="file:\\C:\Users\termine\dev\sample2.csv"
inputfile="file://C://Users//termine///dev//sample2.csv"
When you use classpath spring will try to search with the classpath even if you provide the outside file path.
so instead of using classpath: you can use file:
Ex.
#Value("file:/sample2.csv") //provide full file path if any
Use the key spring.config.location in properties to set the config location. Spring-boot will by default load properties from the locations, with precedence like below :
A /config subdir of the current directory.
The current directory
A classpath /config package
The classpath root
and apart from this when you start the jar or in application.properties you can provide the location of the config file like :
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
You can serve static files from the local disk, by making the resource(s) "sample2.csv" as a static resource. An easy way to do this is by adding spring.resources.static-locations configuration to your applicaiton.properties file. Example:
spring.resources.static-locations=file:///C:/Temp/whatever/path/sample2.csv",classpath:/static-files, classpath:/more-static-resource
When I did this in one of the projects, I was able to access the file form the browser using localhost:8080/sample2.csv.

How do I locate resource files in a Spring Boot project deployed to Elastic Beanstalk?

My Spring Boot project contains an XML file within the src/main/resources folder, which is the common location for such a file.
Running locally and also on Pivotal CloudFoundary, I am able to locate the file and read it in, but on Beanstalk the process results in an empty file.
Code to locate and read file:
URL url = getClass().getResource("/myFile.xml");
LOG.info("File location: " + url.toString());
Resulting log entry:
File location: jar:file:/var/app/current/application.jar!/WEB-INF/classes!/myFile.xml
When I SSH into EC2 instance, I can find the jar in the specified directory.
Do I need to configure Maven to move this file somewhere?
UPDATE
I've since realized that I need to treat this file as in InputStream as it's packaged within the jar.
I'm now using the following code which results in the follow errors:
FileUtils.copyInputStreamToFile(new ClassPathResource("myFile.xml").getInputStream(), myFile);
java.lang.NullPointerException: null
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:345) ~[commons-io-2.5.jar:2.5]
and
FileUtils.copyInputStreamToFile(new ClassPathResource("classpath:myFile.xml").getInputStream(), myFile);
java.io.FileNotFoundException: class path resource [classpath:myFile.xml] cannot be opened because it does not exist
Thanks!
How does your pom.xml look like? Maybe there is a resource-filter active?
In a spring application you could use File file = ResourceUtils.getFile("classpath:myFile.xml"); to read a resource file.
Could you check the result by using ResourceUtils?
Here the link to the api-documentation:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ResourceUtils.html#getFile-java.lang.String-

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.

What is /tmp/jetty-docbase directory used for

I am using SpringBoot and Embedded Jetty.
I see it creates directory /tmp/jetty-docbase...
What is this directory used for? how can I change the root path of it?
It's the document root; the location from which static files will be served by Jetty (rather than by Spring MVC's static resource handling). Spring Boot tries the following locations in order, stopping its search as soon as it finds a match:
An explicitly configured location (ConfigurableEmbeddedServletContainer.setDocumentRoot())
The .war file if running from an executable war
The root directory of an exploded war (identified by the presence of a WEB-INF directory)
./src/main/webapp
./public
./static
$TMP_DIR/jetty-docbase
In your case it's reached 7. This location is used as Jetty needs some location for its document root even if its empty.
If you want to explicitly control the location used for the document root you can configure it by declaring a JettyEmbeddedServletContainerFactory bean:
#Bean
public JettyEmbeddedServletContainerFactory jettyFactory() {
JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
factory.setDocumentRoot(new File("custom/document/root"));
return factory;
}
Or you can create folder ./public or ./static then springboot will never create temp jetty-docbase folder for you

Spring configuration error WEB-INF/servlet-context.xml FileNotFoundException

I have a very simple spring test app. But I get exception even though everything seems to be on order. I might be missing something. Please check the pic to see the project structure and web.xml file contains as well as exception:-
efinitionStoreException: IOException parsing XML document from class path resource [WEB-INF/servlet-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/servlet-context.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
There are two kinds of resources in a servlet environment:
servlet resources - files uner the root of the web application (loaded via ServletContext)
classpath resources - resources on web application's classpath (loaded via ClassLoader)
When Spring is supposed to load its configuration it needs to know which mechanism to use.
classpath:foo/bar.xml - will load as classpath resource
checking WEB-INF/classes, contents of WEB-INF/lib/*.jar and other shared servlet container's classpath locations
when using maven and its project structure, all files from src/main/resources will be placed on classpath
foo/bar.xml - will load as servlet resource
when using maven and its project structure the src/main/webapp folder is the root of your application
TL;DR As I wrote in the comment, either remove classpath: prefix when referencing XML file or move your XML file to src/main/resources and remove the WEB-INF part.

Resources