I concocted the following to cache an Object to a class resource location.
static private <T> void toSerializedCache(Class<T> cls, T t, String cachecrlstr) {
try {
URL crl = cls.getResource(cachecrlstr);
File crf = new File(crl.getFile());
JAXBContext jaxbContext = JAXBContext.newInstance(cls);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(t, crf);
}
catch (Exception e) {
System.out.printf("Failed to write %s to cache %s", t.getClass(), cachecrlstr);
}
}
The problem is cachecrlstr is an initially non-existent file. The file has to be initially created.
Since it is initially non-existent, the class loader would return the url as null and the procedure fails.
I cannot use absolute path because this routine runs on a web service where we need to deduce the absolute path from the classloader.
To solve this problem, I rewrite the routine to
static private <T> void toSerializedCache(Class<T> cls, T t, String cachecrlstr) {
try {
File crf = new File(request.getSession().getServletContext().getRealPath("/WEB-INF/class"+cachecrlstr));
JAXBContext jaxbContext = JAXBContext.newInstance(cls);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(t, file);
}
catch (JAXBException e) {
System.out.printf("Failed to write %s to cache %s", t.getClass(), cachecrlstr);
}
}
But I am unable to obtain the httpservletrequest object because this routine is inside a jax-rs service implementation. And I am unwilling to write a http listener (those registered in web.xml) to store the request into Threadlocal map. (meaning, don't want to muck around maintaining Threadlocal objects).
However, (though unwilling to write to it) I am willing to withdraw objects from Threadlocal.
Does anyone know if RestEasy stores any http objects in Threadlocal that I could withdraw to deduce the session context or request?
More important question is - what do you suggest that I do to write objects to a file, where the file path is relative to WEB-INF/class
, under the constraints I stated above.