As our WS implementation is dictionary-based, we need –
at some point – to read our terms dictionary, i.e., a file containing a list of
terms. As this is an expensive operation we only want to do this once for the
whole WS so that any later web method calls can reuse the terms
dictionary and therewith be faster. In our tutorial implementation we will do
this file reading in an extra initialization method which is only called if the
initialization has not been done before, i.e., only once. This method will then
read the terms dictionary and use it to create a new instance of an OpenNLP
DictionaryNameFinder
(package opennlp.tools.namefind); the latter will be used to find terms, then.
Here is the new initialize
method and a new field for
the created term finder:
As you can see, the actual reading of the term dictionary is performed in the
new readTermDictionary
method which returns a
Dictionary
(package opennlp.tools.dictionary); we still need to develop this method,
though.
Reading a file in Java is pretty straightforward – as long as you know
where to find that file, i.e., as long as you have the complete path to the
file. Unfortunately, reading a file from a WS poses just this
problem: we may know the relative path to the file from the context root of the
WS but usually we don’t know where this context root lies in
the file system of the application server that has deployed our WS. The solution to this problem is to let the application server
give us this location at deployment time. This is done using resource injection
with the following lines of code:
At deployment time the application server fills the wsContext
variable with the correct context for our WS. This context can
then be used in our readTermDictionary
method as
follows:
Via the WS context we can retrieve the servlet context of our
web application with which we can read resources then. As you can see, in the
above example we are using the getServletContext
method
from the QALL-ME Framework’s WebServiceTools
(package net.sf.qallme) for
convenience to get from the WS context to the servlet context.
Therewith the initialization of our simple WS
implementation is done.