SolrDispatchFilter.java

来源:互联网 发布:java json 大括号转义 编辑:程序博客网 时间:2024/06/04 21:31
  1. /** 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements.  See the NOTICE file distributed with 
  4.  * this work for additional information regarding copyright ownership. 
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  * (the "License"); you may not use this file except in compliance with 
  7.  * the License.  You may obtain a copy of the License at 
  8.  * 
  9.  *     http://www.apache.org/licenses/LICENSE-2.0 
  10.  * 
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, 
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  * See the License for the specific language governing permissions and 
  15.  * limitations under the License. 
  16.  */  
  17.   
  18. package org.apache.solr.servlet;  
  19.   
  20. import java.io.IOException;  
  21. import java.io.Writer;  
  22. import java.io.PrintWriter;  
  23. import java.io.StringWriter;  
  24. import java.io.OutputStreamWriter;  
  25. import java.io.ByteArrayInputStream;  
  26. import java.nio.charset.Charset;  
  27. import java.util.Map;  
  28. import java.util.WeakHashMap;  
  29. import org.slf4j.Logger;  
  30. import org.slf4j.LoggerFactory;  
  31. import org.xml.sax.InputSource;  
  32.   
  33. import javax.servlet.Filter;  
  34. import javax.servlet.FilterChain;  
  35. import javax.servlet.FilterConfig;  
  36. import javax.servlet.ServletException;  
  37. import javax.servlet.ServletRequest;  
  38. import javax.servlet.ServletResponse;  
  39. import javax.servlet.http.HttpServletRequest;  
  40. import javax.servlet.http.HttpServletResponse;  
  41.   
  42. import org.apache.solr.common.SolrException;  
  43. import org.apache.solr.common.util.NamedList;  
  44. import org.apache.solr.common.util.SimpleOrderedMap;  
  45. import org.apache.solr.common.params.CommonParams;  
  46. import org.apache.solr.common.util.FastWriter;  
  47. import org.apache.solr.common.util.ContentStreamBase;  
  48. import org.apache.solr.core.*;  
  49. import org.apache.solr.request.*;  
  50. import org.apache.solr.response.BinaryQueryResponseWriter;  
  51. import org.apache.solr.response.QueryResponseWriter;  
  52. import org.apache.solr.response.SolrQueryResponse;  
  53. import org.apache.solr.servlet.cache.HttpCacheHeaderUtil;  
  54. import org.apache.solr.servlet.cache.Method;  
  55.   
  56. /** 
  57.  * This filter looks at the incoming URL maps them to handlers defined in solrconfig.xml 
  58.  * 检查所有的请求路径将他们映射到在solrconfig.xml中定义的处理器上 
  59.  * @since solr 1.2 
  60.  */  
  61. public class SolrDispatchFilter implements Filter  
  62. {  
  63.   final Logger log = LoggerFactory.getLogger(SolrDispatchFilter.class);  
  64.   
  65.   protected CoreContainer cores;/** 这是最关键的一个属性他是但前web应用中为一个用于存放不同solrcore实例的容器 
  66.                                     solrcore是用于存放索引以及如何进行检索服务的一个core类*/  
  67.   protected String pathPrefix = null/** strip this from the beginning of a path 忽略路径中的这段字符窜*/  
  68.   protected String abortErrorMessage = null;  
  69.   protected String solrConfigFilename = null;/** 对应的某个solrcore实例的配置文件名字*/  
  70.   protected final Map<SolrConfig, SolrRequestParsers> parsers = new WeakHashMap<SolrConfig, SolrRequestParsers>();/** 某个solrcore实例的请求分析器的一个集合*/  
  71.   protected final SolrRequestParsers adminRequestParser;/** 对应到管理CoreContainer的那个处理器 */  
  72.     
  73.   private static final Charset UTF8 = Charset.forName("UTF-8");  
  74.     
  75.   /** 在实例话这个对象的时候其实做了很多事情他找到了我们的solrhome主目录并且开始加载一些重要的配置文件 */  
  76.   public SolrDispatchFilter() {  
  77.     try {  
  78.       adminRequestParser = new SolrRequestParsers(new Config(null,"solr",new InputSource(new ByteArrayInputStream("<root/>".getBytes("UTF-8"))),"") );  
  79.     } catch (Exception e) {  
  80.       //unlikely  
  81.       throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,e);  
  82.     }  
  83.   }  
  84.     
  85.   /** 实例化CoreContainer容器将所有的solrCore实例装到容器中 */  
  86.   public void init(FilterConfig config) throws ServletException  
  87.   {  
  88.     log.info("SolrDispatchFilter.init()");  
  89.    
  90.     boolean abortOnConfigurationError = true;  
  91.     CoreContainer.Initializer init = createInitializer();/** 初始化CoreContianer的内部类 */  
  92.     try {  
  93.       /** 配置当前web应用上下文参数*/  
  94.       this.pathPrefix = config.getInitParameter( "path-prefix" );/** 可以在过滤器配置文件中指定好只针对该特殊的请求进行一个过滤*/  
  95.       init.setSolrConfigFilename(config.getInitParameter("solrconfig-filename"));/** 指定好solr配置文件的名字是什么 */  
  96.   
  97.       this.cores = init.initialize();/** 正式将CoreContainer进行一个初始化并创建实例对象然后将所有的solrCore实例放到容器中 */  
  98.       abortOnConfigurationError = init.isAbortOnConfigurationError();  
  99.       log.info("user.dir=" + System.getProperty("user.dir"));  
  100.     }  
  101.     catch( Throwable t ) {  
  102.       /** 捕获这个异常我们的过滤器将会继续工作 */  
  103.       log.error( "Could not start Solr. Check solr/home property", t);  
  104.       SolrConfig.severeErrors.add( t );  
  105.       SolrCore.log( t );  
  106.     }  
  107.   
  108.     /** 如果服务器报错可以选择性的忽略该错误 */  
  109.     if( abortOnConfigurationError && SolrConfig.severeErrors.size() > 0 ) {  
  110.       StringWriter sw = new StringWriter();  
  111.       PrintWriter out = new PrintWriter( sw );  
  112.       out.println( "Severe errors in solr configuration.\n" );  
  113.       out.println( "Check your log files for more detailed information on what may be wrong.\n" );  
  114.       out.println( "If you want solr to continue after configuration errors, change: \n");  
  115.       out.println( " <abortOnConfigurationError>false</abortOnConfigurationError>\n" );  
  116.       out.println( "in "+init.getSolrConfigFilename()+"\n" );  
  117.   
  118.       for( Throwable t : SolrConfig.severeErrors ) {  
  119.         out.println( "-------------------------------------------------------------" );  
  120.         t.printStackTrace( out );  
  121.       }  
  122.       out.flush();  
  123.   
  124.       // Servlet containers behave slightly differently if you throw an exception during   
  125.       // initialization.  Resin will display that error for every page, jetty prints it in  
  126.       // the logs, but continues normally.  (We will see a 404 rather then the real error)  
  127.       // rather then leave the behavior undefined, lets cache the error and spit it out   
  128.       // for every request.  
  129.       abortErrorMessage = sw.toString();  
  130.       //throw new ServletException( abortErrorMessage );  
  131.     }  
  132.   
  133.     log.info("SolrDispatchFilter.init() done");  
  134.   }  
  135.   
  136.   /** Method to override to change how CoreContainer initialization is performed. */  
  137.   protected CoreContainer.Initializer createInitializer() {  
  138.     return new CoreContainer.Initializer();  
  139.   }  
  140.     
  141.   /** 在销毁这个过滤器的时候同时将释放所有的索引实例的文件流 */  
  142.   public void destroy() {  
  143.     if (cores != null) {  
  144.       cores.shutdown();  
  145.       cores = null;  
  146.     }      
  147.   }  
  148.     
  149.   /** 将对特定的需要全文检索的请求进行一个过滤然后提供全文检索服务 */  
  150.   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
  151.     if( abortErrorMessage != null ) {  
  152.       ((HttpServletResponse)response).sendError( 500, abortErrorMessage );  
  153.       return;  
  154.     }  
  155.     /** 下面这几个变量是solr提供全文解锁服务的上下文参数*/  
  156.     if( request instanceof HttpServletRequest) {  
  157.       HttpServletRequest req = (HttpServletRequest)request;  
  158.       HttpServletResponse resp = (HttpServletResponse)response;  
  159.       SolrRequestHandler handler = null;/** 当前请求所对应的请求处理器*/  
  160.       SolrQueryRequest solrReq = null/** 当前的查询请求*/  
  161.       SolrCore core = null/** 当前请求资源所对应的solrCore实例*/  
  162.       String corename = ""/** 当前请求所对应的solrCore实例的名字*/  
  163.       try {  
  164.         /** 将我们的CoreContainer容器以键值对的形式保存到当前这个请求的map集合中 */  
  165.         req.setAttribute("org.apache.solr.CoreContainer", cores);  
  166.         String path = req.getServletPath();/**http://host_name:port/webapp_name/solrcore_name/admin/这样一段URL那么path为solrcore_name/admin/ */  
  167.         if( req.getPathInfo() != null ) {  
  168.           // this lets you handle /update/commit when /update is a servlet  
  169.           path += req.getPathInfo();  
  170.         }  
  171.         /** 如果路径是http://host_name:port/webapp_name/test/select/... 为了能够让solr知道这个请求URL有检索需要首先要把这个test/这段字符窜给截取*/  
  172.         if( pathPrefix != null && path.startsWith( pathPrefix ) ) {  
  173.           path = path.substring( pathPrefix.length() );  
  174.         }  
  175.   
  176.         /** 根据请求参数得到管理CoreContainer这个容器的路径的名字*/  
  177.         String alternate = cores.getManagementPath();  
  178.         if (alternate != null && path.startsWith(alternate)) {  
  179.           path = path.substring(0, alternate.length());  
  180.         }  
  181.         // unused feature ?  
  182.         int idx = path.indexOf( ':' );  
  183.         if( idx > 0 ) {  
  184.           // save the portion after the ':' for a 'handler' path parameter  
  185.           path = path.substring( 0, idx );  
  186.         }  
  187.   
  188.         /** 检查是否需要去管理页面 */  
  189.         if( path.equals( cores.getAdminPath() ) ) {  
  190.           handler = cores.getMultiCoreHandler();  
  191.           solrReq =  adminRequestParser.parse(null,path, req);  
  192.           handleAdminRequest(req, response, handler, solrReq);  
  193.           return;  
  194.         }  
  195.         else {  
  196.           /** 另外,我们应该从路径中找到solrCore的名字*/  
  197.           idx = path.indexOf( "/"1 );  
  198.           if( idx > 1 ) {  
  199.             /** 通过请求参数得到solrCore实例的名字*/  
  200.             corename = path.substring( 1, idx );  
  201.             core = cores.getCore(corename);  
  202.             if (core != null) {  
  203.               path = path.substring( idx );/** 将路径中的solrCore名字截取掉 */  
  204.             }  
  205.           }  
  206.           if (core == null) {  
  207.             corename = "";  
  208.             core = cores.getCore("");  
  209.           }  
  210.         }  
  211.   
  212.         /** 使用一个有效的solrcore实例*/  
  213.         if( core != null ) {  
  214.           final SolrConfig config = core.getSolrConfig();  
  215.           /** 从solrCore的实例缓存中得到一个请求解析对象或者创建一个新的缓存起来*/  
  216.           SolrRequestParsers parser = null;  
  217.           parser = parsers.get(config);  
  218.           if( parser == null ) {  
  219.             parser = new SolrRequestParsers(config);  
  220.             parsers.put(config, parser );/** 将加载这个solrCore实例所配置的所有请求解析器对象*/  
  221.           }  
  222.   
  223.           /** 如果没有设置请求处理器的类型从请求路径得到处理器*/  
  224.           /** 我们已经选择了一个请求处理器*/  
  225.           if( handler == null && path.length() > 1 ) { /**没有匹配空窜或者/是有效字符 */  
  226.             handler = core.getRequestHandler( path );  
  227.             /** 没有处理器但是允许处理查询*/  
  228.             if( handler == null && parser.isHandleSelect() ) {  
  229.               if"/select".equals( path ) || "/select/".equals( path ) ) {/**是一个查询请求 */  
  230.                 solrReq = parser.parse( core, path, req );/** 得到请求查询对象 */  
  231.                 String qt = solrReq.getParams().get( CommonParams.QT );/** 得到查询类型也就是对应的查询请求处理器的名字 */  
  232.                 handler = core.getRequestHandler( qt );/** 根据查询类型得到请求查询处理器对象 */  
  233.                 if( handler == null ) {  
  234.                   throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "unknown handler: "+qt);/**如果发生异常表示没有对应的请求查询处理器 */  
  235.                 }  
  236.               }  
  237.             }  
  238.           }  
  239.   
  240.           // With a valid handler and a valid core...  
  241.           /** 使用一个有效的处理器和有效的solrCore实例*/  
  242.           if( handler != null ) {  
  243.             // if not a /select, create the request  
  244.             if( solrReq == null ) {  
  245.               solrReq = parser.parse( core, path, req );  
  246.             }  
  247.   
  248.             final Method reqMethod = Method.getMethod(req.getMethod());/** 得到http请求提交的方式*/  
  249.             HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);  
  250.             // unless we have been explicitly told not to, do cache validation  
  251.             // if we fail cache validation, execute the query  
  252.             if (config.getHttpCachingConfig().isNever304() ||  
  253.                 !HttpCacheHeaderUtil.doCacheHeaderValidation(solrReq, req, reqMethod, resp)) {  
  254.                 SolrQueryResponse solrRsp = new SolrQueryResponse();  
  255.                 /* even for HEAD requests, we need to execute the handler to 
  256.                  * ensure we don't get an error (and to make sure the correct 
  257.                  * QueryResponseWriter is selected and we get the correct 
  258.                  * Content-Type) 
  259.                  */  
  260.                 /** solr提供全文检索服务的入口*/  
  261.                 this.execute( req, handler, solrReq, solrRsp );/** 根据请求对象,根据请求参数中指定的处理器名字得到的处理器,根据响应对象, 
  262.                                                                     以及发送请求的方式对索引库进行一个读写操作 */  
  263.                 HttpCacheHeaderUtil.checkHttpCachingVeto(solrRsp, resp, reqMethod);  
  264.               // add info to http headers  
  265.               //TODO: See SOLR-232 and SOLR-267.    
  266.                 /*try { 
  267.                   NamedList solrRspHeader = solrRsp.getResponseHeader(); 
  268.                  for (int i=0; i<solrRspHeader.size(); i++) { 
  269.                    ((javax.servlet.http.HttpServletResponse) response).addHeader(("Solr-" + solrRspHeader.getName(i)), String.valueOf(solrRspHeader.getVal(i))); 
  270.                  } 
  271.                 } catch (ClassCastException cce) { 
  272.                   log.log(Level.WARNING, "exception adding response header log information", cce); 
  273.                 }*/  
  274.                QueryResponseWriter responseWriter = core.getQueryResponseWriter(solrReq);/** 将请求结果通过输出流写出到客户端*/  
  275.               writeResponse(solrRsp, response, responseWriter, solrReq, reqMethod);  
  276.             }  
  277.             return// we are done with a valid handler  
  278.           }  
  279.           // otherwise (we have a core), let's ensure the core is in the SolrCore request attribute so  
  280.           // a servlet/jsp can retrieve it  
  281.           else {  
  282.             req.setAttribute("org.apache.solr.SolrCore", core);  
  283.             // Modify the request so each core gets its own /admin  
  284.             /** 修改请求根据不同的solrcore的管理界面进行一个转发*/  
  285.             if( path.startsWith( "/admin" ) ) {  
  286.               req.getRequestDispatcher( pathPrefix == null ? path : pathPrefix + path ).forward( request, response );  
  287.               return;  
  288.             }  
  289.           }  
  290.         }  
  291.         log.debug("no handler or core retrieved for " + path + ", follow through...");  
  292.       }   
  293.       catch (Throwable ex) {  
  294.         sendError( (HttpServletResponse)response, ex );  
  295.         return;  
  296.       }   
  297.       finally {  
  298.         if( solrReq != null ) {  
  299.           solrReq.close();  
  300.         }  
  301.         if (core != null) {  
  302.           core.close();  
  303.         }  
  304.       }  
  305.     }  
  306.   
  307.     /** 让web应用处理其他请求*/  
  308.     chain.doFilter(request, response);  
  309.   }  
  310.     
  311.   /** 处理需要管理corecontainer容器的请求*/  
  312.   private void handleAdminRequest(HttpServletRequest req, ServletResponse response, SolrRequestHandler handler,  
  313.                                   SolrQueryRequest solrReq) throws IOException {  
  314.     SolrQueryResponse solrResp = new SolrQueryResponse();  
  315.     final NamedList<Object> responseHeader = new SimpleOrderedMap<Object>();  
  316.     solrResp.add("responseHeader", responseHeader);  
  317.     NamedList toLog = solrResp.getToLog();  
  318.     toLog.add("webapp", req.getContextPath());  
  319.     toLog.add("path", solrReq.getContext().get("path"));  
  320.     toLog.add("params""{" + solrReq.getParamString() + "}");  
  321.     handler.handleRequest(solrReq, solrResp);  
  322.     SolrCore.setResponseHeaderValues(handler, solrReq, solrResp);  
  323.     StringBuilder sb = new StringBuilder();  
  324.     for (int i = 0; i < toLog.size(); i++) {  
  325.       String name = toLog.getName(i);  
  326.       Object val = toLog.getVal(i);  
  327.       sb.append(name).append("=").append(val).append(" ");  
  328.     }  
  329.     QueryResponseWriter respWriter = SolrCore.DEFAULT_RESPONSE_WRITERS.get(solrReq.getParams().get(CommonParams.WT));  
  330.     if (respWriter == null) respWriter = SolrCore.DEFAULT_RESPONSE_WRITERS.get("standard");  
  331.     writeResponse(solrResp, response, respWriter, solrReq, Method.getMethod(req.getMethod()));  
  332.   }  
  333.   /** 在该请求执行往filterChain.doFilter(...)的时候将会把我们的结果添加到响应对象中*/  
  334.   private void writeResponse(SolrQueryResponse solrRsp, ServletResponse response,  
  335.                              QueryResponseWriter responseWriter, SolrQueryRequest solrReq, Method reqMethod)  
  336.           throws IOException {  
  337.     if (solrRsp.getException() != null) {  
  338.       sendError((HttpServletResponse) response, solrRsp.getException());  
  339.     } else {  
  340.       // Now write it out  
  341.       final String ct = responseWriter.getContentType(solrReq, solrRsp);  
  342.       // don't call setContentType on null  
  343.       if (null != ct) response.setContentType(ct);   
  344.   
  345.       if (Method.HEAD != reqMethod) {  
  346.         if (responseWriter instanceof BinaryQueryResponseWriter) {  
  347.           BinaryQueryResponseWriter binWriter = (BinaryQueryResponseWriter) responseWriter;  
  348.           binWriter.write(response.getOutputStream(), solrReq, solrRsp);  
  349.         } else {  
  350.           String charset = ContentStreamBase.getCharsetFromContentType(ct);  
  351.           Writer out = (charset == null || charset.equalsIgnoreCase("UTF-8"))  
  352.             ? new OutputStreamWriter(response.getOutputStream(), UTF8)  
  353.             : new OutputStreamWriter(response.getOutputStream(), charset);  
  354.           out = new FastWriter(out);  
  355.           responseWriter.write(out, solrReq, solrRsp);  
  356.           out.flush();  
  357.         }  
  358.       }  
  359.       //else http HEAD request, nothing to write out, waited this long just to get ContentType  
  360.     }  
  361.   }  
  362.   
  363.   protected void execute( HttpServletRequest req, SolrRequestHandler handler, SolrQueryRequest sreq, SolrQueryResponse rsp) {  
  364.     // a custom filter could add more stuff to the request before passing it on.  
  365.     // for example: sreq.getContext().put( "HttpServletRequest", req );  
  366.     // used for logging query stats in SolrCore.execute()  
  367.     sreq.getContext().put( "webapp", req.getContextPath() );  
  368.     sreq.getCore().execute( handler, sreq, rsp );  
  369.   }  
  370.     
  371.   protected void sendError(HttpServletResponse res, Throwable ex) throws IOException {  
  372.     int code=500;  
  373.     String trace = "";  
  374.     if( ex instanceof SolrException ) {  
  375.       code = ((SolrException)ex).code();  
  376.     }  
  377.   
  378.     // For any regular code, don't include the stack trace  
  379.     if( code == 500 || code < 100 ) {  
  380.       StringWriter sw = new StringWriter();  
  381.       ex.printStackTrace(new PrintWriter(sw));  
  382.       trace = "\n\n"+sw.toString();  
  383.   
  384.       SolrException.logOnce(log,null,ex );  
  385.   
  386.       // non standard codes have undefined results with various servers  
  387.       if( code < 100 ) {  
  388.         log.warn( "invalid return code: "+code );  
  389.         code = 500;  
  390.       }  
  391.     }  
  392.     res.sendError( code, ex.getMessage() + trace );  
  393.   }  
  394.   
  395.   //---------------------------------------------------------------------  
  396.   //---------------------------------------------------------------------  
  397.   
  398.   /** 
  399.    * Set the prefix for all paths.  This is useful if you want to apply the 
  400.    * filter to something other then /*, perhaps because you are merging this 
  401.    * filter into a larger web application. 
  402.    * 
  403.    * For example, if web.xml specifies: 
  404.    * 
  405.    * <filter-mapping> 
  406.    *  <filter-name>SolrRequestFilter</filter-name> 
  407.    *  <url-pattern>/xxx/*</url-pattern> 
  408.    * </filter-mapping> 
  409.    * 
  410.    * Make sure to set the PathPrefix to "/xxx" either with this function 
  411.    * or in web.xml. 
  412.    * 
  413.    * <init-param> 
  414.    *  <param-name>path-prefix</param-name> 
  415.    *  <param-value>/xxx</param-value> 
  416.    * </init-param> 
  417.    * 
  418.    */  
  419.   public void setPathPrefix(String pathPrefix) {  
  420.     this.pathPrefix = pathPrefix;  
  421.   }  
  422.   
  423.   public String getPathPrefix() {  
  424.     return pathPrefix;  
  425.   }  
  426. }  
0 0
原创粉丝点击