1

Developed project using grails-3.3.1 and generated a Runnable WAR file. When I run using the command:

java -jar build/libs/myproject-0.1.war

It is returning null for the following line:

serveltContext.getRealPath("/someSource");

But it is working fine when deployed in a Tomcat Container.

Then tried the following way:

servletContext.getResource("someSource").getPath();

It is returning, but not the one as expected and not what getRealPath() returns. It is returning like this:

D:/myprojects/myproject/build/libs/myproject-01.war*/

which serves no use for me. Found answers suggesting to use getResourceAsStream() but I don't want a resource, I want only String.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Abdul
  • 81
  • 8

2 Answers2

1

I was unable to find a solution that worked both locally and when deployed in a container. I ended up using this workaround instead to get the path depending on which environment the code is running in:

def path
if (Environment.current == Environment.DEVELOPMENT) {
    path = java.nio.file.FileSystems.default.getPath("someSource").toAbsolutePath().toString()
} else {
    path = ServletContextHolder.servletContext.getRealPath("/someSource")
}
doelleri
  • 19,232
  • 5
  • 61
  • 65
1

I had the same issue with Grails 4.0.11. Seems like serveltContext.getRealPath is deprecated and returns null. Your solution didn't work either for me, so I decided to go with the following approach: (found on https://howtodoinjava.com/spring-boot2/read-file-from-resources/)

  import org.springframework.core.io.ClassPathResource
  import org.springframework.core.io.Resource

  Resource resource = new ClassPathResource("pdfResources/fonts/SFUIText-Medium.ttf") 
  String path = resource?.getPath()

Given the fact, that my app is called "filetest", the file is located on filetest/src/main/resources/pdfResources/fonts/SFUIText-Medium.ttf

This works with "grails run-app" and "grails war" as embedded runnable war file. Hope it helps, as it took me quite a while.

sullivan
  • 360
  • 1
  • 4
  • 14