Ignore:
Timestamp:
2011-10-13T12:05:21+13:00 (13 years ago)
Author:
sjm84
Message:

Some modifications to LibraryServlet to allow CGI formatted POST requests to go through the doGet method, also some initial code for handling file uploads

Location:
main/trunk/greenstone3
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • main/trunk/greenstone3/src/java/org/greenstone/gsdl3/LibraryServlet.java

    r24221 r24753  
    55import org.greenstone.gsdl3.util.*;
    66import org.greenstone.gsdl3.action.PageAction; // used to get the default action
     7import org.greenstone.util.GlobalProperties;
    78import org.w3c.dom.Document;
    89import org.w3c.dom.Element;
     
    1516import java.util.ArrayList;
    1617import java.util.HashMap;
     18import java.util.Iterator;
    1719import java.util.List;
    1820import java.util.Map;
     21import java.util.Set;
    1922import java.io.File;
    2023import java.lang.reflect.Type;
     
    2629
    2730// Apache Commons
     31import org.apache.commons.fileupload.FileItem;
     32import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     33import org.apache.commons.fileupload.servlet.ServletFileUpload;
    2834import org.apache.commons.lang3.*;
    2935
    30 /** a servlet to serve the greenstone library - we are using servlets instead
    31 * of cgi
    32 * the init method is called only once - the first time the servlet classes
    33 * are loaded. Each time a request comes in to the servlet, the session()
    34 * method is called in a new thread (calls doGet/doPut etc)
    35 * takes the a=p&p=home type args and builds a simple request to send to
    36 * its receptionist, which returns a result in html, cos output=html
    37 * is set in the request
    38 *
    39 * 18/Jul/07 xiao
    40 * modify to make the cached parameters collection-specific.
    41 * Most of the work is done in doGet(), except adding an inner class UserSessionCache.
    42 *
    43 * @see Receptionist
    44 */
    45 public class LibraryServlet extends HttpServlet {
     36/**
     37 * a servlet to serve the greenstone library - we are using servlets instead of
     38 * cgi the init method is called only once - the first time the servlet classes
     39 * are loaded. Each time a request comes in to the servlet, the session() method
     40 * is called in a new thread (calls doGet/doPut etc) takes the a=p&p=home type
     41 * args and builds a simple request to send to its receptionist, which returns a
     42 * result in html, cos output=html is set in the request
     43 *
     44 * 18/Jul/07 xiao modify to make the cached parameters collection-specific. Most
     45 * of the work is done in doGet(), except adding an inner class
     46 * UserSessionCache.
     47 *
     48 * @see Receptionist
     49 */
     50public class LibraryServlet extends HttpServlet
     51{
    4652
    4753    /** the receptionist to send messages to */
    48     protected Receptionist recept=null;
    49 
    50     /** the default language - is specified by setting a servlet param,
    51 * otherwise DEFAULT_LANG is used*/
    52     protected String default_lang= null;
     54    protected Receptionist recept = null;
     55
     56    /**
     57     * the default language - is specified by setting a servlet param, otherwise
     58     * DEFAULT_LANG is used
     59     */
     60    protected String default_lang = null;
    5361
    5462    /** Whether or not client-side XSLT support should be exposed */
    5563    protected boolean supports_client_xslt = false;
    5664
    57     /** The default default - used if a default lang is not specified
    58 * in the servlet params */
     65    /**
     66     * The default default - used if a default lang is not specified in the
     67     * servlet params
     68     */
    5969    protected final String DEFAULT_LANG = "en";
    6070
    6171    /** container Document to create XML Nodes */
    62     protected Document doc=null;
     72    protected Document doc = null;
    6373
    6474    /** a converter class to parse XML and create Docs */
    65     protected XMLConverter converter=null;
    66 
    67     /** the cgi stuff - the Receptionist can add new args to this
    68 *
    69 * its used by the servlet to determine what args to save */
     75    protected XMLConverter converter = null;
     76
     77    /**
     78     * the cgi stuff - the Receptionist can add new args to this
     79     *
     80     * its used by the servlet to determine what args to save
     81     */
    7082    protected GSParams params = null;
    7183
    72     /** user id - new one per session. This doesn't work if session state is saved between restarts - this requires this value to be saved too. */
     84    /**
     85     * user id - new one per session. This doesn't work if session state is
     86     * saved between restarts - this requires this value to be saved too.
     87     */
    7388    protected int next_user_id = 0;
    7489
    75     /** a hash that contains all the active session IDs mapped to the cached items
    76 *  It is updated whenever the whole site or a particular collection is reconfigured
    77 *  using the command a=s&sa=c or a=s&sa=c&c=xxx
    78 *  It is in the form: sid -> (UserSessionCache object)
    79 */
     90    /**
     91     * a hash that contains all the active session IDs mapped to the cached
     92     * items It is updated whenever the whole site or a particular collection is
     93     * reconfigured using the command a=s&sa=c or a=s&sa=c&c=xxx It is in the
     94     * form: sid -> (UserSessionCache object)
     95     */
    8096    protected Hashtable session_ids_table = new Hashtable();
    8197
    82     /** the maximum interval that the cached info remains in session_ids_table (in seconds)
    83 *  This is set in web.xml
    84 */
     98    /**
     99     * the maximum interval that the cached info remains in session_ids_table
     100     * (in seconds) This is set in web.xml
     101     */
    85102    protected int session_expiration = 1800;
    86103
    87104    static Logger logger = Logger.getLogger(org.greenstone.gsdl3.LibraryServlet.class.getName());
    88105
    89     /** initialise the servlet
    90 */
    91     public void init(ServletConfig config) throws ServletException {
     106    /** initialise the servlet */
     107    public void init(ServletConfig config) throws ServletException
     108    {
    92109        // always call super.init;
    93110        super.init(config);
    94111        // disable preferences - does this work anyway??
    95112        //System.setProperty("java.util.prefs.PreferencesFactory", "org.greenstone.gsdl3.util.DisabledPreferencesFactory");
    96        
     113
    97114        String library_name = config.getInitParameter(GSConstants.LIBRARY_NAME);
    98115        String gsdl3_home = config.getInitParameter(GSConstants.GSDL3_HOME);
    99116        String interface_name = config.getInitParameter(GSConstants.INTERFACE_NAME);
    100        
    101         String allowXslt = (String)config.getInitParameter(GSConstants.ALLOW_CLIENT_SIDE_XSLT);
     117
     118        String allowXslt = (String) config.getInitParameter(GSConstants.ALLOW_CLIENT_SIDE_XSLT);
    102119        supports_client_xslt = allowXslt != null && allowXslt.equals("true");
    103        
     120
    104121        this.default_lang = config.getInitParameter(GSConstants.DEFAULT_LANG);
    105122        String sess_expire = config.getInitParameter(GSXML.SESSION_EXPIRATION);
    106        
    107         if (sess_expire != null && !sess_expire.equals("")) {
     123
     124        if (sess_expire != null && !sess_expire.equals(""))
     125        {
    108126            this.session_expiration = Integer.parseInt(sess_expire);
    109127        }
    110        
    111         if (library_name == null || interface_name ==null) {
     128
     129        if (library_name == null || interface_name == null)
     130        {
    112131            // must have this
    113132            System.err.println("initialisation parameters not all set!");
     
    115134            System.exit(1);
    116135        }
    117        
     136
    118137        String site_name = config.getInitParameter(GSConstants.SITE_NAME);
    119138        String remote_site_name = null;
    120139        String remote_site_type = null;
    121140        String remote_site_address = null;
    122        
    123         if (site_name == null) {
     141
     142        if (site_name == null)
     143        {
    124144            // no site, try for communicator
    125145            remote_site_name = config.getInitParameter("remote_site_name");
    126146            remote_site_type = config.getInitParameter("remote_site_type");
    127147            remote_site_address = config.getInitParameter("remote_site_address");
    128             if (remote_site_name == null || remote_site_type == null || remote_site_address == null) {
     148            if (remote_site_name == null || remote_site_type == null || remote_site_address == null)
     149            {
    129150                System.err.println("initialisation paramters not all set!");
    130151                System.err.println("if site_name is not set, then you must have remote_site_name, remote_site_type and remote_site_address set");
     
    132153            }
    133154        }
    134        
    135         if (this.default_lang == null) {
     155
     156        if (this.default_lang == null)
     157        {
    136158            // choose english
    137159            this.default_lang = DEFAULT_LANG;
    138160        }
    139        
     161
    140162        HashMap config_params = new HashMap();
    141        
     163
    142164        config_params.put(GSConstants.LIBRARY_NAME, library_name);
    143         config_params.put(GSConstants.INTERFACE_NAME, interface_name); 
     165        config_params.put(GSConstants.INTERFACE_NAME, interface_name);
    144166        config_params.put(GSConstants.ALLOW_CLIENT_SIDE_XSLT, supports_client_xslt);
    145        
    146         if (site_name != null) {
     167
     168        if (site_name != null)
     169        {
    147170            config_params.put(GSConstants.SITE_NAME, site_name);
    148171        }
    149172        this.converter = new XMLConverter();
    150173        this.doc = this.converter.newDOM();
    151        
     174
    152175        // the receptionist -the servlet will talk to this
    153         String recept_name = (String)config.getInitParameter("receptionist_class");
    154         if (recept_name == null) {
     176        String recept_name = (String) config.getInitParameter("receptionist_class");
     177        if (recept_name == null)
     178        {
    155179            this.recept = new DefaultReceptionist();
    156         } else {
    157             try {
    158                 this.recept = (Receptionist)Class.forName("org.greenstone.gsdl3.core."+recept_name).newInstance();
    159             } catch (Exception e) { // cant use this new one, so use normal one
    160                 System.err.println("LibraryServlet configure exception when trying to use a new Receptionist "+recept_name+": "+e.getMessage());
     180        }
     181        else
     182        {
     183            try
     184            {
     185                this.recept = (Receptionist) Class.forName("org.greenstone.gsdl3.core." + recept_name).newInstance();
     186            }
     187            catch (Exception e)
     188            { // cant use this new one, so use normal one
     189                System.err.println("LibraryServlet configure exception when trying to use a new Receptionist " + recept_name + ": " + e.getMessage());
    161190                e.printStackTrace();
    162191                this.recept = new DefaultReceptionist();
     
    164193        }
    165194        this.recept.setConfigParams(config_params);
    166        
     195
    167196        // the receptionist uses a MessageRouter or Communicator to send its requests to. We either create a MessageRouter here for the designated site (if site_name set), or we create a Communicator for a remote site. The is given to teh Receptionist, and the servlet never talks to it again.directly.
    168         if (site_name != null) {
    169             String mr_name = (String)config.getInitParameter("messagerouter_class");
     197        if (site_name != null)
     198        {
     199            String mr_name = (String) config.getInitParameter("messagerouter_class");
    170200            MessageRouter message_router = null;
    171             if (mr_name == null) { // just use the normal MR
     201            if (mr_name == null)
     202            { // just use the normal MR
    172203                message_router = new MessageRouter();
    173             } else { // try the specified one
    174                 try {
    175                     message_router = (MessageRouter)Class.forName("org.greenstone.gsdl3.core."+mr_name).newInstance();
    176                 } catch (Exception e) { // cant use this new one, so use normal one
    177                     System.err.println("LibraryServlet configure exception when trying to use a new MessageRouter "+mr_name+": "+e.getMessage());
     204            }
     205            else
     206            { // try the specified one
     207                try
     208                {
     209                    message_router = (MessageRouter) Class.forName("org.greenstone.gsdl3.core." + mr_name).newInstance();
     210                }
     211                catch (Exception e)
     212                { // cant use this new one, so use normal one
     213                    System.err.println("LibraryServlet configure exception when trying to use a new MessageRouter " + mr_name + ": " + e.getMessage());
    178214                    e.printStackTrace();
    179215                    message_router = new MessageRouter();
    180216                }
    181217            }
    182            
     218
    183219            message_router.setSiteName(site_name);
    184220            message_router.setLibraryName(library_name);
    185221            message_router.configure();
    186222            this.recept.setMessageRouter(message_router);
    187         } else {
     223        }
     224        else
     225        {
    188226            // talking to a remote site, create a communicator
    189227            Communicator communicator = null;
     
    193231            site_elem.setAttribute(GSXML.NAME_ATT, remote_site_name);
    194232            site_elem.setAttribute(GSXML.ADDRESS_ATT, remote_site_address);
    195            
    196             if (remote_site_type.equals(GSXML.COMM_TYPE_SOAP_JAVA)) {
     233
     234            if (remote_site_type.equals(GSXML.COMM_TYPE_SOAP_JAVA))
     235            {
    197236                communicator = new SOAPCommunicator();
    198             } else {
    199                 System.err.println("LibraryServlet.init Error: invalid Communicator type: "+remote_site_type);
     237            }
     238            else
     239            {
     240                System.err.println("LibraryServlet.init Error: invalid Communicator type: " + remote_site_type);
    200241                System.exit(1);
    201242            }
    202            
    203             if (!communicator.configure(site_elem)) {
     243
     244            if (!communicator.configure(site_elem))
     245            {
    204246                System.err.println("LibraryServlet.init Error: Couldn't configure communicator");
    205247                System.exit(1);
     
    207249            this.recept.setMessageRouter(communicator);
    208250        }
    209        
     251
    210252        // the params arg thingy
    211        
    212         String params_name = (String)config.getInitParameter("params_class");
    213         if (params_name == null) {
     253
     254        String params_name = (String) config.getInitParameter("params_class");
     255        if (params_name == null)
     256        {
    214257            this.params = new GSParams();
    215         } else {
    216             try {
    217                 this.params = (GSParams)Class.forName("org.greenstone.gsdl3.util."+params_name).newInstance();
    218             } catch (Exception e) {
    219                 System.err.println("LibraryServlet configure exception when trying to use a new params thing "+params_name+": "+e.getMessage());
     258        }
     259        else
     260        {
     261            try
     262            {
     263                this.params = (GSParams) Class.forName("org.greenstone.gsdl3.util." + params_name).newInstance();
     264            }
     265            catch (Exception e)
     266            {
     267                System.err.println("LibraryServlet configure exception when trying to use a new params thing " + params_name + ": " + e.getMessage());
    220268                e.printStackTrace();
    221269                this.params = new GSParams();
     
    225273        this.recept.setParams(this.params);
    226274        this.recept.configure();
    227        
     275
    228276    }
    229277
    230 
    231     private void logUsageInfo(HttpServletRequest request){
     278    private void logUsageInfo(HttpServletRequest request)
     279    {
    232280        String usageInfo = "";
    233        
     281
    234282        //session-info: get params stored in the session
    235283        HttpSession session = request.getSession(true);
    236284        Enumeration attributeNames = session.getAttributeNames();
    237         while(attributeNames.hasMoreElements()) {
    238             String name = (String)attributeNames.nextElement();
    239             usageInfo +=name+"="+session.getAttribute(name)+" ";
     285        while (attributeNames.hasMoreElements())
     286        {
     287            String name = (String) attributeNames.nextElement();
     288            usageInfo += name + "=" + session.getAttribute(name) + " ";
     289        }
     290
     291        //logged info = general-info + session-info
     292        usageInfo = request.getServletPath() + " " + //serlvet
     293        "[" + request.getQueryString() + "]" + " " + //the query string
     294        "[" + usageInfo.trim() + "]" + " " + // params stored in a session
     295        request.getRemoteAddr() + " " + //remote address
     296        request.getRequestedSessionId() + " " + //session id
     297        request.getHeader("user-agent") + " "; //the remote brower info
     298
     299        logger.info(usageInfo);
     300
     301    }
     302
     303    public class UserSessionCache implements HttpSessionBindingListener
     304    {
     305
     306        String session_id = "";
     307
     308        /**
     309         * a hash that maps the session ID to a hashtable that maps the
     310         * coll_name to its parameters coll_name -> Hashtable (param_name ->
     311         * param_value)
     312         */
     313        protected Hashtable coll_name_params_table = null;
     314
     315        public UserSessionCache(String id, Hashtable table)
     316        {
     317            session_id = id;
     318            coll_name_params_table = (table == null) ? new Hashtable() : table;
     319        }
     320
     321        protected void cleanupCache(String coll_name)
     322        {
     323            if (coll_name_params_table.containsKey(coll_name))
     324            {
     325                coll_name_params_table.remove(coll_name);
     326            }
     327        }
     328
     329        protected Hashtable getParamsTable()
     330        {
     331            return coll_name_params_table;
     332        }
     333
     334        public void valueBound(HttpSessionBindingEvent event)
     335        {
     336            // Do nothing
     337        }
     338
     339        public void valueUnbound(HttpSessionBindingEvent event)
     340        {
     341            if (session_ids_table.containsKey(session_id))
     342            {
     343                session_ids_table.remove(session_id);
     344            }
     345        }
     346
     347        public int tableSize()
     348        {
     349            return (coll_name_params_table == null) ? 0 : coll_name_params_table.size();
     350        }
     351
     352    }
     353
     354    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     355    {
     356        logUsageInfo(request);
     357
     358        String query_string;
     359        if(request.getMethod().equals("GET"))
     360        {
     361            query_string = request.getQueryString();   
     362        }
     363        else if(request.getMethod().equals("POST"))
     364        {
     365            query_string = "";
     366            Map paramMap = request.getParameterMap();
     367            Iterator keyIter = paramMap.keySet().iterator();
     368           
     369            while(keyIter.hasNext())
     370            {
     371                String current = (String)keyIter.next();
     372                query_string += current + "=" + ((String[])paramMap.get(current))[0];
     373                if(keyIter.hasNext())
     374                {
     375                    query_string += "&";
     376                }
     377            }
     378           
     379            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
     380
     381            int sizeLimit = System.getProperties().containsKey("servlet.upload.filesize.limit") ? Integer.parseInt(System.getProperty("servlet.upload.filesize.limit")) : 20 * 1024 * 1024;
     382
     383            fileItemFactory.setSizeThreshold(sizeLimit);
     384            fileItemFactory.setRepository(new File(GlobalProperties.getGSDL3Home() + File.separator + "tmp"));
     385
     386            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
     387
     388            try
     389            {
     390                List items = uploadHandler.parseRequest(request);
     391                Iterator iter = items.iterator();
     392                while(iter.hasNext())
     393                {
     394                    FileItem current = (FileItem) iter.next();
     395                    if(current.isFormField())
     396                    {
     397                        query_string += current.getFieldName() + "=" + current.getString();
     398                        if(iter.hasNext())
     399                        {
     400                            query_string += "&";
     401                        }
     402                    }
     403                    else
     404                    {
     405                        File file = new File(GlobalProperties.getGSDL3Home() + File.separator + "tmp" + File.separator + current.getName());
     406                        current.write(file);
     407                    }
     408                }
     409            }
     410            catch (Exception e)
     411            {
     412                logger.error("Exception in LibraryServlet -> " + e.getMessage());
     413            }
     414           
     415            if(query_string.equals(""))
     416            {
     417                query_string = null;
     418            }
     419        }
     420        else
     421        {
     422            query_string = null;
    240423        }
    241424       
    242         //logged info = general-info + session-info
    243         usageInfo =
    244         request.getServletPath()+" "+ //serlvet
    245         "["+request.getQueryString()+"]" +" "+ //the query string
    246         "["+usageInfo.trim()+"]" +" "+ // params stored in a session
    247         request.getRemoteAddr()+" "+   //remote address
    248         request.getRequestedSessionId()+" "+ //session id
    249         request.getHeader("user-agent")+" "; //the remote brower info
    250        
    251         logger.info(usageInfo);
    252        
    253     }
    254 
    255     public class UserSessionCache implements HttpSessionBindingListener {
    256 
    257         String session_id = "";
    258        
    259         /** a hash that maps the session ID to a hashtable that maps the coll_name to its parameters
    260     *  coll_name -> Hashtable (param_name -> param_value)
    261     */
    262         protected Hashtable coll_name_params_table = null;
    263        
    264         public UserSessionCache(String id, Hashtable table) {
    265             session_id = id;     
    266             coll_name_params_table = (table == null)? new Hashtable() : table;     
    267         }
    268 
    269         protected void cleanupCache(String coll_name) {
    270             if (coll_name_params_table.containsKey(coll_name)) {
    271                 coll_name_params_table.remove(coll_name);
    272             }
    273         }
    274 
    275         protected Hashtable getParamsTable() {
    276             return coll_name_params_table;
    277         }
    278 
    279         public void valueBound(HttpSessionBindingEvent event) {
    280             // Do nothing
    281         }
    282 
    283         public void valueUnbound(HttpSessionBindingEvent event) {
    284             if(session_ids_table.containsKey(session_id)) {
    285                 session_ids_table.remove(session_id);
    286             }
    287         }
    288 
    289         public int tableSize() {
    290             return (coll_name_params_table == null)? 0 : coll_name_params_table.size();
    291         }
    292 
    293     }
    294 
    295     public void doGet (HttpServletRequest request, HttpServletResponse response)
    296     throws ServletException, IOException {
    297         logUsageInfo (request);
    298 
    299         String query_string = request.getQueryString();
    300         if (query_string!=null){
     425        if (query_string != null)
     426        {
    301427            String[] query_arr = StringUtils.split(query_string, "&");
    302428            boolean redirect = false;
     
    305431            String[] nameval = new String[2]; // Reuse it for memory efficiency purposes   
    306432
    307             for (int i=0;i<query_arr.length;i++){
    308 
    309                 if (query_arr[i].startsWith("el=")){
    310                     if (query_arr[i].substring(query_arr[i].indexOf("=")+1,query_arr[i].length()).equals("direct")){
     433            for (int i = 0; i < query_arr.length; i++)
     434            {
     435                if (query_arr[i].startsWith("el="))
     436                {
     437                    if (query_arr[i].substring(query_arr[i].indexOf("=") + 1, query_arr[i].length()).equals("direct"))
     438                    {
    311439                        redirect = true;
    312440                    }
    313                 }else if(query_arr[i].startsWith("href=")){
    314                     href = query_arr[i].substring(query_arr[i].indexOf("=")+1,query_arr[i].length());
     441                }
     442                else if (query_arr[i].startsWith("href="))
     443                {
     444                    href = query_arr[i].substring(query_arr[i].indexOf("=") + 1, query_arr[i].length());
    315445                    href = StringUtils.replace(href, "%2f", "/");
    316446                    href = StringUtils.replace(href, "%7e", "~");
    317447                    href = StringUtils.replace(href, "%3f", "?");
    318448                    href = StringUtils.replace(href, "%3A", "\\:");
    319                 }else if(query_arr[i].startsWith("rl=")){
    320                     rl = query_arr[i].substring(query_arr[i].indexOf("=")+1,query_arr[i].length());
     449                }
     450                else if (query_arr[i].startsWith("rl="))
     451                {
     452                    rl = query_arr[i].substring(query_arr[i].indexOf("=") + 1, query_arr[i].length());
    321453                }
    322454            }
     
    325457            //"rl=0" this is an external link
    326458            //"rl=1" this is an internal link
    327             if ((redirect) && (href != null) && (rl.equals("0"))){// This is an external link, the web page is re-directed to the external URL (&el=&rl=0&href="http://...")
     459            if ((redirect) && (href != null) && (rl.equals("0")))
     460            {// This is an external link, the web page is re-directed to the external URL (&el=&rl=0&href="http://...")
    328461                response.setContentType("text/xml");
    329462                response.sendRedirect(href);
    330463            }
    331464        }
    332        
     465
    333466        // Nested Diagnostic Configurator to identify the client for
    334         HttpSession session = request.getSession (true);
     467        HttpSession session = request.getSession(true);
    335468        session.setMaxInactiveInterval(session_expiration);
    336         String uid = (String)session.getAttribute (GSXML.USER_ID_ATT);
    337         if (uid ==null) {
    338             uid = ""+getNextUserId ();
    339             session.setAttribute (GSXML.USER_ID_ATT, uid);
    340         }
    341         request.setCharacterEncoding ("UTF-8");
    342         response.setContentType ("text/html;charset=UTF-8");
    343         PrintWriter out = response.getWriter ();
    344        
    345         String lang = request.getParameter (GSParams.LANGUAGE);
    346         if (lang==null || lang.equals ("")) {
     469        String uid = (String) session.getAttribute(GSXML.USER_ID_ATT);
     470        if (uid == null)
     471        {
     472            uid = "" + getNextUserId();
     473            session.setAttribute(GSXML.USER_ID_ATT, uid);
     474        }
     475        request.setCharacterEncoding("UTF-8");
     476        response.setContentType("text/html;charset=UTF-8");
     477        PrintWriter out = response.getWriter();
     478
     479        String lang = request.getParameter(GSParams.LANGUAGE);
     480        if (lang == null || lang.equals(""))
     481        {
    347482            // try the session cached lang
    348             lang = (String)session.getAttribute (GSParams.LANGUAGE);
    349             if (lang==null || lang.equals ("")) {
     483            lang = (String) session.getAttribute(GSParams.LANGUAGE);
     484            if (lang == null || lang.equals(""))
     485            {
    350486                // still not set, use the default
    351487                lang = this.default_lang;
    352488            }
    353489        }
    354        
     490
    355491        // set the lang in the session
    356         session.setAttribute (GSParams.LANGUAGE, lang);
    357        
    358         String output = request.getParameter (GSParams.OUTPUT);
    359         if (output==null || output.equals ("")) {
     492        session.setAttribute(GSParams.LANGUAGE, lang);
     493
     494        String output = request.getParameter(GSParams.OUTPUT);
     495        if (output == null || output.equals(""))
     496        {
    360497            output = "html"; // uses html by default
    361498        }
    362        
     499
    363500        // If server output, force a switch to traditional interface
    364501        //output = (output.equals("server")) ? "html" : output;
    365        
     502
    366503        // Force change the output mode if client-side XSLT is supported - server vs. client
    367504        // BUT only if the library allows client-side transforms   
    368         if(supports_client_xslt) {
     505        if (supports_client_xslt)
     506        {
    369507            // MUST be done before the xml_message is built
    370508            Cookie[] cookies = request.getCookies();
    371509            Cookie xsltCookie = null;
    372            
     510
    373511            // The client has cookies enabled and a value set - use it!
    374             if(cookies != null) {
    375                 for(Cookie c : cookies) {
    376                     if(c.getName().equals("supportsXSLT")) {
     512            if (cookies != null)
     513            {
     514                for (Cookie c : cookies)
     515                {
     516                    if (c.getName().equals("supportsXSLT"))
     517                    {
    377518                        xsltCookie = c;
    378519                        break;
     
    382523            }
    383524        }
    384        
     525
    385526        // the request to the receptionist
    386         Element xml_message = this.doc.createElement (GSXML.MESSAGE_ELEM);
    387         Element xml_request = GSXML.createBasicRequest (this.doc, GSXML.REQUEST_TYPE_PAGE, "", lang, uid);
    388         xml_request.setAttribute (GSXML.OUTPUT_ATT, output);
    389        
    390         xml_message.appendChild (xml_request);
    391        
    392         String action = request.getParameter (GSParams.ACTION);
    393         String subaction = request.getParameter (GSParams.SUBACTION);
     527        Element xml_message = this.doc.createElement(GSXML.MESSAGE_ELEM);
     528        Element xml_request = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_PAGE, "", lang, uid);
     529        xml_request.setAttribute(GSXML.OUTPUT_ATT, output);
     530
     531        xml_message.appendChild(xml_request);
     532
     533        String action = request.getParameter(GSParams.ACTION);
     534        String subaction = request.getParameter(GSParams.SUBACTION);
    394535        String collection = request.getParameter(GSParams.COLLECTION);
    395536        String service = request.getParameter(GSParams.SERVICE);
     
    398539        // commands are issued (and also don't need to do caching for this request)
    399540        boolean should_cache = true;
    400         if(action != null && action.equals(GSParams.SYSTEM)) {
     541        if (action != null && action.equals(GSParams.SYSTEM))
     542        {
    401543            should_cache = false;
    402544
    403545            // we may want to remove all collection cache info, or just a specific collection
    404             boolean clean_all = true; 
     546            boolean clean_all = true;
    405547            String clean_collection = null;
    406548            // system commands are to activate/deactivate stuff
     
    408550            // don't like the fact that it is hard coded here
    409551            String coll = request.getParameter(GSParams.SYSTEM_CLUSTER);
    410             if (coll != null && !coll.equals("")) {
     552            if (coll != null && !coll.equals(""))
     553            {
    411554                clean_all = false;
    412555                clean_collection = coll;
    413             } else {
     556            }
     557            else
     558            {
    414559                // check other system types
    415                 if (subaction.equals("a") || subaction.equals("d")) {
     560                if (subaction.equals("a") || subaction.equals("d"))
     561                {
    416562                    String module_name = request.getParameter("sn");
    417                     if (module_name != null && !module_name.equals("")) {
     563                    if (module_name != null && !module_name.equals(""))
     564                    {
    418565                        clean_all = false;
    419566                        clean_collection = module_name;
     
    421568                }
    422569            }
    423             if (clean_all) {
    424                 session_ids_table = new Hashtable();
     570            if (clean_all)
     571            {
     572                session_ids_table = new Hashtable();
    425573                session.removeAttribute(GSXML.USER_SESSION_CACHE_ATT);
    426             } else {
     574            }
     575            else
     576            {
    427577                // just clean up info for clean_collection
    428578                ArrayList cache_list = new ArrayList(session_ids_table.values());
    429                 for (int i=0; i<cache_list.size(); i++) {
    430                     UserSessionCache cache = (UserSessionCache)cache_list.get(i);
     579                for (int i = 0; i < cache_list.size(); i++)
     580                {
     581                    UserSessionCache cache = (UserSessionCache) cache_list.get(i);
    431582                    cache.cleanupCache(clean_collection);
    432583                }
    433                
    434             }
    435 
    436         }
    437        
     584
     585            }
     586
     587        }
     588
    438589        // cache_key is the collection name, or service name
    439590        String cache_key = collection;
    440         if (cache_key == null || cache_key.equals("")) {
     591        if (cache_key == null || cache_key.equals(""))
     592        {
    441593            cache_key = service;
    442594        }
    443        
     595
    444596        // logger.info("should_cache= " + should_cache);
    445597
     
    447599        //about the same collection as the last session or not.
    448600        Enumeration attributeNames = session.getAttributeNames();
    449         while(attributeNames.hasMoreElements()) {
    450             String name = (String)attributeNames.nextElement();
    451             if (!name.equals (GSXML.USER_SESSION_CACHE_ATT)
    452                     && !name.equals (GSParams.LANGUAGE)
    453                     && !name.equals (GSXML.USER_ID_ATT)) {
     601        while (attributeNames.hasMoreElements())
     602        {
     603            String name = (String) attributeNames.nextElement();
     604            if (!name.equals(GSXML.USER_SESSION_CACHE_ATT) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSXML.USER_ID_ATT))
     605            {
    454606
    455607                session.removeAttribute(name);
    456608            }
    457609        }
    458        
     610
    459611        UserSessionCache session_cache = null;
    460         Hashtable param_table = null;   
     612        Hashtable param_table = null;
    461613        Hashtable table = null;
    462614        String sid = session.getId();
    463         if (should_cache == true && cache_key != null && !cache_key.equals("")) {
    464             if (session_ids_table.containsKey(sid)) {
    465                 session_cache = (UserSessionCache)session_ids_table.get(sid);
     615        if (should_cache == true && cache_key != null && !cache_key.equals(""))
     616        {
     617            if (session_ids_table.containsKey(sid))
     618            {
     619                session_cache = (UserSessionCache) session_ids_table.get(sid);
    466620                param_table = session_cache.getParamsTable();
    467621                logger.info("collections in table: " + tableToString(param_table));
    468                 if (param_table.containsKey(cache_key)) {
     622                if (param_table.containsKey(cache_key))
     623                {
    469624                    //logger.info("existing table: " + collection);
    470                     table = (Hashtable)param_table.get(cache_key);
    471                 } else {
     625                    table = (Hashtable) param_table.get(cache_key);
     626                }
     627                else
     628                {
    472629                    table = new Hashtable();
    473630                    param_table.put(cache_key, table);
    474631                    //logger.info("new table: " + collection);
    475632                }
    476             } else {
     633            }
     634            else
     635            {
    477636                param_table = new Hashtable();
    478637                table = new Hashtable();
     
    485644        }
    486645
    487         if (action==null || action.equals ("")) {
     646        if (action == null || action.equals(""))
     647        {
    488648            // should we do all the following stuff if using default page?
    489649            // display the home page  - the default page
    490             xml_request.setAttribute (GSXML.ACTION_ATT, "p");
    491             xml_request.setAttribute (GSXML.SUBACTION_ATT, PageAction.HOME_PAGE);
    492         }
    493         else {
    494             xml_request.setAttribute (GSXML.ACTION_ATT, action);
    495             if (subaction != null) {
    496                 xml_request.setAttribute (GSXML.SUBACTION_ATT, subaction);
    497             }
    498            
     650            xml_request.setAttribute(GSXML.ACTION_ATT, "p");
     651            xml_request.setAttribute(GSXML.SUBACTION_ATT, PageAction.HOME_PAGE);
     652        }
     653        else
     654        {
     655            xml_request.setAttribute(GSXML.ACTION_ATT, action);
     656            if (subaction != null)
     657            {
     658                xml_request.setAttribute(GSXML.SUBACTION_ATT, subaction);
     659            }
     660
    499661            //  create the param list for the greenstone request - includes
    500662            // the params from the current request and any others from the saved session
    501             Element xml_param_list = this.doc.createElement (GSXML.PARAM_ELEM+GSXML.LIST_MODIFIER);
    502             xml_request.appendChild (xml_param_list);
    503            
    504             Enumeration params = request.getParameterNames ();
    505             while(params.hasMoreElements ()) {
    506                 String name = (String)params.nextElement ();
    507                 if (!name.equals (GSParams.ACTION)
    508                         && !name.equals (GSParams.SUBACTION)
    509                         && !name.equals (GSParams.LANGUAGE)
    510                         && !name.equals (GSParams.OUTPUT)) {// we have already dealt with these
    511                    
    512                     String value="";
    513                     String [] values = request.getParameterValues (name);
     663            Element xml_param_list = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
     664            xml_request.appendChild(xml_param_list);
     665
     666            Enumeration params = request.getParameterNames();
     667            while (params.hasMoreElements())
     668            {
     669                String name = (String) params.nextElement();
     670                if (!name.equals(GSParams.ACTION) && !name.equals(GSParams.SUBACTION) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSParams.OUTPUT))
     671                {// we have already dealt with these
     672
     673                    String value = "";
     674                    String[] values = request.getParameterValues(name);
    514675                    value = values[0];
    515                     if (values.length > 1) {
    516                         for (int i=1; i< values.length; i++) {
    517                             value += ","+values[i];
     676                    if (values.length > 1)
     677                    {
     678                        for (int i = 1; i < values.length; i++)
     679                        {
     680                            value += "," + values[i];
    518681                        }
    519682                    }
    520683                    // either add it to the param list straight away, or save it to the session and add it later
    521                     if (this.params.shouldSave (name) && table != null) {
     684                    if (this.params.shouldSave(name) && table != null)
     685                    {
    522686                        table.put(name, value);
    523                     } else {
    524                         Element param = this.doc.createElement (GSXML.PARAM_ELEM);
    525                         param.setAttribute (GSXML.NAME_ATT, name);
    526                         param.setAttribute (GSXML.VALUE_ATT, GSXML.xmlSafe (value));
    527                         xml_param_list.appendChild (param);
     687                    }
     688                    else
     689                    {
     690                        Element param = this.doc.createElement(GSXML.PARAM_ELEM);
     691                        param.setAttribute(GSXML.NAME_ATT, name);
     692                        param.setAttribute(GSXML.VALUE_ATT, GSXML.xmlSafe(value));
     693                        xml_param_list.appendChild(param);
    528694                    }
    529695                }
     
    531697            //put everything in the table into the session
    532698            // do we need to do this? why not just put from table into param list
    533             if (table != null) {
    534                 Enumeration keys = table.keys ();
    535                 while(keys.hasMoreElements ()) {
    536                     String name = (String)keys.nextElement();
    537                     session.setAttribute(name, (String)table.get(name));
    538                 }
    539             }
    540            
     699            if (table != null)
     700            {
     701                Enumeration keys = table.keys();
     702                while (keys.hasMoreElements())
     703                {
     704                    String name = (String) keys.nextElement();
     705                    session.setAttribute(name, (String) table.get(name));
     706                }
     707            }
     708
    541709            // put in all the params from the session cache
    542             params = session.getAttributeNames ();
    543             while(params.hasMoreElements ()) {
    544                 String name = (String)params.nextElement ();
    545                
    546                 if ( !name.equals (GSXML.USER_SESSION_CACHE_ATT)
    547                         && !name.equals (GSParams.LANGUAGE)
    548                         && !name.equals (GSXML.USER_ID_ATT)) {
     710            params = session.getAttributeNames();
     711            while (params.hasMoreElements())
     712            {
     713                String name = (String) params.nextElement();
     714
     715                if (!name.equals(GSXML.USER_SESSION_CACHE_ATT) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSXML.USER_ID_ATT))
     716                {
    549717
    550718                    // lang and uid are stored but we dont want it in the param list cos its already in the request
    551                     Element param = this.doc.createElement (GSXML.PARAM_ELEM);
    552                     param.setAttribute (GSXML.NAME_ATT, name);
    553                     String value =  GSXML.xmlSafe ((String)session.getAttribute (name));
     719                    Element param = this.doc.createElement(GSXML.PARAM_ELEM);
     720                    param.setAttribute(GSXML.NAME_ATT, name);
     721                    String value = GSXML.xmlSafe((String) session.getAttribute(name));
    554722
    555723                    // ugly hack to undo : escaping
    556724                    value = StringUtils.replace(value, "%3A", "\\:");
    557                     param.setAttribute (GSXML.VALUE_ATT,value);
    558                     xml_param_list.appendChild (param);
    559                 }
    560             }
    561         }
    562        
    563         if (!output.equals("html") && !output.equals("server") && !output.equals("xsltclient")) {
    564             response.setContentType ("text/xml"); // for now use text
    565         }
    566        
     725                    param.setAttribute(GSXML.VALUE_ATT, value);
     726                    xml_param_list.appendChild(param);
     727                }
     728            }
     729        }
     730
     731        if (!output.equals("html") && !output.equals("server") && !output.equals("xsltclient"))
     732        {
     733            response.setContentType("text/xml"); // for now use text
     734        }
     735
    567736        //Add custom HTTP headers if requested
    568737        String httpHeadersParam = request.getParameter(GSParams.HTTPHEADERFIELDS);
     
    570739        {
    571740            Gson gson = new Gson();
    572             Type type = new TypeToken<List<Map<String,String>>>() {}.getType();
    573             List<Map<String,String>> httpHeaders = gson.fromJson(httpHeadersParam, type);
    574             if (httpHeaders != null && httpHeaders.size() > 0) {
    575                
    576                 for(int j = 0; j < httpHeaders.size(); j++)
    577                 {
    578                     Map nameValueMap = (Map)httpHeaders.get(j);
    579                     String name = (String)nameValueMap.get("name");
    580                     String value = (String)nameValueMap.get("value");
    581                    
    582                     if(name != null && value != null)
     741            Type type = new TypeToken<List<Map<String, String>>>()
     742            {
     743            }.getType();
     744            List<Map<String, String>> httpHeaders = gson.fromJson(httpHeadersParam, type);
     745            if (httpHeaders != null && httpHeaders.size() > 0)
     746            {
     747
     748                for (int j = 0; j < httpHeaders.size(); j++)
     749                {
     750                    Map nameValueMap = (Map) httpHeaders.get(j);
     751                    String name = (String) nameValueMap.get("name");
     752                    String value = (String) nameValueMap.get("value");
     753
     754                    if (name != null && value != null)
    583755                    {
    584756                        response.setHeader(name, value);
     
    587759            }
    588760        }
    589        
     761
    590762        Node xml_result = this.recept.process(xml_message);
    591         encodeURLs (xml_result, response);
    592         out.println (this.converter.getPrettyString (xml_result));
    593        
     763        encodeURLs(xml_result, response);
     764        out.println(this.converter.getPrettyString(xml_result));
     765
    594766        displaySize(session_ids_table);
    595767
     
    597769
    598770    //a debugging method
    599     private void displaySize(Hashtable table) {
    600         if(table == null) {
     771    private void displaySize(Hashtable table)
     772    {
     773        if (table == null)
     774        {
    601775            logger.info("cached table is null");
    602776            return;
    603777        }
    604         if (table.size() == 0) {
     778        if (table.size() == 0)
     779        {
    605780            logger.info("cached table size is zero");
    606781            return;
     
    608783        int num_cached_coll = 0;
    609784        ArrayList cache_list = new ArrayList(table.values());
    610         for (int i=0; i<cache_list.size(); i++) {
    611             num_cached_coll += ((UserSessionCache)cache_list.get(i)).tableSize();
     785        for (int i = 0; i < cache_list.size(); i++)
     786        {
     787            num_cached_coll += ((UserSessionCache) cache_list.get(i)).tableSize();
    612788        }
    613789        logger.info("Number of sessions : total number of cached collection info = " + table.size() + " : " + num_cached_coll);
     
    615791
    616792    /** merely a debugging method! */
    617     private String tableToString(Hashtable table) {
     793    private String tableToString(Hashtable table)
     794    {
    618795        String str = "";
    619         Enumeration keys = table.keys ();
    620         while(keys.hasMoreElements ()) {
    621             String name = (String)keys.nextElement();
     796        Enumeration keys = table.keys();
     797        while (keys.hasMoreElements())
     798        {
     799            String name = (String) keys.nextElement();
    622800            str += name + ", ";
    623801        }
     
    625803    }
    626804
    627     /** this goes through each URL and adds in a session id if needed--
    628 * its needed if the browser doesn't accept cookies
    629 * also escapes things if needed
    630 */
    631     protected void encodeURLs(Node dataNode, HttpServletResponse response) {
    632        
    633         if (dataNode == null) {
     805    /**
     806     * this goes through each URL and adds in a session id if needed-- its
     807     * needed if the browser doesn't accept cookies also escapes things if
     808     * needed
     809     */
     810    protected void encodeURLs(Node dataNode, HttpServletResponse response)
     811    {
     812
     813        if (dataNode == null)
     814        {
    634815            return;
    635816        }
    636817
    637         Element data =null;
     818        Element data = null;
    638819
    639820        short nodeType = dataNode.getNodeType();
    640         if (nodeType == Node.DOCUMENT_NODE) {
    641             Document docNode = (Document)dataNode;
    642             data = docNode.getDocumentElement() ;
    643         }
    644         else {
    645             data = (Element)dataNode;
    646         }
    647 
    648         if ( data != null ) {
     821        if (nodeType == Node.DOCUMENT_NODE)
     822        {
     823            Document docNode = (Document) dataNode;
     824            data = docNode.getDocumentElement();
     825        }
     826        else
     827        {
     828            data = (Element) dataNode;
     829        }
     830
     831        if (data != null)
     832        {
    649833
    650834            // get all the <a> elements
     
    653837            int hrefscount = hrefs.getLength();
    654838
    655             for (int i=0; hrefs!=null && i < hrefscount; i++) {
    656                 Element a = (Element)hrefs.item(i);
     839            for (int i = 0; hrefs != null && i < hrefscount; i++)
     840            {
     841                Element a = (Element) hrefs.item(i);
    657842                // ugly hack to get rid of : in the args - interferes with session handling
    658843                String href = a.getAttribute("href");
    659                 if (!href.equals("")) {
    660                     if (href.indexOf("?")!=-1) {
     844                if (!href.equals(""))
     845                {
     846                    if (href.indexOf("?") != -1)
     847                    {
    661848                        String[] parts = StringUtils.split(href, "\\?", -1);
    662849                        if (parts.length == 1)
    663850                        {
    664851                            parts[0] = StringUtils.replace(parts[0], ":", "%3A");
    665                             href = "?"+parts[0];
     852                            href = "?" + parts[0];
    666853                        }
    667854                        else
    668855                        {
    669856                            parts[1] = StringUtils.replace(parts[1], ":", "%3A");
    670                             href = parts[0]+"?"+parts[1];
     857                            href = parts[0] + "?" + parts[1];
    671858                        }
    672                        
     859
    673860                    }
    674861                    a.setAttribute("href", response.encodeURL(href));
    675862                }
    676863            }
    677            
     864
    678865            // now find any submit bits - get all the <form> elements
    679866            NodeList forms = data.getElementsByTagName("form");
    680867            int formscount = forms.getLength();
    681             for (int i=0; forms!=null && i < formscount; i++) {
    682                 Element form = (Element)forms.item(i);
     868            for (int i = 0; forms != null && i < formscount; i++)
     869            {
     870                Element form = (Element) forms.item(i);
    683871                form.setAttribute("action", response.encodeURL(form.getAttribute("action")));
    684872            }
     
    686874            // we should only do this for greenstone urls?
    687875        }
    688        
     876
    689877    }
    690878
    691     synchronized protected int getNextUserId() {
     879    synchronized protected int getNextUserId()
     880    {
    692881        next_user_id++;
    693882        return next_user_id;
    694883    }
    695884
    696     public void doPost(HttpServletRequest request, HttpServletResponse response)
    697     throws ServletException, IOException {
    698 
    699         doGet(request,response);
    700        
     885    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     886    {
     887        doGet(request, response);
    701888    }
    702889}
Note: See TracChangeset for help on using the changeset viewer.