org.apache.solr.request.SolrRequestInfo Java Examples

The following examples show how to use org.apache.solr.request.SolrRequestInfo. 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: TestOverriddenPrefixQueryForCustomFieldType.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.lucene.search.QueryUtils#check
 * @see org.apache.lucene.search.QueryUtils#checkEqual
 */
protected void assertQueryEquals(final SolrQueryRequest req,
                                 final String... inputs) throws Exception {

  final Query[] queries = new Query[inputs.length];

  try {
    SolrQueryResponse rsp = new SolrQueryResponse();
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    for (int i = 0; i < inputs.length; i++) {
      queries[i] = (QParser.getParser(inputs[i], req).getQuery());
    }
  } finally {
    SolrRequestInfo.clearRequestInfo();
  }

  for (int i = 0; i < queries.length; i++) {
    org.apache.lucene.search.QueryUtils.check(queries[i]);
    for (int j = i; j < queries.length; j++) {
      org.apache.lucene.search.QueryUtils.checkEqual(queries[i], queries[j]);
    }
  }
}
 
Example #4
Source File: HttpSolrCall.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
void destroy() {
  try {
    if (solrReq != null) {
      log.debug("Closing out SolrRequest: {}", solrReq);
      solrReq.close();
    }
  } finally {
    try {
      if (core != null) core.close();
    } finally {
      if (mustClearSolrRequestInfo) {
        SolrRequestInfo.clearRequestInfo();
      }
    }
    AuthenticationPlugin authcPlugin = cores.getAuthenticationPlugin();
    if (authcPlugin != null) authcPlugin.closeRequest();
  }
}
 
Example #5
Source File: IgnoreCommitOptimizeUpdateProcessorFactoryTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
SolrQueryResponse processCommit(final String chain, boolean optimize, Boolean commitEndPoint) throws IOException {
  SolrCore core = h.getCore();
  UpdateRequestProcessorChain pc = core.getUpdateProcessingChain(chain);
  assertNotNull("No Chain named: " + chain, pc);

  SolrQueryResponse rsp = new SolrQueryResponse();
  SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams());

  if (commitEndPoint != null) {
    ((ModifiableSolrParams)req.getParams()).set(
        DistributedUpdateProcessor.COMMIT_END_POINT, commitEndPoint.booleanValue());
  }

  try {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req,rsp));
    CommitUpdateCommand cmd = new CommitUpdateCommand(req, false);
    cmd.optimize = optimize;
    UpdateRequestProcessor processor = pc.createProcessor(req, rsp);
    processor.processCommit(cmd);
  } finally {
    SolrRequestInfo.clearRequestInfo();
    req.close();
  }
  return rsp;
}
 
Example #6
Source File: RestManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Locates the RestManager using ThreadLocal SolrRequestInfo.
 */
public static RestManager getRestManager(SolrRequestInfo solrRequestInfo) {
  if (solrRequestInfo == null)
    throw new ResourceException(Status.SERVER_ERROR_INTERNAL, 
        "No SolrRequestInfo in this Thread!");

  SolrQueryRequest req = solrRequestInfo.getReq();
  RestManager restManager = 
      (req != null) ? req.getCore().getRestManager() : null;
  
  if (restManager == null)
    throw new ResourceException(Status.SERVER_ERROR_INTERNAL, 
        "No RestManager found!");
  
  return restManager;
}
 
Example #7
Source File: TestCrossCoreJoin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public String query(SolrCore core, SolrQueryRequest req) throws Exception {
  String handler = "standard";
  if (req.getParams().get("qt") != null) {
    handler = req.getParams().get("qt");
  }
  if (req.getParams().get("wt") == null){
    ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
    params.set("wt", "xml");
    req.setParams(params);
  }
  SolrQueryResponse rsp = new SolrQueryResponse();
  SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
  core.execute(core.getRequestHandler(handler), req, rsp);
  if (rsp.getException() != null) {
    throw rsp.getException();
  }
  StringWriter sw = new StringWriter(32000);
  QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
  responseWriter.write(sw, req, rsp);
  req.close();
  SolrRequestInfo.clearRequestInfo();
  return sw.toString();
}
 
