I want to use the content of a textfile (it is .xml, but I treat it as a plaintext file) to fill my database via jpa, so I need to place the file somewhere and retrieve it on the (glassfish) server, therefore I use this class:
@Singleton
@Startup
public class Initializer {
@PostConstruct
public void populate() {
I found this:
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath(request.getContextPath());
But I don't know where to get that session
object. And I tried this:
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String filename = ctx.getRealPath("/WEB-INF/filename.xml");
This gives me a NullPointerException in the first line.
I've also seen this, but it does not work for me:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("filename.xml").getFile());
Later I will download the file from another location, but for testing purposes I do not want to download it every time.
Update:
InputStream inputStream;
inputStream = Initializer.class.getResourceAsStream("filename.xml");
This is placed in the same directory as Initializer, but inputStream is null.
And here:
InputStream inputStream;
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
inputStream = ctx.getResourceAsStream("/WEB-INF/filename.xml");
The ServletContext is null.
Also null:
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("filename.xml");
And also null (file is in /src/main/java/de/name/):
URL defaultFile = Initializer.class.getResource("/de/name/filename.xml");
Okay, here a different approach - I use the primefaces-extensions showcase in my application and that is able to get file content.
public class ShowcaseUtil {
public static String getFileContent(final String fullPathToFile) {
try {
// Finding in WEB ...
FacesContext fc = FacesContext.getCurrentInstance();
InputStream is = fc.getExternalContext().getResourceAsStream(fullPathToFile);
if (is != null) {
return FileContentMarkerUtil.readFileContent(fullPathToFile, is);
}
// Finding in ClassPath ...
is = ShowcaseUtil.class.getResourceAsStream(fullPathToFile);
if (is != null) {
return FileContentMarkerUtil.readFileContent(fullPathToFile, is);
}
} catch (Exception e) {
throw new IllegalStateException("Internal error: file " + fullPathToFile + " could not be read", e);
}
return "";
}
}
They use it like this:
<ui:define name="contentTab2">
${showcase:getFileContent('/org/primefaces/extensions/showcase/controller/AjaxErrorHandlerController.java')}
</ui:define>
So I tried:
String document = ShowcaseUtil.getFileContent("/org/primefaces/extensions/showcase/controller/AjaxErrorHandlerController.java");
But that is not working. So maybe it's because of the Singleton-Environment? I have no clue, so I find it a bit difficult to find a start for looking for answers.