Java Code Examples for org.apache.solr.request.SolrRequestInfo#getRequestInfo()

The following examples show how to use org.apache.solr.request.SolrRequestInfo#getRequestInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpParamDelegationTokenPlugin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private Optional<String> getPrincipal() {
  SolrRequestInfo reqInfo = SolrRequestInfo.getRequestInfo();
  String usr;
  if (reqInfo != null) {
    Principal principal = reqInfo.getUserPrincipal();
    if (principal == null) {
      //this had a request but not authenticated
      //so we don't not need to set a principal
      return Optional.empty();
    } else {
      usr = principal.getName();
    }
  } else {
    if (!isSolrThread()) {
      //if this is not running inside a Solr threadpool (as in testcases)
      // then no need to add any header
      return Optional.empty();
    }
    //this request seems to be originated from Solr itself
    usr = "$"; //special name to denote the user is the node itself
  }
  return Optional.of(usr);
}
 
Example 2
Source File: ScoreJoinQParserPlugin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, org.apache.lucene.search.ScoreMode scoreMode, float boost) throws IOException {
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();

  CoreContainer container = info.getReq().getCore().getCoreContainer();

  final SolrCore fromCore = container.getCore(fromIndex);

  if (fromCore == null) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Cross-core join: no such core " + fromIndex);
  }
  RefCounted<SolrIndexSearcher> fromHolder = null;
  fromHolder = fromCore.getRegisteredSearcher();
  final Query joinQuery;
  try {
    joinQuery = JoinUtil.createJoinQuery(fromField, true,
        toField, fromQuery, fromHolder.get(), this.scoreMode);
  } finally {
    fromCore.close();
    fromHolder.decref();
  }
  return joinQuery.rewrite(searcher.getIndexReader()).createWeight(searcher, scoreMode, boost);
}
 
