Changeset 33181 for main/trunk


Ignore:
Timestamp:
2019-06-21T14:33:09+12:00 (5 years ago)
Author:
kjdon
Message:

intermediary commit - am still tidying up the code. 1. servlet context is one per tomcat, not one per servlet. so if you store eg library name as an attribute, if another servlet is initialised, then the value is overwritten. so now store MR as library_nameRouter, one per servlet. library_name is now added to collection assocfile urls, eg /greenstone3/library/sites/localsite.... remove that from url, use it if we need to talk to library eg for verify page. 2. store hmvf in the session, so don't present T&C to user for each document, just once. 3. am trying to tidy up the code. am partway through but committing so far so others can test.

File:
1 edited

Legend:

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

    r33058 r33181  
    2626import org.apache.log4j.Logger;
    2727import org.greenstone.gsdl3.util.GSParams;
     28import org.greenstone.gsdl3.util.GSPath;
    2829import org.greenstone.gsdl3.util.GSXML;
    2930import org.greenstone.gsdl3.util.UserContext;
     
    3637public class URLFilter implements Filter
    3738{
    38     private FilterConfig _filterConfig = null;
    39     private static Logger _logger = Logger.getLogger(org.greenstone.gsdl3.core.URLFilter.class.getName());
    40 
    41     //Restricted URLs
    42     protected static final String SITECONFIG_URL = "sites/[^/]+/siteConfig.xml";
    43     protected static final String USERS_DB_URL = "etc/usersDB/.*";
    44     protected static final ArrayList<String> _restrictedURLs;
    45     static
    46     {
    47         ArrayList<String> restrictedURLs = new ArrayList<String>();
    48         restrictedURLs.add(SITECONFIG_URL);
    49         restrictedURLs.add(USERS_DB_URL);
    50         _restrictedURLs = restrictedURLs;
     39  private FilterConfig _filterConfig = null;
     40  private static Logger _logger = Logger.getLogger(org.greenstone.gsdl3.core.URLFilter.class.getName());
     41
     42  //Restricted URLs
     43  protected static final String SITECONFIG_URL = "sites/[^/]+/siteConfig.xml";
     44  protected static final String USERS_DB_URL = "etc/usersDB/.*";
     45  protected static final ArrayList<String> _restrictedURLs;
     46  static
     47  {
     48    ArrayList<String> restrictedURLs = new ArrayList<String>();
     49    restrictedURLs.add(SITECONFIG_URL);
     50    restrictedURLs.add(USERS_DB_URL);
     51    _restrictedURLs = restrictedURLs;
     52  }
     53
     54  //Constants
     55  protected static final String DOCUMENT_PATH = "document";
     56  protected static final String COLLECTION_PATH = "collection";
     57  protected static final String GROUP_PATH = "group";
     58  protected static final String PAGE_PATH = "page";
     59  protected static final String SYSTEM_PATH = "system";
     60  protected static final String BROWSE_PATH = "browse";
     61  protected static final String SEARCH_PATH = "search";
     62
     63  protected static final String METADATA_RETRIEVAL_SERVICE = "DocumentMetadataRetrieve";
     64  protected static final String ASSOCIATED_FILE_PATH = "/index/assoc/";
     65  protected static final String COLLECTION_FILE_PATH = "/collect/";
     66  protected static final String INTERFACE_PATH = "/interfaces/";
     67  protected static final String SITES_PATH = "/sites/";
     68 
     69  protected static final String SYSTEM_SUBACTION_CONFIGURE = "configure";
     70  protected static final String SYSTEM_SUBACTION_RECONFIGURE = "reconfigure";
     71  protected static final String SYSTEM_SUBACTION_ACTIVATE = "activate";
     72  protected static final String SYSTEM_SUBACTION_DEACTIVATE = "deactivate";
     73
     74  public void init(FilterConfig filterConfig) throws ServletException
     75  {
     76    this._filterConfig = filterConfig;
     77  }
     78
     79  public void destroy()
     80  {
     81    this._filterConfig = null;
     82  }
     83
     84  @SuppressWarnings("deprecation")
     85  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
     86  {
     87    if (!(request instanceof HttpServletRequest)) {
     88      // Can this ever happen?
     89      _logger.error("The request was not an HttpServletRequest");
     90      return;
     91    }
     92     
     93   
     94    HttpServletRequest hRequest = ((HttpServletRequest) request);
     95    HttpSession hSession = hRequest.getSession();
     96    ServletContext context = hSession.getServletContext();
     97   
     98    GSHttpServletRequestWrapper gRequest = new GSHttpServletRequestWrapper(hRequest);
     99     
     100    // this is the part before the ?
     101    String url = hRequest.getRequestURI().toString();
     102    if (isURLRestricted(url)) {
     103     
     104      // TODO - should we make this a proper HTML page?
     105      response.getWriter().println("ERROR: Access to this page is forbidden.");
     106      return;
     107    }
     108
     109
     110    // Run security checks on files requested from a collection's index/assoc folder
     111    if (url.contains(ASSOCIATED_FILE_PATH)) {
     112     
     113    // now we need to get library name from the path, which is like
     114    // /greenstone3/library/sites/localsite/collect/collname/index/assoc/...
     115    String library_name = url.replaceFirst(context.getContextPath(), "");
     116    library_name = library_name.substring(0, library_name.indexOf(SITES_PATH));
     117    if (library_name.equals("")) {
     118      response.getWriter().println("ERROR: Assoc file paths must now contain the library name");
     119      return;
     120    }
     121    // remove initial '/'
     122    library_name = library_name.substring(1);
     123
     124    MessageRouter gsRouter = (MessageRouter) context.getAttribute(library_name+"Router");
     125               
     126    if (gsRouter == null) { 
     127      _logger.error("Receptionist is null, stopping filter");
     128      return;
    51129    }
    52 
    53     //Constants
    54     protected static final String DOCUMENT_PATH = "document";
    55     protected static final String COLLECTION_PATH = "collection";
    56         protected static final String GROUP_PATH = "group";
    57     protected static final String PAGE_PATH = "page";
    58     protected static final String SYSTEM_PATH = "system";
    59         protected static final String BROWSE_PATH = "browse";
    60         protected static final String SEARCH_PATH = "search";
    61 
    62     protected static final String METADATA_RETRIEVAL_SERVICE = "DocumentMetadataRetrieve";
    63     protected static final String ASSOCIATED_FILE_PATH = "/index/assoc/";
    64     protected static final String COLLECTION_FILE_PATH = "/collect/";
    65     protected static final String INTERFACE_PATH = "/interfaces/";
    66 
    67     protected static final String SYSTEM_SUBACTION_CONFIGURE = "configure";
    68     protected static final String SYSTEM_SUBACTION_RECONFIGURE = "reconfigure";
    69     protected static final String SYSTEM_SUBACTION_ACTIVATE = "activate";
    70     protected static final String SYSTEM_SUBACTION_DEACTIVATE = "deactivate";
    71 
    72     public void init(FilterConfig filterConfig) throws ServletException
    73     {
    74         this._filterConfig = filterConfig;
     130    // Sometimes we have a // before the filename - that mucks up the following code, so lets remove them
     131    url = url.replaceAll("//","/");
     132    String dir = null;
     133    int dirStart = url.indexOf(ASSOCIATED_FILE_PATH) + ASSOCIATED_FILE_PATH.length();
     134    int dirEnd = -1;
     135    if (dirStart < url.length() && url.indexOf("/", dirStart) != -1)
     136      {
     137        dirEnd = url.lastIndexOf("/");
     138      }
     139    if (dirEnd != -1)
     140      {
     141        dir = url.substring(dirStart, dirEnd);
     142      }
     143    if (dir == null)
     144      {
     145        return;
     146      }
     147   
     148    String collection = null;
     149    int colStart = url.indexOf(COLLECTION_FILE_PATH) + COLLECTION_FILE_PATH.length();
     150    int colEnd = -1;
     151    if (colStart < url.length() && url.indexOf("/", colStart) != -1)
     152      {
     153        colEnd = url.indexOf("/", colStart);
     154      }
     155    if (colEnd != -1)
     156      {
     157        collection = url.substring(colStart, colEnd);
     158      }
     159    if (collection == null)
     160      {
     161        return;
     162      }
     163   
     164    String file_name = url.substring(url.lastIndexOf("/")+1);
     165
     166   
     167
     168    // Query the MR with a request for the contains metadata for node "dir" - where dir is the assocfilepath
     169    // In the jdbm db, have entries like
     170    // [HASH1552e]
     171    // <contains>HASH1552e3sdlkjf7sdfsdfk
     172    // mapping assocfilepath to doc id
     173    String document = queryMRforDOCID(gsRouter, collection, dir);
     174    if (document == null) {
     175      response.getWriter().println("ERROR: Couldn't find the document associated with assocfilepath: "+dir);
     176      return;
    75177    }
    76 
    77     public void destroy()
    78     {
    79         this._filterConfig = null;
     178   
     179    //Query the MR for the security info for this document - can we show it? Or do we need to be logged in?
     180    // Or do we need to throw up the verify page?
     181   
     182    // While we are doing this, query the document for its srclinkFile metadata - then we can determine if the
     183    // file we are being asked for is the main doc (eg pdf) or just a supporting image on the page
     184
     185    //Get the security info for this collection
     186    Document gsDoc = XMLConverter.newDOM();
     187    Element securityMessage = gsDoc.createElement(GSXML.MESSAGE_ELEM);
     188    Element securityRequest = GSXML.createBasicRequest(gsDoc, GSXML.REQUEST_TYPE_SECURITY, collection, new UserContext());
     189                   
     190    securityMessage.appendChild(securityRequest);
     191    securityRequest.setAttribute(GSXML.NODE_OID, document);
     192                     
     193    // get the srclinkFile for the document
     194    Element metadata_request = GSXML.createBasicRequest(gsDoc, GSXML.REQUEST_TYPE_PROCESS, GSPath.appendLink(collection, "DocumentMetadataRetrieve"), new UserContext());
     195    Element param_list = gsDoc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
     196    GSXML.addParameterToList(param_list, "metadata", "srclinkFile");
     197    metadata_request.appendChild(param_list);
     198    Element doc_list = gsDoc.createElement(GSXML.DOC_NODE_ELEM + GSXML.LIST_MODIFIER);
     199    metadata_request.appendChild(doc_list);
     200    Element d = gsDoc.createElement(GSXML.DOC_NODE_ELEM);
     201    d.setAttribute(GSXML.NODE_ID_ATT, document);
     202    doc_list.appendChild(d);
     203    securityMessage.appendChild(metadata_request);
     204         
     205                   
     206    Element mr_response = (Element)gsRouter.process(securityMessage);
     207    _logger.debug("security response = "+XMLConverter.getPrettyString(mr_response));
     208
     209    boolean verifiable_file = true;
     210    // TODO check for errors
     211
     212    Element meta_response = (Element) GSXML.getNamedElement(mr_response, GSXML.RESPONSE_ELEM, GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
     213    Element metadata_list = (Element)meta_response.getElementsByTagName(GSXML.METADATA_ELEM+GSXML.LIST_MODIFIER).item(0);
     214    String srcdoc = GSXML.getMetadataValue(metadata_list, "srclinkFile");
     215    if (!srcdoc.equals(file_name)) {
     216      // the specified file is just a supporting file, not the main file.
     217      // eg an image in an html doc.
     218      verifiable_file = false;
    80219    }
    81220
    82         @SuppressWarnings("deprecation")
    83     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    84     {
    85         if (request instanceof HttpServletRequest)
    86         {
    87             HttpServletRequest hRequest = ((HttpServletRequest) request);
    88             HttpSession hSession = hRequest.getSession();
    89             ServletContext context = hSession.getServletContext();
    90 
    91             GSHttpServletRequestWrapper gRequest = new GSHttpServletRequestWrapper(hRequest);
    92 
    93             // this is the part before the ?
    94             String url = hRequest.getRequestURI().toString();
    95 
    96             if (isURLRestricted(url))
    97             {
    98                 response.getWriter().println("Access to this page is forbidden.");
    99                 return;
    100             }
    101 
    102             //If the user is trying to access a collection file we need to run a security check
    103             if (url.contains(ASSOCIATED_FILE_PATH))
    104             {
    105                 String dir = null;
    106                 int dirStart = url.indexOf(ASSOCIATED_FILE_PATH) + ASSOCIATED_FILE_PATH.length();
    107                 int dirEnd = -1;
    108                 if (dirStart < url.length() && url.indexOf("/", dirStart) != -1)
    109                 {
    110                     //dirEnd = url.indexOf("/", dirStart);
    111                     // assocfilepath might have more than one folder in it
    112                     dirEnd = url.lastIndexOf("/");
    113                 }
    114                 if (dirEnd != -1)
    115                 {
    116                     dir = url.substring(dirStart, dirEnd);
    117                 }
    118                 if (dir == null)
    119                 {
    120                     return;
    121                 }
    122 
    123                 String collection = null;
    124                 int colStart = url.indexOf(COLLECTION_FILE_PATH) + COLLECTION_FILE_PATH.length();
    125                 int colEnd = -1;
    126                 if (colStart < url.length() && url.indexOf("/", colStart) != -1)
    127                 {
    128                     colEnd = url.indexOf("/", colStart);
    129                 }
    130                 if (colEnd != -1)
    131                 {
    132                     collection = url.substring(colStart, colEnd);
    133                 }
    134                 if (collection == null)
    135                 {
    136                     return;
    137                 }
    138 
    139                 MessageRouter gsRouter = (MessageRouter) context.getAttribute("GSRouter");
     221    Element securityResponse = (Element) GSXML.getNamedElement(mr_response, GSXML.RESPONSE_ELEM, GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_SECURITY);
     222    ArrayList<String> groups = GSXML.getGroupsFromSecurityResponse(securityResponse);
    140223               
    141                 if (gsRouter == null)
    142                 {
    143                     _logger.error("Receptionist is null, stopping filter");
    144                     return;
    145                 }
    146 
    147                 Document gsDoc = XMLConverter.newDOM();
    148 
    149                 Element metaMessage = gsDoc.createElement(GSXML.MESSAGE_ELEM);
    150                 Element metaRequest = GSXML.createBasicRequest(gsDoc, GSXML.REQUEST_TYPE_PROCESS, collection + "/" + METADATA_RETRIEVAL_SERVICE, new UserContext());
    151                 metaMessage.appendChild(metaRequest);
    152 
    153                 Element paramList = gsDoc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
    154                 metaRequest.appendChild(paramList);
    155 
    156                 Element param = gsDoc.createElement(GSXML.PARAM_ELEM);
    157                 paramList.appendChild(param);
    158 
    159                 param.setAttribute(GSXML.NAME_ATT, "metadata");
    160                 param.setAttribute(GSXML.VALUE_ATT, "contains");
    161 
    162                 Element docList = gsDoc.createElement(GSXML.DOC_NODE_ELEM + GSXML.LIST_MODIFIER);
    163                 metaRequest.appendChild(docList);
    164 
    165                 Element doc = gsDoc.createElement(GSXML.DOC_NODE_ELEM);
    166                 docList.appendChild(doc);
    167 
    168                 doc.setAttribute(GSXML.NODE_ID_ATT, dir);
    169 
    170                 Element metaResponse = (Element) gsRouter.process(metaMessage);
    171 
    172                 NodeList metadataList = metaResponse.getElementsByTagName(GSXML.METADATA_ELEM);
    173                 if (metadataList.getLength() == 0)
    174                 {
    175                     _logger.error("Could not find the document related to this url");
    176                 }
    177                 else
    178                 {
    179                     Element metadata = (Element) metadataList.item(0);
    180                     String document = metadata.getTextContent();
    181 
    182                     //Get the security info for this collection
    183                     Element securityMessage = gsDoc.createElement(GSXML.MESSAGE_ELEM);
    184                     Element securityRequest = GSXML.createBasicRequest(gsDoc, GSXML.REQUEST_TYPE_SECURITY, collection, new UserContext());
    185                     securityMessage.appendChild(securityRequest);
    186                     if (document != null && !document.equals(""))
    187                     {
    188                         securityRequest.setAttribute(GSXML.NODE_OID, document);
    189                     }
    190 
    191                     Element securityResponse = (Element) GSXML.getChildByTagName(gsRouter.process(securityMessage), GSXML.RESPONSE_ELEM);
    192                     ArrayList<String> groups = GSXML.getGroupsFromSecurityResponse(securityResponse);
    193                     _logger.debug("security response = "+XMLConverter.getPrettyString(securityResponse));
    194 
    195                     if (!groups.contains(""))
    196                     {
    197                         boolean found = false;
    198                         for (String group : groups)
    199                         {
    200                             if (((HttpServletRequest) request).isUserInRole(group))
    201                             {
    202                                 found = true;
    203                                 break;
    204                             }
    205                         }
    206 
    207                         if (!found)
    208                         {
    209                           // this just returns nothing to the browser - get no error or anything, just an empty document
    210                           // can we return an error page??
    211                           String new_url = context.getContextPath()+"/"+ context.getAttribute("LibraryName")+"?a=p&sa=error&c="+collection+"&ec=wrong_group";
    212                           ((HttpServletResponse)response).sendRedirect(new_url);
    213                             return;
    214                         }
    215                     }
    216                     // if got here have no groups.
    217                     // do we have human verify thing?
    218                     boolean human_verify = false;
     224    if (!groups.contains(""))
     225      {
     226        boolean found = false;
     227        for (String group : groups)
     228          {
     229        if (((HttpServletRequest) request).isUserInRole(group))
     230          {
     231            found = true;
     232            break;
     233          }
     234          }
     235
     236        if (!found)
     237          {
     238        // return an error page to the browser
     239        String new_url = context.getContextPath()+"/"+ library_name+"?a=p&sa=error&c="+collection+"&ec=wrong_group";             
     240        ((HttpServletResponse)response).sendRedirect(new_url);
     241        return;
     242          }
     243      }
     244    // if got here have no groups.
     245    // do we have human verify thing?
     246    if (verifiable_file) {
     247      // we are asking for the main document - lets check human verify
     248                     
     249      if (!securityResponse.getAttribute(GSXML.VERIFY_ATT).equals("")) {
     250        // have we done the test previously?
     251        HttpSession this_session =  ((HttpServletRequest) request).getSession();
     252        if (this_session == null) {
     253          _logger.error("KATH session is null");
     254        } else {
     255          _logger.error("KATH session id = "+this_session.getId());
     256        }
     257        if (this_session.getAttribute(GSParams.VERIFIED) != null ) {
     258          _logger.error("KATH have verified in the session");
     259          // we don't need to re-verify
     260        } else {
     261          _logger.error("KATH verfied not in session");
     262                         
     263          // have we just  done the test?
     264          String hmvf_response = gRequest.getParameter(GSParams.VERIFIED);
     265          // hmvf param will be set by form if the verify page was submitted
     266          if (hmvf_response != null && hmvf_response.equals("1")) {
     267        if (!securityResponse.getAttribute(GSXML.SITE_KEY_ATT).equals("")) {
     268          String recaptcha_response = gRequest.getParameter(Authentication.RECAPTCHA_RESPONSE_PARAM);
     269          String secret_key = securityResponse.getAttribute(GSXML.SECRET_KEY_ATT);
     270          int result = Authentication.verifyRecaptcha(secret_key, recaptcha_response);
     271          _logger.debug("recaptcha result code = "+result);
     272          if (result == Authentication.NO_ERROR) {
     273            _logger.debug("RECAPTCHA SUCCESS, hopefully going to the document");
     274
     275            this_session.setAttribute(GSParams.VERIFIED, "1");
     276          } else {
     277            _logger.error("something went wrong with recaptcha, error="+result);
     278            _logger.error(Authentication.getErrorKey(result));
     279            // display error page
     280            //String new_url = context.getContextPath()+"/"+ context.getAttribute("LibraryName")+"?a=p&sa=error&c="+collection+"&ec=recap_fail";
     281            String new_url = context.getContextPath()+"/"+ library_name+"?a=p&sa=error&c="+collection+"&ec=recap_fail";             
     282            ((HttpServletResponse)response).sendRedirect(new_url);
     283                       
     284            return;
     285          }
     286        }
     287                       
     288          } else {
     289        // hmvf param is not set - we haven't shown them the form yet
     290        // we need to display the verify page
     291        //String new_url = context.getContextPath()+"/"+ context.getAttribute("LibraryName")+"?a=p&sa=verify&c="+collection+"&url="+url;
     292        String new_url = context.getContextPath()+"/"+ library_name+"?a=p&sa=verify&c="+collection+"&url="+url;             
     293        ((HttpServletResponse)response).sendRedirect(new_url);
     294        return;
     295          }
     296        }
     297      }
     298    }
     299   
     300           
     301    // if we got here, we have passed all security checks and just want to view the file.
     302    // However, we need to remove the library_name from the URL. As can't change the
     303    // existing URL, we need to forward to the new one.
     304    // Remove the context and library name parts.
     305    // don't know what happens with the rest of the filter chain? Does this bypass that??
     306    url = url.replaceFirst(context.getContextPath(), "");
     307    url = url.replaceFirst("/"+library_name, "");
     308    request.getRequestDispatcher(url).forward(request, response);
     309
     310    return;
     311    }
     312    else if (url.contains(INTERFACE_PATH))
     313      {             
     314    String fileURL = url.replaceFirst(context.getContextPath(), "");
     315    File requestedFile = new File(context.getRealPath(fileURL));
     316
     317    if (!requestedFile.exists())
     318      {
     319        int interfaceNameStart = fileURL.indexOf(INTERFACE_PATH) + INTERFACE_PATH.length();
     320        int interfaceNameEnd = fileURL.indexOf("/", interfaceNameStart);
     321        String interfaceName = fileURL.substring(interfaceNameStart, interfaceNameEnd);
     322        String interfacesDir = fileURL.substring(0, interfaceNameStart);
     323        File interfaceConfigFile = new File(context.getRealPath(interfacesDir + interfaceName + "/interfaceConfig.xml"));
     324
     325        if (interfaceConfigFile.exists())
     326          {
     327        Document interfaceConfigDoc = XMLConverter.getDOM(interfaceConfigFile);
     328
     329        String baseInterface = interfaceConfigDoc.getDocumentElement().getAttribute("baseInterface");
     330        if (baseInterface.length() > 0)
     331          {
     332            File baseInterfaceFile = new File(context.getRealPath(fileURL.replace("/" + interfaceName + "/", "/" + baseInterface + "/")));
     333            if (baseInterfaceFile.exists())
     334              {
     335            ServletOutputStream out = response.getOutputStream();
     336            out.write(FileUtils.readFileToByteArray(baseInterfaceFile));
     337            out.flush();
     338            out.close();
     339            return;
     340              }
     341          }
     342          }
     343      }
     344      }
     345    else
     346      {
     347    ArrayList<String> keywords = new ArrayList<String>();
     348    keywords.add(PAGE_PATH);
     349    keywords.add(BROWSE_PATH);
     350    keywords.add(SEARCH_PATH);
     351    keywords.add(DOCUMENT_PATH);
     352    //If we have a jsessionid on the end of our URL we want to ignore it
     353    int index;
     354    if ((index = url.indexOf(";jsessionid")) != -1)
     355      {
     356        url = url.substring(0, index);
     357      }
     358    String[] segments = url.split("/");
     359    for (int i = 0; i < segments.length; i++)
     360      {
     361        String[] additionalParameters = null;
     362        String[] defaultParamValues = null;
     363        //COLLECTION
     364        if (segments[i].equals(COLLECTION_PATH) && (i + 1) < segments.length) {
     365          int j=i+1;
     366          while(j+1 < segments.length && !keywords.contains(segments[j+1])) {
     367        j++;
     368          }
     369                     
     370          if (j>i+1) {
     371        // we had a group part
     372        String [] groups = Arrays.copyOfRange(segments, i+1, j);
     373        String group = StringUtils.join(groups, "/");
     374        gRequest.setParameter(GSParams.GROUP, group);
     375          }
     376          gRequest.setParameter(GSParams.COLLECTION, segments[j]);
     377        }
     378        // GROUP
     379        else if(segments[i].equals(GROUP_PATH) && (i + 1) < segments.length)
     380          {
     381        // assume for now, no other path parts for group links
     382        int j= segments.length - 1;
     383        String group;
     384        if (j==i+1) {
     385          group = segments[j];
     386        } else {
     387          String [] groups = Arrays.copyOfRange(segments, i+1, j+1);
     388          group = StringUtils.join(groups, "/");
     389        }
     390        gRequest.setParameter(GSParams.GROUP, group);
     391        gRequest.setParameter(GSParams.ACTION, "p");
     392        gRequest.setParameter(GSParams.SUBACTION, "home");
     393                       
     394          }
     395        //DOCUMENT
     396        else if (segments[i].equals(DOCUMENT_PATH) && (i + 1) < segments.length)
     397          {
     398        gRequest.setParameter(GSParams.DOCUMENT, segments[i + 1]);
     399                       
     400        additionalParameters = new String[] { GSParams.ACTION };
     401        defaultParamValues = new String[] { "d" };
     402        if ((i+2) < segments.length && segments[i+2].equals("print")) {
     403          gRequest.setParameter(GSParams.SUBACTION, "print");
     404          gRequest.setParameter("ed", "1");
     405                         
     406        }
    219407                   
    220                     if (!securityResponse.getAttribute("humanVerify").equals("")) {
    221                       // have we already done the test?
    222                       String hmvf_response = gRequest.getParameter("hmvf");
    223                       // hmvf param will be set by form
    224                       if (hmvf_response != null) {
    225                         if (!securityResponse.getAttribute("siteKey").equals("")) {
    226                           String recaptcha_response = gRequest.getParameter("g-recaptcha-response");
    227                           String secret_key = securityResponse.getAttribute("secretKey");
    228                           int result = Authentication.verifyRecaptcha(secret_key, recaptcha_response);
    229                           _logger.debug("recaptcha result code = "+result);
    230                           if (result == Authentication.NO_ERROR) {
    231                         _logger.debug("RECAPTCHA SUCCESS, hopefully going to the document");
    232                        
    233                           } else {
    234                         _logger.error("something went wrong with recaptcha, error="+result);
    235                         _logger.error(Authentication.getErrorKey(result));
    236                         // display error page
    237                         String new_url = context.getContextPath()+"/"+ context.getAttribute("LibraryName")+"?a=p&sa=error&c="+collection+"&ec=recap_fail";
    238                         ((HttpServletResponse)response).sendRedirect(new_url);
    239                        
    240                         return;
    241                           }
    242                         }
    243                        
    244                       } else {
    245                         // hmvf param is not set - we haven't shown them the form yet
    246                         // we need to display the verify page
    247                         String new_url = context.getContextPath()+"/"+ context.getAttribute("LibraryName")+"?a=p&sa=verify&c="+collection+"&url="+url;
    248                         ((HttpServletResponse)response).sendRedirect(new_url);
    249                         return;
    250                       }
    251                     }
    252                 }
    253             }
    254             else if (url.contains(INTERFACE_PATH))
    255             {               
    256                 String fileURL = url.replaceFirst(context.getContextPath(), "");
    257                 File requestedFile = new File(context.getRealPath(fileURL));
    258 
    259                 if (!requestedFile.exists())
    260                 {
    261                     int interfaceNameStart = fileURL.indexOf(INTERFACE_PATH) + INTERFACE_PATH.length();
    262                     int interfaceNameEnd = fileURL.indexOf("/", interfaceNameStart);
    263                     String interfaceName = fileURL.substring(interfaceNameStart, interfaceNameEnd);
    264                     String interfacesDir = fileURL.substring(0, interfaceNameStart);
    265                     File interfaceConfigFile = new File(context.getRealPath(interfacesDir + interfaceName + "/interfaceConfig.xml"));
    266 
    267                     if (interfaceConfigFile.exists())
    268                     {
    269                       Document interfaceConfigDoc = XMLConverter.getDOM(interfaceConfigFile);
    270 
    271                         String baseInterface = interfaceConfigDoc.getDocumentElement().getAttribute("baseInterface");
    272                         if (baseInterface.length() > 0)
    273                         {
    274                             File baseInterfaceFile = new File(context.getRealPath(fileURL.replace("/" + interfaceName + "/", "/" + baseInterface + "/")));
    275                             if (baseInterfaceFile.exists())
    276                             {
    277                                 ServletOutputStream out = response.getOutputStream();
    278                                 out.write(FileUtils.readFileToByteArray(baseInterfaceFile));
    279                                 out.flush();
    280                                 out.close();
    281                                 return;
    282                             }
    283                         }
    284                     }
    285                 }
    286             }
    287             else
    288             {
    289               ArrayList<String> keywords = new ArrayList<String>();
    290               keywords.add(PAGE_PATH);
    291               keywords.add(BROWSE_PATH);
    292               keywords.add(SEARCH_PATH);
    293               keywords.add(DOCUMENT_PATH);
    294                 //If we have a jsessionid on the end of our URL we want to ignore it
    295                 int index;
    296                 if ((index = url.indexOf(";jsessionid")) != -1)
    297                 {
    298                     url = url.substring(0, index);
    299                 }
    300                 String[] segments = url.split("/");
    301                 for (int i = 0; i < segments.length; i++)
    302                 {
    303                     String[] additionalParameters = null;
    304                     String[] defaultParamValues = null;
    305                     //COLLECTION
    306                     if (segments[i].equals(COLLECTION_PATH) && (i + 1) < segments.length) {
    307                       int j=i+1;
    308                       while(j+1 < segments.length && !keywords.contains(segments[j+1])) {
    309                         j++;
    310                       }
    311                      
    312                       if (j>i+1) {
    313                         // we had a group part
    314                         String [] groups = Arrays.copyOfRange(segments, i+1, j);
    315                         String group = StringUtils.join(groups, "/");
    316                         gRequest.setParameter(GSParams.GROUP, group);
    317                       }
    318                       gRequest.setParameter(GSParams.COLLECTION, segments[j]);
    319                     }
    320                     // GROUP
    321                     else if(segments[i].equals(GROUP_PATH) && (i + 1) < segments.length)
    322                       {
    323                         // assume for now, no other path parts for group links
    324                         int j= segments.length - 1;
    325                         String group;
    326                         if (j==i+1) {
    327                           group = segments[j];
    328                         } else {
    329                           String [] groups = Arrays.copyOfRange(segments, i+1, j+1);
    330                           group = StringUtils.join(groups, "/");
    331                         }
    332                         gRequest.setParameter(GSParams.GROUP, group);
    333                         gRequest.setParameter(GSParams.ACTION, "p");
    334                         gRequest.setParameter(GSParams.SUBACTION, "home");
    335                        
    336                       }
    337                     //DOCUMENT
    338                     else if (segments[i].equals(DOCUMENT_PATH) && (i + 1) < segments.length)
    339                     {
    340                         gRequest.setParameter(GSParams.DOCUMENT, segments[i + 1]);
    341                        
    342                         additionalParameters = new String[] { GSParams.ACTION };
    343                         defaultParamValues = new String[] { "d" };
    344                         if ((i+2) < segments.length && segments[i+2].equals("print")) {
    345                           gRequest.setParameter(GSParams.SUBACTION, "print");
    346                           gRequest.setParameter("ed", "1");
    347                          
    348                         }
    349                    
    350                     }
    351                     //PAGE
    352                     else if (segments[i].equals(PAGE_PATH) && (i + 1) < segments.length)
    353                     {
    354                         gRequest.setParameter(GSParams.SUBACTION, segments[i + 1]);
    355 
    356                         additionalParameters = new String[] { GSParams.ACTION };
    357                         defaultParamValues = new String[] { "p" };
    358                     }
    359                     //SYSTEM
    360                     else if (segments[i].equals(SYSTEM_PATH) && (i + 1) < segments.length)
    361                     {
    362                         String sa = segments[i + 1];
    363                         if (sa.equals(SYSTEM_SUBACTION_CONFIGURE) || sa.equals(SYSTEM_SUBACTION_RECONFIGURE))
    364                         {
    365                             sa = "c";
    366                         }
    367                         else if (sa.equals(SYSTEM_SUBACTION_ACTIVATE))
    368                         {
    369                             sa = "a";
    370                         }
    371                         else if (sa.equals(SYSTEM_SUBACTION_DEACTIVATE))
    372                         {
    373                             sa = "d";
    374                         }
    375 
    376                         if (sa.equals("c") && (i + 2) < segments.length)
    377                         {
    378                             gRequest.setParameter(GSParams.SYSTEM_CLUSTER, segments[i + 2]);
    379                         }
    380 
    381                         if (sa.equals("a") && (i + 2) < segments.length)
    382                         {
    383                             gRequest.setParameter(GSParams.SYSTEM_MODULE_TYPE, "collection");
    384                             gRequest.setParameter(GSParams.SYSTEM_MODULE_NAME, segments[i + 2]);
    385                         }
    386 
    387                         if (sa.equals("d") && (i + 2) < segments.length)
    388                         {
    389                             gRequest.setParameter(GSParams.SYSTEM_CLUSTER, segments[i + 2]);
    390                         }
    391 
    392                         gRequest.setParameter(GSParams.SUBACTION, sa);
    393 
    394                         additionalParameters = new String[] { GSParams.ACTION };
    395                         defaultParamValues = new String[] { "s" };
    396                     }
    397                     //ADMIN
    398                     else if (segments[i].equals("admin") && (i + 1) < segments.length)
    399                     {
    400                         String pageName = segments[i + 1];
    401 
    402                         gRequest.setParameter("s1.authpage", pageName);
    403 
    404                         additionalParameters = new String[] { GSParams.ACTION, GSParams.REQUEST_TYPE, GSParams.SUBACTION, GSParams.SERVICE };
    405                         defaultParamValues = new String[] { "g", "r", "authen", "Authentication" };
    406                     }
    407                     //BROWSE
    408                     else if (segments[i].equals(BROWSE_PATH) && (i + 1) < segments.length)
    409                     {
    410                         String cl = "";
    411                         for (int j = 1; (i + j) < segments.length; j++)
    412                         {
    413                             String currentSegment = segments[i + j].replace("CL", "").replace("cl", "");
    414                             if (currentSegment.contains("."))
    415                             {
    416                                 String[] subsegments = currentSegment.split("\\.");
    417                                 for (String subsegment : subsegments)
    418                                 {
    419                                     subsegment = subsegment.replace("CL", "").replace("cl", "");
    420 
    421                                     if (cl.length() > 0)
    422                                     {
    423                                         cl += ".";
    424                                     }
    425 
    426                                     if (subsegment.length() > 0)
    427                                     {
    428                                         cl += subsegment;
    429                                     }
    430                                 }
    431                                 continue;
    432                             }
    433                             if (!currentSegment.matches("^(CL|cl)?\\d+$"))
    434                             {
    435                                 continue;
    436                             }
    437 
    438                             if (cl.length() > 0)
    439                             {
    440                                 cl += ".";
    441                             }
    442 
    443                             cl += currentSegment;
    444                         }
    445 
    446                         gRequest.setParameter("cl", "CL" + cl);
    447 
    448                         additionalParameters = new String[] { GSParams.ACTION, GSParams.REQUEST_TYPE, GSParams.SERVICE };
    449                         defaultParamValues = new String[] { "b", "s", "ClassifierBrowse" };
    450                     }
    451                     //QUERY
    452                     else if (segments[i].equals(SEARCH_PATH))
    453                     {
    454                         String serviceName = "";
    455                         if ((i + 1) < segments.length)
    456                         {
    457                             serviceName = segments[i + 1];
    458                             gRequest.setParameter("s", serviceName);
    459 
    460                             additionalParameters = new String[] { GSParams.ACTION, GSParams.SUBACTION, GSParams.REQUEST_TYPE };
    461                             defaultParamValues = new String[] { "q", "", "d" };
    462                         }
    463                         if ((i + 2) < segments.length)
    464                         {
    465                             if (serviceName.equals("TextQuery") || serviceName.equals("RawQuery"))
    466                             {
    467 
    468                                 gRequest.setParameter("s1.query", segments[i + 2]);
    469                             }
    470                             else if (serviceName.equals("FieldQuery"))
    471                             {
    472                                 gRequest.setParameter("s1.fqv", segments[i + 2]);
    473                             }
    474                             else if (serviceName.equals("AdvancedFieldQuery"))
    475                             {
    476                                 gRequest.setParameter("s1.fqv", segments[i + 2]);
    477                             }
    478                         }
    479                     }
    480                     if (additionalParameters != null)
    481                     {
    482                         for (int j = 0; j < additionalParameters.length; j++)
    483                         {
    484                             if (gRequest.getParameter(additionalParameters[j]) == null)
    485                             {
    486                                 gRequest.setParameter(additionalParameters[j], defaultParamValues[j]);
    487                             }
    488                         }
    489                     }
    490                 }
    491             }
    492 
    493             chain.doFilter(gRequest, response);
    494         }
    495         else
    496         {
    497             //Will this ever happen?
    498             System.err.println("The request was not an HttpServletRequest");
    499         }
    500     }
    501 
    502     private boolean isURLRestricted(String url)
    503     {
    504         for (String restrictedURL : _restrictedURLs)
    505         {
    506             if (url.matches(".*" + restrictedURL + ".*"))
    507             {
    508                 return true;
    509             }
    510         }
    511 
    512         return false;
    513     }
    514 
     408          }
     409        //PAGE
     410        else if (segments[i].equals(PAGE_PATH) && (i + 1) < segments.length)
     411          {
     412        gRequest.setParameter(GSParams.SUBACTION, segments[i + 1]);
     413
     414        additionalParameters = new String[] { GSParams.ACTION };
     415        defaultParamValues = new String[] { "p" };
     416          }
     417        //SYSTEM
     418        else if (segments[i].equals(SYSTEM_PATH) && (i + 1) < segments.length)
     419          {
     420        String sa = segments[i + 1];
     421        if (sa.equals(SYSTEM_SUBACTION_CONFIGURE) || sa.equals(SYSTEM_SUBACTION_RECONFIGURE))
     422          {
     423            sa = "c";
     424          }
     425        else if (sa.equals(SYSTEM_SUBACTION_ACTIVATE))
     426          {
     427            sa = "a";
     428          }
     429        else if (sa.equals(SYSTEM_SUBACTION_DEACTIVATE))
     430          {
     431            sa = "d";
     432          }
     433
     434        if (sa.equals("c") && (i + 2) < segments.length)
     435          {
     436            gRequest.setParameter(GSParams.SYSTEM_CLUSTER, segments[i + 2]);
     437          }
     438
     439        if (sa.equals("a") && (i + 2) < segments.length)
     440          {
     441            gRequest.setParameter(GSParams.SYSTEM_MODULE_TYPE, "collection");
     442            gRequest.setParameter(GSParams.SYSTEM_MODULE_NAME, segments[i + 2]);
     443          }
     444
     445        if (sa.equals("d") && (i + 2) < segments.length)
     446          {
     447            gRequest.setParameter(GSParams.SYSTEM_CLUSTER, segments[i + 2]);
     448          }
     449
     450        gRequest.setParameter(GSParams.SUBACTION, sa);
     451
     452        additionalParameters = new String[] { GSParams.ACTION };
     453        defaultParamValues = new String[] { "s" };
     454          }
     455        //ADMIN
     456        else if (segments[i].equals("admin") && (i + 1) < segments.length)
     457          {
     458        String pageName = segments[i + 1];
     459
     460        gRequest.setParameter("s1.authpage", pageName);
     461
     462        additionalParameters = new String[] { GSParams.ACTION, GSParams.REQUEST_TYPE, GSParams.SUBACTION, GSParams.SERVICE };
     463        defaultParamValues = new String[] { "g", "r", "authen", "Authentication" };
     464          }
     465        //BROWSE
     466        else if (segments[i].equals(BROWSE_PATH) && (i + 1) < segments.length)
     467          {
     468        String cl = "";
     469        for (int j = 1; (i + j) < segments.length; j++)
     470          {
     471            String currentSegment = segments[i + j].replace("CL", "").replace("cl", "");
     472            if (currentSegment.contains("."))
     473              {
     474            String[] subsegments = currentSegment.split("\\.");
     475            for (String subsegment : subsegments)
     476              {
     477                subsegment = subsegment.replace("CL", "").replace("cl", "");
     478
     479                if (cl.length() > 0)
     480                  {
     481                cl += ".";
     482                  }
     483
     484                if (subsegment.length() > 0)
     485                  {
     486                cl += subsegment;
     487                  }
     488              }
     489            continue;
     490              }
     491            if (!currentSegment.matches("^(CL|cl)?\\d+$"))
     492              {
     493            continue;
     494              }
     495
     496            if (cl.length() > 0)
     497              {
     498            cl += ".";
     499              }
     500
     501            cl += currentSegment;
     502          }
     503
     504        gRequest.setParameter("cl", "CL" + cl);
     505
     506        additionalParameters = new String[] { GSParams.ACTION, GSParams.REQUEST_TYPE, GSParams.SERVICE };
     507        defaultParamValues = new String[] { "b", "s", "ClassifierBrowse" };
     508          }
     509        //QUERY
     510        else if (segments[i].equals(SEARCH_PATH))
     511          {
     512        String serviceName = "";
     513        if ((i + 1) < segments.length)
     514          {
     515            serviceName = segments[i + 1];
     516            gRequest.setParameter("s", serviceName);
     517
     518            additionalParameters = new String[] { GSParams.ACTION, GSParams.SUBACTION, GSParams.REQUEST_TYPE };
     519            defaultParamValues = new String[] { "q", "", "d" };
     520          }
     521        if ((i + 2) < segments.length)
     522          {
     523            if (serviceName.equals("TextQuery") || serviceName.equals("RawQuery"))
     524              {
     525
     526            gRequest.setParameter("s1.query", segments[i + 2]);
     527              }
     528            else if (serviceName.equals("FieldQuery"))
     529              {
     530            gRequest.setParameter("s1.fqv", segments[i + 2]);
     531              }
     532            else if (serviceName.equals("AdvancedFieldQuery"))
     533              {
     534            gRequest.setParameter("s1.fqv", segments[i + 2]);
     535              }
     536          }
     537          }
     538        if (additionalParameters != null)
     539          {
     540        for (int j = 0; j < additionalParameters.length; j++)
     541          {
     542            if (gRequest.getParameter(additionalParameters[j]) == null)
     543              {
     544            gRequest.setParameter(additionalParameters[j], defaultParamValues[j]);
     545              }
     546          }
     547          }
     548      }
     549      }
     550
     551    chain.doFilter(gRequest, response);
     552  }
     553
     554  private boolean isURLRestricted(String url)
     555  {
     556    for (String restrictedURL : _restrictedURLs)
     557      {
     558    if (url.matches(".*" + restrictedURL + ".*"))
     559      {
     560        return true;
     561      }
     562      }
     563
     564    return false;
     565  }
     566
     567  private String queryMRforDOCID(MessageRouter gsRouter, String collection, String assocfiledir) {
     568    Document gsDoc = XMLConverter.newDOM();
     569
     570    Element metaMessage = gsDoc.createElement(GSXML.MESSAGE_ELEM);
     571    Element metaRequest = GSXML.createBasicRequest(gsDoc, GSXML.REQUEST_TYPE_PROCESS, collection + "/" + METADATA_RETRIEVAL_SERVICE, new UserContext());
     572    metaMessage.appendChild(metaRequest);
     573
     574    Element paramList = gsDoc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
     575    metaRequest.appendChild(paramList);
     576   
     577    Element param = gsDoc.createElement(GSXML.PARAM_ELEM);   
     578    param.setAttribute(GSXML.NAME_ATT, "metadata");
     579    param.setAttribute(GSXML.VALUE_ATT, "contains");
     580    paramList.appendChild(param);
     581
     582    Element docList = gsDoc.createElement(GSXML.DOC_NODE_ELEM + GSXML.LIST_MODIFIER);
     583    metaRequest.appendChild(docList);
     584
     585    Element doc = gsDoc.createElement(GSXML.DOC_NODE_ELEM);
     586    doc.setAttribute(GSXML.NODE_ID_ATT, assocfiledir);
     587    docList.appendChild(doc);
     588   
     589    Element metaResponse = (Element) gsRouter.process(metaMessage);
     590   
     591    NodeList metadataList = metaResponse.getElementsByTagName(GSXML.METADATA_ELEM);
     592    if (metadataList.getLength() == 0) {
     593     
     594      _logger.error("Could not find the document related to this url");
     595      return null;
     596    }
     597     
     598    Element metadata = (Element) metadataList.item(0);
     599    String document = metadata.getTextContent();
     600    if (document != null && document.equals("")) {
     601      document = null;
     602    }
     603    return document;
     604     
     605 
     606  }
     607 
    515608}
Note: See TracChangeset for help on using the changeset viewer.