Example #8
Source File: UUIDUpdateProcessorFallbackTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
SolrInputDocument processAdd(final String chain,
                             final SolrInputDocument docIn, SolrParams params)
    throws IOException {

  SolrCore core = h.getCore();
  UpdateRequestProcessorChain pc = chain == null ?
      core.getUpdateProcessorChain(params) :
      core.getUpdateProcessingChain(chain);
  assertNotNull("No Chain named: " + chain, pc);

  SolrQueryResponse rsp = new SolrQueryResponse();

  SolrQueryRequest req = new LocalSolrQueryRequest
      (core, params);
  try {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req,rsp));
    AddUpdateCommand cmd = new AddUpdateCommand(req);
    cmd.solrDoc = docIn;

    UpdateRequestProcessor processor = pc.createProcessor(req, rsp);
    processor.processAdd(cmd);

    return cmd.solrDoc;
  } finally {
    SolrRequestInfo.clearRequestInfo();
    req.close();
  }
}
 
Example #9
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 #10
Source File: DefaultValueUpdateProcessorTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Runs a document through the specified chain, and returns the final 
 * document used when the chain is completed (NOTE: some chains may 
 * modify the document in place
 */
SolrInputDocument processAdd(final String chain, 
                             final SolrInputDocument docIn) 
  throws IOException {

  SolrCore core = h.getCore();
  UpdateRequestProcessorChain pc = core.getUpdateProcessingChain(chain);
  assertNotNull("No Chain named: " + chain, pc);

  SolrQueryResponse rsp = new SolrQueryResponse();

  SolrQueryRequest req = new LocalSolrQueryRequest
    (core, new ModifiableSolrParams());
  try {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req,rsp));
    AddUpdateCommand cmd = new AddUpdateCommand(req);
    cmd.solrDoc = docIn;

    UpdateRequestProcessor processor = pc.createProcessor(req, rsp);
    processor.processAdd(cmd);

    return cmd.solrDoc;
  } finally {
    SolrRequestInfo.clearRequestInfo();
    req.close();
  }
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: TestScoreJoinQPScore.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Ignore("SOLR-7814, also don't forget cover boost at testCacheHit()")
public void testBoost() throws Exception {
  indexDataForScorring();
  ScoreMode score = ScoreMode.values()[random().nextInt(ScoreMode.values().length)];

  final SolrQueryRequest req = req("q", "{!join from=movieId_s to=id score=" + score + " b=200}title:movie", "fl", "id,score", "omitHeader", "true");
  SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, new SolrQueryResponse()));
  final Query luceneQ = QParser.getParser(req.getParams().get("q"), req).getQuery().rewrite(req.getSearcher().getSlowAtomicReader());
  assertTrue(luceneQ instanceof BoostQuery);
  float boost = ((BoostQuery) luceneQ).getBoost();
  assertEquals("" + luceneQ, Float.floatToIntBits(200), Float.floatToIntBits(boost));
  SolrRequestInfo.clearRequestInfo();
  req.close();
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
Source File: UpdateProcessorTestBase.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Runs a document through the specified chain, and returns the final
 * document used when the chain is completed (NOTE: some chains may
 * modify the document in place
 */
protected SolrInputDocument processAdd(final String chain,
                                       final SolrParams requestParams,
                                       final SolrInputDocument docIn)
  throws IOException {

  SolrCore core = h.getCore();
  UpdateRequestProcessorChain pc = core.getUpdateProcessingChain(chain);
  assertNotNull("No Chain named: " + chain, pc);

  SolrQueryResponse rsp = new SolrQueryResponse();

  SolrQueryRequest req = new LocalSolrQueryRequest(core, requestParams);
  try {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    AddUpdateCommand cmd = new AddUpdateCommand(req);
    cmd.solrDoc = docIn;

    UpdateRequestProcessor processor = pc.createProcessor(req, rsp);
    if (null != processor) {
      // test chain might be empty or short circuited.
      processor.processAdd(cmd);
    }

    return cmd.solrDoc;
  } finally {
    SolrRequestInfo.clearRequestInfo();
    req.close();
  }
}
 
Example #21
Source File: TestHarness.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a "query" using a user constructed SolrQueryRequest, and closes the request at the end.
 *
 * @param handler the name of the request handler to process the request
 * @param req the Query to process, will be closed.
 * @return The XML response to the query
 * @exception Exception any exception in the response.
 * @exception IOException if there is a problem writing the XML
 * @see LocalSolrQueryRequest
 */
public String query(String handler, SolrQueryRequest req) throws Exception {
  try {
    SolrCore core = req.getCore();
    SolrQueryResponse rsp = new SolrQueryResponse();
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    core.execute(core.getRequestHandler(handler),req,rsp);
    if (rsp.getException() != null) {
      throw rsp.getException();
    }
    QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
    if (responseWriter instanceof BinaryQueryResponseWriter) {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32000);
      BinaryQueryResponseWriter writer = (BinaryQueryResponseWriter) responseWriter;
      writer.write(byteArrayOutputStream, req, rsp);
      return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } else {
      StringWriter sw = new StringWriter(32000);
      responseWriter.write(sw,req,rsp);
      return sw.toString();
    }

  } finally {
    req.close();
    SolrRequestInfo.clearRequestInfo();
  }
}
 