Example 3
Source File: CollapsingQParserPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public DelegatingCollector getFilterCollector(IndexSearcher indexSearcher) {
  try {

    SolrIndexSearcher searcher = (SolrIndexSearcher)indexSearcher;
    CollectorFactory collectorFactory = new CollectorFactory();
    //Deal with boosted docs.
    //We have to deal with it here rather then the constructor because
    //because the QueryElevationComponent runs after the Queries are constructed.

    IntIntHashMap boostDocsMap = null;
    @SuppressWarnings({"rawtypes"})
    Map context = null;
    SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
    if(info != null) {
      context = info.getReq().getContext();
    }

    if(this.boosted == null && context != null) {
      this.boosted = (Set<BytesRef>)context.get(QueryElevationComponent.BOOSTED);
    }

    boostDocsMap = QueryElevationComponent.getBoostDocs(searcher, this.boosted, context);
    return collectorFactory.getCollector(this.collapseField,
                                         this.groupHeadSelector,
                                         this.sortSpec,
                                         this.nullPolicy,
                                         this.hint,
                                         this.needsScores4Collapsing,
                                         this.needsScores,
                                         this.size,
                                         boostDocsMap,
                                         searcher);

  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 4
Source File: DateMathParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * @param now The current time. If null, it defaults to {@link SolrRequestInfo#getNOW()}.
 *            otherwise the current time is assumed.
 * @param tz The TimeZone used for rounding (to determine when hours/days begin).  If null, then this method defaults
 *           to the value dictated by the SolrRequestInfo if it exists -- otherwise it uses UTC.
 * @see #DEFAULT_MATH_TZ
 * @see Calendar#getInstance(TimeZone,Locale)
 * @see SolrRequestInfo#getClientTimeZone
 */
public DateMathParser(Date now, TimeZone tz) {
  this.now = now;// potentially null; it's okay

  if (null == tz) {
    SolrRequestInfo reqInfo = SolrRequestInfo.getRequestInfo();
    tz = (null != reqInfo) ? reqInfo.getClientTimeZone() : DEFAULT_MATH_TZ;
  }
  this.zone = (null != tz) ? tz : DEFAULT_MATH_TZ;
}
 
Example 5
Source File: ResponseBuilder.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public ResponseBuilder(SolrQueryRequest req, SolrQueryResponse rsp, List<SearchComponent> components)
{
  this.req = req;
  this.rsp = rsp;
  this.components = components;
  this.requestInfo = SolrRequestInfo.getRequestInfo();
}
 
Example 6
Source File: AbstractReRankQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public TopDocsCollector getTopDocsCollector(int len, QueryCommand cmd, IndexSearcher searcher) throws IOException {
  if(this.boostedPriority == null) {
    SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
    if(info != null) {
      Map context = info.getReq().getContext();
      this.boostedPriority = (Set<BytesRef>)context.get(QueryElevationComponent.BOOSTED);
    }
  }

  return new ReRankCollector(reRankDocs, len, reRankQueryRescorer, cmd, searcher, boostedPriority);
}
 
Example 7
Source File: ScoreJoinQParserPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, org.apache.lucene.search.ScoreMode scoreMode, float boost) throws IOException {
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  final Query jq = JoinUtil.createJoinQuery(fromField, true,
      toField, fromQuery, info.getReq().getSearcher(), this.scoreMode);
  return jq.rewrite(searcher.getIndexReader()).createWeight(searcher, scoreMode, boost);
}
 
Example 8
Source File: ValueSourceParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public FunctionValues getValues(@SuppressWarnings({"rawtypes"})Map context
        , LeafReaderContext readerContext) throws IOException {
  if (context.get(this) == null) {
    SolrRequestInfo requestInfo = SolrRequestInfo.getRequestInfo();
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "testfunc: unweighted value source detected.  delegate="+source + " request=" + (requestInfo==null ? "null" : requestInfo.getReq()));
  }
  return source.getValues(context, readerContext);
}
 
Example 9
Source File: AlfrescoReRankQParserPlugin.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
public TopDocsCollector getTopDocsCollector(int len, QueryCommand cmd, IndexSearcher searcher) throws IOException {

            if(this.boostedPriority == null) {
                SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
                if(info != null) {
                    Map context = info.getReq().getContext();
                    this.boostedPriority = (Map<BytesRef, Integer>)context.get(QueryElevationComponent.BOOSTED_PRIORITY);
                }
            }

            return new ReRankCollector(reRankDocs, length, reRankQuery, reRankWeight, cmd, searcher, boostedPriority, scale);
        }
 
Example 10
Source File: AnalyticsQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public DelegatingCollector getFilterCollector(IndexSearcher searcher) {
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  ResponseBuilder rb = null;
  if(info != null) {
    rb = info.getResponseBuilder();
  }

  if(rb == null) {
    //This is the autowarming case.
    return new DelegatingCollector();
  } else {
    return getAnalyticsCollector(rb, searcher);
  }
}
 
Example 11
Source File: AnalyticsQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Use this constructor for distributed analytics.
 * @param mergeStrategy defines the distributed merge strategy for this AnalyticsQuery
 **/

public AnalyticsQuery(MergeStrategy mergeStrategy){
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  ResponseBuilder rb = info.getResponseBuilder();
  rb.addMergeStrategy(mergeStrategy);
}
 
Example 12
Source File: SolrIndexSearcher.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public CollectionStatistics collectionStatistics(String field) throws IOException {
  final SolrRequestInfo reqInfo = SolrRequestInfo.getRequestInfo();
  if (reqInfo != null) {
    final StatsSource statsSrc = (StatsSource) reqInfo.getReq().getContext().get(STATS_SOURCE);
    if (statsSrc != null) {
      return statsSrc.collectionStatistics(this, field);
    }
  }
  return localCollectionStatistics(field);
}
 
Example 13
Source File: SolrIndexSearcher.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public TermStatistics termStatistics(Term term, int docFreq, long totalTermFreq) throws IOException {
  final SolrRequestInfo reqInfo = SolrRequestInfo.getRequestInfo();
  if (reqInfo != null) {
    final StatsSource statsSrc = (StatsSource) reqInfo.getReq().getContext().get(STATS_SOURCE);
    if (statsSrc != null) {
      return statsSrc.termStatistics(this, term, docFreq, totalTermFreq);
    }
  }
  return localTermStatistics(term, docFreq, totalTermFreq);
}
 
Example 14
Source File: KerberosPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean interceptInternodeRequest(Request request) {
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  if (info != null && (info.getAction() == SolrDispatchFilter.Action.FORWARD ||
      info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {
    if (info.getUserPrincipal() != null) {
      if (log.isInfoEnabled()) {
        log.info("Setting original user principal: {}", info.getUserPrincipal().getName());
      }
      request.header(ORIGINAL_USER_PRINCIPAL_HEADER, info.getUserPrincipal().getName());
      return true;
    }
  }
  return false;
}
 
Example 15
Source File: KerberosPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean interceptInternodeRequest(HttpRequest httpRequest, HttpContext httpContext) {
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  if (info != null && (info.getAction() == SolrDispatchFilter.Action.FORWARD ||
      info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {
    if (info.getUserPrincipal() != null) {
      if (log.isInfoEnabled()) {
        log.info("Setting original user principal: {}", info.getUserPrincipal().getName());
      }
      httpRequest.setHeader(ORIGINAL_USER_PRINCIPAL_HEADER, info.getUserPrincipal().getName());
      return true;
    }
  }
  return false;
}
 
Example 16
Source File: SolrCmdDistributor.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void submit(final Req req, boolean isCommit) throws IOException {
  // Copy user principal from the original request to the new update request, for later authentication interceptor use
  if (SolrRequestInfo.getRequestInfo() != null) {
    req.uReq.setUserPrincipal(SolrRequestInfo.getRequestInfo().getReq().getUserPrincipal());
  }

  Tracer tracer = GlobalTracer.getTracer();
  Span parentSpan = tracer.activeSpan();
  if (parentSpan != null) {
    tracer.inject(parentSpan.context(), Format.Builtin.HTTP_HEADERS,
        new SolrRequestCarrier(req.uReq));
  }

  if (req.synchronous) {
    blockAndDoRetries();

    try {
      req.uReq.setBasePath(req.node.getUrl());
      clients.getHttpClient().request(req.uReq);
    } catch (Exception e) {
      SolrException.log(log, e);
      Error error = new Error();
      error.e = e;
      error.req = req;
      if (e instanceof SolrException) {
        error.statusCode = ((SolrException) e).code();
      }
      errors.add(error);
    }
    
    return;
  }
  
  if (log.isDebugEnabled()) {
    log.debug("sending update to {} retry: {} {} params {}"
        , req.node.getUrl(), req.retries, req.cmd, req.uReq.getParams());
  }
  
  if (isCommit) {
    // a commit using ConncurrentUpdateSolrServer is not async,
    // so we make it async to prevent commits from happening
    // serially across multiple nodes
    pending.add(completionService.submit(() -> {
      doRequest(req);
      return null;
    }));
  } else {
    doRequest(req);
  }
}
 
Example 17
Source File: JoinQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public JoinQueryWeight(SolrIndexSearcher searcher, ScoreMode scoreMode, float boost) {
  super(JoinQuery.this, boost);
  this.scoreMode = scoreMode;
  this.fromSearcher = searcher;
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  if (info != null) {
    rb = info.getResponseBuilder();
  }

  if (fromIndex == null) {
    this.fromSearcher = searcher;
  } else {
    if (info == null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Cross-core join must have SolrRequestInfo");
    }

    CoreContainer container = searcher.getCore().getCoreContainer();
    final SolrCore fromCore = container.getCore(fromIndex);

    if (fromCore == null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Cross-core join: no such core " + fromIndex);
    }

    if (info.getReq().getCore() == fromCore) {
      // if this is the same core, use the searcher passed in... otherwise we could be warming and
      // get an older searcher from the core.
      fromSearcher = searcher;
    } else {
      // This could block if there is a static warming query with a join in it, and if useColdSearcher is true.
      // Deadlock could result if two cores both had useColdSearcher and had joins that used eachother.
      // This would be very predictable though (should happen every time if misconfigured)
      fromRef = fromCore.getSearcher(false, true, null);

      // be careful not to do anything with this searcher that requires the thread local
      // SolrRequestInfo in a manner that requires the core in the request to match
      fromSearcher = fromRef.get();
    }

    if (fromRef != null) {
      final RefCounted<SolrIndexSearcher> ref = fromRef;
      info.addCloseHook(new Closeable() {
        @Override
        public void close() {
          ref.decref();
        }
      });
    }

    info.addCloseHook(new Closeable() {
      @Override
      public void close() {
        fromCore.close();
      }
    });

  }
  this.toSearcher = searcher;
}
 
Example 18
Source File: ShardRequestor.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public ShardResponse call() throws Exception {

  ShardResponse srsp = new ShardResponse();
  if (sreq.nodeName != null) {
    srsp.setNodeName(sreq.nodeName);
  }
  srsp.setShardRequest(sreq);
  srsp.setShard(shard);
  SimpleSolrResponse ssr = new SimpleSolrResponse();
  srsp.setSolrResponse(ssr);
  long startTime = System.nanoTime();

  try {
    params.remove(CommonParams.WT); // use default (currently javabin)
    params.remove(CommonParams.VERSION);

    QueryRequest req = httpShardHandler.makeQueryRequest(sreq, params, shard);
    if (tracer != null && span != null) {
      tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new SolrRequestCarrier(req));
    }
    req.setMethod(SolrRequest.METHOD.POST);
    SolrRequestInfo requestInfo = SolrRequestInfo.getRequestInfo();
    if (requestInfo != null) req.setUserPrincipal(requestInfo.getReq().getUserPrincipal());

    // no need to set the response parser as binary is the defaultJab
    // req.setResponseParser(new BinaryResponseParser());

    // if there are no shards available for a slice, urls.size()==0
    if (urls.size() == 0) {
      // TODO: what's the right error code here? We should use the same thing when
      // all of the servers for a shard are down.
      throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "no servers hosting shard: " + shard);
    }

    if (urls.size() <= 1) {
      String url = urls.get(0);
      srsp.setShardAddress(url);
      ssr.nl = httpShardHandler.request(url, req);
    } else {
      LBSolrClient.Rsp rsp = httpShardHandler.httpShardHandlerFactory.makeLoadBalancedRequest(req, urls);
      ssr.nl = rsp.getResponse();
      srsp.setShardAddress(rsp.getServer());
    }
  } catch (ConnectException cex) {
    srsp.setException(cex); //????
  } catch (Exception th) {
    srsp.setException(th);
    if (th instanceof SolrException) {
      srsp.setResponseCode(((SolrException) th).code());
    } else {
      srsp.setResponseCode(-1);
    }
  }

  ssr.elapsedTime = TimeUnit.MILLISECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);

  return httpShardHandler.transfomResponse(sreq, srsp, shard);
}
 
Example 19
Source File: PKIAuthenticationPlugin.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
SolrRequestInfo getRequestInfo() {
  return SolrRequestInfo.getRequestInfo();
}