Example #22
Source File: TestZKPropertiesWriter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Code copied from {@link org.apache.solr.util.TestHarness#query(String, SolrQueryRequest)} because it is not
 * <code>static</code> there (it could have been) and we do not have an instance of {@link org.apache.solr.util.TestHarness}.
 */
private static String localQuery(String handler, SolrQueryRequest req) throws Exception {
  try {
    SolrCore core = req.getCore();
    SolrQueryResponse rsp = new SolrQueryResponse();
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    core.execute(core.getRequestHandler(handler),req,rsp); // TODO the core doesn't have the request handler
    if (rsp.getException() != null) {
      throw rsp.getException();
    }
    QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
    if (responseWriter instanceof BinaryQueryResponseWriter) {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32000);
      BinaryQueryResponseWriter writer = (BinaryQueryResponseWriter) responseWriter;
      writer.write(byteArrayOutputStream, req, rsp);
      return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } else {
      StringWriter sw = new StringWriter(32000);
      responseWriter.write(sw,req,rsp);
      return sw.toString();
    }

  } finally {
    req.close();
    SolrRequestInfo.clearRequestInfo();
  }
}
 
Example #23
Source File: PKIAuthenticationPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressForbidden(reason = "Needs currentTimeMillis to set current time in header")
private Optional<String> generateToken() {
  SolrRequestInfo reqInfo = getRequestInfo();
  String usr;
  if (reqInfo != null) {
    Principal principal = reqInfo.getUserPrincipal();
    if (principal == null) {
      log.debug("generateToken: principal is 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
      log.debug("generateToken: not a solr (server) thread");
      return Optional.empty();
    }
    //this request seems to be originated from Solr itself
    usr = "$"; //special name to denote the user is the node itself
  }

  String s = usr + " " + System.currentTimeMillis();

  byte[] payload = s.getBytes(UTF_8);
  byte[] payloadCipher = publicKeyHandler.keyPair.encrypt(ByteBuffer.wrap(payload));
  String base64Cipher = Base64.byteArrayToBase64(payloadCipher);
  log.trace("generateToken: usr={} token={}", usr, base64Cipher);
  return Optional.of(base64Cipher);
}
 
Example #24
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 #25
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 #26
Source File: ResponseSink.java    From querqy with Apache License 2.0 5 votes vote down vote up
@Override
public void endOfRequest(final SearchEngineRequestAdapter searchEngineRequestAdapter) {

    @SuppressWarnings("unchecked")
    final Map<String, List<Object>> messages = (Map<String, List<Object>>) searchEngineRequestAdapter.getContext()
            .get(CONTEXT_KEY);

    if (messages != null && !messages.isEmpty()) {
        final SolrQueryResponse rsp = SolrRequestInfo.getRequestInfo().getRsp();
        rsp.add("querqy.infoLog", messages);
    }

}
 
Example #27
Source File: TestSchemalessBufferedUpdates.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private SolrInputDocument processAdd(final SolrInputDocument docIn) throws IOException {
  UpdateRequestProcessorChain processorChain = h.getCore().getUpdateProcessingChain(UPDATE_CHAIN);
  assertNotNull("Undefined URP chain '" + UPDATE_CHAIN + "'", processorChain);
  List <UpdateRequestProcessorFactory> factoriesUpToDUP = new ArrayList<>();
  for (UpdateRequestProcessorFactory urpFactory : processorChain.getProcessors()) {
    factoriesUpToDUP.add(urpFactory);
    if (urpFactory.getClass().equals(DistributedUpdateProcessorFactory.class)) 
      break;
  }
  UpdateRequestProcessorChain chainUpToDUP = new UpdateRequestProcessorChain(factoriesUpToDUP, h.getCore());
  assertNotNull("URP chain '" + UPDATE_CHAIN + "'", chainUpToDUP);
  SolrQueryResponse rsp = new SolrQueryResponse();
  SolrQueryRequest req = req();
  try {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    AddUpdateCommand cmd = new AddUpdateCommand(req);
    cmd.solrDoc = docIn;
    UpdateRequestProcessor processor = chainUpToDUP.createProcessor(req, rsp);
    processor.processAdd(cmd);
    if (cmd.solrDoc.get("f_dt").getValue() instanceof Date) {
      // Non-JSON types (Date in this case) aren't handled properly in noggit-0.6.  Although this is fixed in
      // https://github.com/yonik/noggit/commit/ec3e732af7c9425e8f40297463cbe294154682b1 to call obj.toString(), 
      // Date::toString produces a Date representation that Solr doesn't like, so we convert using Instant::toString
      cmd.solrDoc.get("f_dt").setValue(((Date) cmd.solrDoc.get("f_dt").getValue()).toInstant().toString());
    }
    return cmd.solrDoc;
  } finally {
    SolrRequestInfo.clearRequestInfo();
    req.close();
  }
}
 
Example #28
Source File: TestGroupingSearch.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupingSimpleFormatArrayIndexOutOfBoundsExceptionWithJavaBin() throws Exception {
  assertU(add(doc("id", "1", "nullfirst", "1")));
  assertU(add(doc("id", "2", "nullfirst", "1")));
  assertU(add(doc("id", "3", "nullfirst", "2")));
  assertU(add(doc("id", "4", "nullfirst", "2")));
  assertU(add(doc("id", "5", "nullfirst", "2")));
  assertU(add(doc("id", "6", "nullfirst", "3")));
  assertU(commit());

  SolrQueryRequest request =
      req("q", "*:*","group", "true", "group.field", "nullfirst", "group.main", "true", "wt", "javabin", "start", "4", "rows", "10");

  SolrQueryResponse response = new SolrQueryResponse();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  try {
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(request, response));
    String handlerName = request.getParams().get(CommonParams.QT);
    h.getCore().execute(h.getCore().getRequestHandler(handlerName), request, response);
    BinaryResponseWriter responseWriter = new BinaryResponseWriter();
    responseWriter.write(out, request, response);
  } finally {
    request.close();
    SolrRequestInfo.clearRequestInfo();
  }

  assertEquals(6, ((ResultContext) response.getResponse()).getDocList().matches());
  new BinaryResponseParser().processResponse(new ByteArrayInputStream(out.toByteArray()), "");
  out.close();
}
 
Example #29
Source File: TimestampUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public UpdateRequestProcessor getInstance(SolrQueryRequest req, 
                                          SolrQueryResponse rsp, 
                                          UpdateRequestProcessor next ) {
  return new DefaultValueUpdateProcessor(fieldName, next) {
    @Override
    public Object getDefaultValue() { 
      return SolrRequestInfo.getRequestInfo().getNOW();
    }
  };
}
 
Example #30
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);
}