Java Code Examples for org.apache.solr.request.SolrQueryRequest#getCore()

The following examples show how to use org.apache.solr.request.SolrQueryRequest#getCore() . 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: ExtractingDocumentLoader.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public ExtractingDocumentLoader(SolrQueryRequest req, UpdateRequestProcessor processor,
                         TikaConfig config, ParseContextConfig parseContextConfig,
                                SolrContentHandlerFactory factory) {
  this.params = req.getParams();
  this.core = req.getCore();
  this.config = config;
  this.parseContextConfig = parseContextConfig;
  this.processor = processor;

  templateAdd = new AddUpdateCommand(req);
  templateAdd.overwrite = params.getBool(UpdateParams.OVERWRITE, true);
  templateAdd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);

  //this is lightweight
  autoDetectParser = new AutoDetectParser(config);
  this.factory = factory;
  
  ignoreTikaException = params.getBool(ExtractingParams.IGNORE_TIKA_EXCEPTION, false);
}
 
Example 2
Source File: PostingsSolrHighlighter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected UnifiedHighlighter getHighlighter(SolrQueryRequest req) {
  // Adjust the highlight parameters to match what the old PostingsHighlighter had.
  ModifiableSolrParams invariants = new ModifiableSolrParams();
  invariants.set(HighlightParams.OFFSET_SOURCE, "POSTINGS");
  invariants.set(HighlightParams.FIELD_MATCH, true);
  invariants.set(HighlightParams.USE_PHRASE_HIGHLIGHTER, false);
  invariants.set(HighlightParams.FRAGSIZE, -1);

  ModifiableSolrParams defaults = new ModifiableSolrParams();
  defaults.set(HighlightParams.DEFAULT_SUMMARY, true);
  defaults.set(HighlightParams.TAG_ELLIPSIS, "... ");

  SolrParams newParams = SolrParams.wrapDefaults(
      invariants,// this takes precedence
      SolrParams.wrapDefaults(
          req.getParams(), // then this (original)
          defaults // finally our defaults
      )
  );
  try (LocalSolrQueryRequest fakeReq = new LocalSolrQueryRequest(req.getCore(), newParams)) {
    return super.getHighlighter(fakeReq);
  }
}
 
Example 3
Source File: RoutedAlias.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Create as many collections as required. This method loops to allow for the possibility that the route value
 * requires more than one collection to be created. Since multiple threads may be invoking maintain on separate
 * requests to the same alias, we must pass in a descriptor that details what collection is to be created.
 * This assumption is checked when the command is executed in the overseer. When this method
 * finds that all collections required have been created it returns the (possibly new) destination collection
 * for the document that caused the creation cycle.
 *
 * @param cmd                  the update command being processed
 * @param targetCollectionDesc the descriptor for the presently selected collection .
 * @return The destination collection, possibly created during this method's execution
 */
private String createAllRequiredCollections(AddUpdateCommand cmd, CandidateCollection targetCollectionDesc) {

  SolrQueryRequest req = cmd.getReq();
  SolrCore core = req.getCore();
  CoreContainer coreContainer = core.getCoreContainer();
  do {
    switch (targetCollectionDesc.getCreationType()) {
      case NONE:
        return targetCollectionDesc.destinationCollection; // we don't need another collection
      case SYNCHRONOUS:
        targetCollectionDesc = doSynchronous( cmd, targetCollectionDesc, coreContainer);
        break;
      case ASYNC_PREEMPTIVE:
        return doPreemptive(targetCollectionDesc, core, coreContainer);
      default:
        throw unknownCreateType();
    }
  } while (true);
}
 
Example 4
Source File: HttpShardHandlerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected ReplicaListTransformer getReplicaListTransformer(final SolrQueryRequest req) {
  final SolrParams params = req.getParams();
  final SolrCore core = req.getCore(); // explicit check for null core (temporary?, for tests)
  @SuppressWarnings("resource")
  ZkController zkController = core == null ? null : core.getCoreContainer().getZkController();
  if (zkController != null) {
    return requestReplicaListTransformerGenerator.getReplicaListTransformer(
        params,
        zkController.getZkStateReader().getClusterProperties()
            .getOrDefault(ZkStateReader.DEFAULT_SHARD_PREFERENCES, "")
            .toString(),
        zkController.getNodeName(),
        zkController.getBaseUrl(),
        zkController.getSysPropsCacher()
    );
  } else {
    return requestReplicaListTransformerGenerator.getReplicaListTransformer(params);
  }
}
 
Example 5
Source File: SentryIndexAuthorizationSingleton.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
/**
 * Get the user name associated with the request
 *
 * @param req the request
 * @return the user name associated with the request
 */
public String getUserName(SolrQueryRequest req) throws SolrException {
  if (binding == null) {
    throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED,
      "Solr binding was not created successfully.  Defaulting to no access");
  }
  SolrCore solrCore = req.getCore();
  HttpServletRequest httpServletRequest = (HttpServletRequest)req.getContext().get("httpRequest");

  // LocalSolrQueryRequests won't have the HttpServletRequest because there is no
  // http request associated with it.
  if (httpServletRequest == null && !(req instanceof LocalSolrQueryRequest)) {
    StringBuilder builder = new StringBuilder("Unable to locate HttpServletRequest");
    if (solrCore != null && solrCore.getSolrConfig().getBool(
      "requestDispatcher/requestParsers/@addHttpRequestToContext", true) == false) {
      builder.append(", ensure requestDispatcher/requestParsers/@addHttpRequestToContext is set to true");
    }
    throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED, builder.toString());
  }

  String superUser = System.getProperty("solr.authorization.superuser", "solr");
  // If a local request, treat it like a super user request; i.e. it is equivalent to an
  // http request from the same process.
  return req instanceof LocalSolrQueryRequest?
    superUser:(String)httpServletRequest.getAttribute(USER_NAME);
}
 
Example 6
Source File: SkipExistingDocumentsProcessorFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
SkipExistingDocumentsUpdateProcessor(SolrQueryRequest req,
                                     UpdateRequestProcessor next,
                                     boolean skipInsertIfExists,
                                     boolean skipUpdateIfMissing) {
  super(next);
  this.skipInsertIfExists = skipInsertIfExists;
  this.skipUpdateIfMissing = skipUpdateIfMissing;
  this.core = req.getCore();

  for (UpdateRequestProcessor proc = next ;proc != null; proc = proc.next) {
    if (proc instanceof DistributedUpdateProcessor) {
      distribProc = (DistributedUpdateProcessor)proc;
      break;
    }
  }

  if (distribProc == null) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "DistributedUpdateProcessor must follow SkipExistingDocumentsUpdateProcessor");
  }

  phase = DistributedUpdateProcessor.DistribPhase.parseParam(req.getParams().get(DISTRIB_UPDATE_PARAM));
}
 
Example 7
Source File: HttpCacheHeaderUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate the appropriate last-modified time for Solr relative the current request.
 * 
 * @return the timestamp to use as a last modified time.
 */
public static long calcLastModified(final SolrQueryRequest solrReq) {
  final SolrCore core = solrReq.getCore();
  final SolrIndexSearcher searcher = solrReq.getSearcher();
  
  final LastModFrom lastModFrom
    = core.getSolrConfig().getHttpCachingConfig().getLastModFrom();

  long lastMod;
  try {
    // assume default, change if needed (getOpenTime() should be fast)
    lastMod =
      LastModFrom.DIRLASTMOD == lastModFrom
      ? IndexDeletionPolicyWrapper.getCommitTimestamp(searcher.getIndexReader().getIndexCommit())
      : searcher.getOpenTimeStamp().getTime();
  } catch (IOException e) {
    // we're pretty freaking screwed if this happens
    throw new SolrException(ErrorCode.SERVER_ERROR, e);
  }
  // Get the time where the searcher has been opened
  // We get rid of the milliseconds because the HTTP header has only
  // second granularity
  return lastMod - (lastMod % 1000L);
}
 
Example 8
Source File: HttpCacheHeaderUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates a tag for the ETag header.
 *
 * @return a tag
 */
public static String calcEtag(final SolrQueryRequest solrReq) {
  final SolrCore core = solrReq.getCore();
  final long currentIndexVersion
    = solrReq.getSearcher().getIndexReader().getVersion();

  EtagCacheVal etagCache = etagCoreCache.get(core);
  if (null == etagCache) {
    final String etagSeed
      = core.getSolrConfig().getHttpCachingConfig().getEtagSeed();
    etagCache = new EtagCacheVal(etagSeed);
    etagCoreCache.put(core, etagCache);
  }
  
  return etagCache.calcEtag(currentIndexVersion);
  
}
 
Example 9
Source File: SecureAdminHandlers.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  // this may or may not have the core
  SolrCore core = req.getCore();
  SecureRequestHandlerUtil.checkSentryAdmin(req, SecureRequestHandlerUtil.QUERY_ONLY, getClass().getName(), core != null, null);
  super.handleRequestBody(req, rsp);
}
 
Example 10
Source File: DocBasedVersionConstraintsProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public DocBasedVersionConstraintsProcessor(List<String> versionFields,
                                           boolean ignoreOldUpdates,
                                           List<String> deleteVersionParamNames,
                                           boolean supportMissingVersionOnOldDocs,
                                           boolean useFieldCache,
                                           NamedList<Object> tombstoneConfig,
                                           SolrQueryRequest req,
                                           UpdateRequestProcessor next ) {
  super(next);
  this.ignoreOldUpdates = ignoreOldUpdates;
  this.deleteVersionParamNames = deleteVersionParamNames.toArray(EMPTY_STR_ARR);
  this.supportMissingVersionOnOldDocs = supportMissingVersionOnOldDocs;
  this.core = req.getCore();
  this.versionFieldNames = versionFields.toArray(EMPTY_STR_ARR);
  IndexSchema schema = core.getLatestSchema();
  userVersionFields = new SchemaField[versionFieldNames.length];
  for (int i = 0; i < versionFieldNames.length; i++) {
    userVersionFields[i] = schema.getField(versionFieldNames[i]);
  }
  this.solrVersionField = schema.getField(CommonParams.VERSION_FIELD);
  this.useFieldCache = useFieldCache;

  this.distribProc = getDistributedUpdateProcessor(next);

  this.phase = DistributedUpdateProcessor.DistribPhase.parseParam(req.getParams().get(DISTRIB_UPDATE_PARAM));
  this.tombstoneConfig = tombstoneConfig;
}
 
Example 11
Source File: InvokeOp.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
static Map<String, Object> invokeAClass(SolrQueryRequest req, String c) {
  SolrResourceLoader loader = null;
  if (req.getCore() != null) loader = req.getCore().getResourceLoader();
  else if (req.getContext().get(CoreContainer.class.getName()) != null) {
    CoreContainer cc = (CoreContainer) req.getContext().get(CoreContainer.class.getName());
    loader = cc.getResourceLoader();
  }

  CoreAdminHandler.Invocable invokable = loader.newInstance(c, CoreAdminHandler.Invocable.class);
  Map<String, Object> result = invokable.invoke(req);
  log.info("Invocable_invoked {}", result);
  return result;
}
 
Example 12
Source File: SystemInfoHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception
{
  rsp.setHttpCaching(false);
  SolrCore core = req.getCore();
  if (AdminHandlersProxy.maybeProxyToNodes(req, rsp, getCoreContainer(req, core))) {
    return; // Request was proxied to other node
  }
  if (core != null) rsp.add( "core", getCoreInfo( core, req.getSchema() ) );
  boolean solrCloudMode =  getCoreContainer(req, core).isZooKeeperAware();
  rsp.add( "mode", solrCloudMode ? "solrcloud" : "std");
  if (solrCloudMode) {
    rsp.add("zkHost", getCoreContainer(req, core).getZkController().getZkServerAddress());
  }
  if (cc != null)
    rsp.add( "solr_home", cc.getSolrHome());
  rsp.add( "lucene", getLuceneInfo() );
  rsp.add( "jvm", getJvmInfo() );
  rsp.add( "security", getSecurityInfo(req) );
  rsp.add( "system", getSystemInfo() );
  if (solrCloudMode) {
    rsp.add("node", getCoreContainer(req, core).getZkController().getNodeName());
  }
  SolrEnvironment env = SolrEnvironment.getFromSyspropOrClusterprop(solrCloudMode ?
      getCoreContainer(req, core).getZkController().zkStateReader : null);
  if (env.isDefined()) {
    rsp.add("environment", env.getCode());
    if (env.getLabel() != null) {
      rsp.add("environment_label", env.getLabel());
    }
    if (env.getColor() != null) {
      rsp.add("environment_color", env.getColor());
    }
  }
}
 
Example 13
Source File: SecureReplicationHandler.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  String collection = null;
  if (req.getCore() == null) {
    // if the request doesn't have a core, let's use the core stored on the
    // request handler
    collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
  }
  SecureRequestHandlerUtil.checkSentryAdmin(req, SecureRequestHandlerUtil.QUERY_AND_UPDATE, getClass().getName(), true, collection);
  super.handleRequestBody(req, rsp);
}
 
Example 14
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 15
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 16
Source File: ReSearcherHandler.java    From solr-researcher with Apache License 2.0 5 votes vote down vote up
private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb, ShardHandlerFactory shardHandlerFactory) {
  ShardHandler shardHandler = null;

  boolean isZkAware = false;
  CoreContainer cc = null;
  if (req.getCore() != null) {
    cc = req.getCore().getCoreContainer();
    isZkAware = cc.isZooKeeperAware();
  } 
  
  rb.isDistrib = req.getParams().getBool("distrib", isZkAware);
  if (!rb.isDistrib) {
    // for back compat, a shards param with URLs like localhost:8983/solr will mean that this
    // search is distributed.
    final String shards = req.getParams().get(ShardParams.SHARDS);
    rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0));
  }
  
  if (rb.isDistrib) {
    shardHandler = shardHandlerFactory.getShardHandler();
    shardHandler.prepDistributed(rb);
    if (!rb.isDistrib) {
      shardHandler = null; // request is not distributed after all and so the shard handler is not needed
    }
  }

  if(isZkAware) {
    ZkController zkController = cc.getZkController();
    NamedList<Object> headers = rb.rsp.getResponseHeader();
    if(headers != null) {
      headers.add("zkConnected", 
          zkController != null 
        ? !zkController.getZkClient().getConnectionManager().isLikelyExpired() 
        : false);
    }
    
  }

  return shardHandler;
}
 
Example 17
Source File: RangerSolrAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
/**
 * This method return the user name from the provided {@linkplain SolrQueryRequest}
 */
private final String getUserName(SolrQueryRequest req) {
	// If a local request, treat it like a super user request; i.e. it is equivalent to an
	// http request from the same process.
	if (req instanceof LocalSolrQueryRequest) {
		return SUPERUSER;
	}

	SolrCore solrCore = req.getCore();

	HttpServletRequest httpServletRequest = (HttpServletRequest) req.getContext().get("httpRequest");
	if (httpServletRequest == null) {
		StringBuilder builder = new StringBuilder("Unable to locate HttpServletRequest");
		if (solrCore != null && !solrCore.getSolrConfig().getBool("requestDispatcher/requestParsers/@addHttpRequestToContext", true)) {
			builder.append(", ensure requestDispatcher/requestParsers/@addHttpRequestToContext is set to true in solrconfig.xml");
		}
		throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED, builder.toString());
	}

	String userName = httpServletRequest.getRemoteUser();
	if (userName == null) {
		userName = MiscUtil.getShortNameFromPrincipalName(httpServletRequest.getUserPrincipal().getName());
	}
	if (userName == null) {
		throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED, "This request is not authenticated.");
	}

	return userName;
}
 
Example 18
Source File: StreamHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  SolrParams params = req.getParams();
  params = adjustParams(params);
  req.setParams(params);

  if (params.get("action") != null) {
    handleAdmin(req, rsp, params);
    return;
  }

  TupleStream tupleStream;

  try {
    StreamExpression streamExpression = StreamExpressionParser.parse(params.get(StreamParams.EXPR));
    if (this.streamFactory.isEvaluator(streamExpression)) {
      StreamExpression tupleExpression = new StreamExpression(StreamParams.TUPLE);
      tupleExpression.addParameter(new StreamExpressionNamedParameter(StreamParams.RETURN_VALUE, streamExpression));
      tupleStream = this.streamFactory.constructStream(tupleExpression);
    } else {
      tupleStream = this.streamFactory.constructStream(streamExpression);
    }
  } catch (Exception e) {
    // Catch exceptions that occur while the stream is being created. This will include streaming expression parse
    // rules.
    SolrException.log(log, e);
    rsp.add(StreamParams.RESULT_SET, new DummyErrorStream(e));

    return;
  }


  final SolrCore core = req.getCore(); // explicit check for null core (temporary?, for tests)
  @SuppressWarnings("resource")
  ZkController zkController = core == null ? null : core.getCoreContainer().getZkController();
  RequestReplicaListTransformerGenerator requestReplicaListTransformerGenerator;
  if (zkController != null) {
    requestReplicaListTransformerGenerator = new RequestReplicaListTransformerGenerator(
        zkController.getZkStateReader().getClusterProperties()
            .getOrDefault(ZkStateReader.DEFAULT_SHARD_PREFERENCES, "")
            .toString(),
        zkController.getNodeName(),
        zkController.getBaseUrl(),
        zkController.getSysPropsCacher()
    );
  } else {
    requestReplicaListTransformerGenerator = new RequestReplicaListTransformerGenerator();
  }

  int worker = params.getInt("workerID", 0);
  int numWorkers = params.getInt("numWorkers", 1);
  boolean local = params.getBool("streamLocalOnly", false);
  StreamContext context = new StreamContext();
  context.setRequestParams(params);
  context.setRequestReplicaListTransformerGenerator(requestReplicaListTransformerGenerator);
  context.put("shards", getCollectionShards(params));
  context.workerID = worker;
  context.numWorkers = numWorkers;
  context.setSolrClientCache(solrClientCache);
  context.setModelCache(modelCache);
  context.setObjectCache(objectCache);
  context.put("core", this.coreName);
  context.put("solr-core", req.getCore());
  context.setLocal(local);
  tupleStream.setStreamContext(context);

  // if asking for explanation then go get it
  if (params.getBool("explain", false)) {
    rsp.add("explanation", tupleStream.toExplanation(this.streamFactory));
  }

  if (tupleStream instanceof DaemonStream) {
    DaemonStream daemonStream = (DaemonStream) tupleStream;
    if (daemons.containsKey(daemonStream.getId())) {
      daemons.remove(daemonStream.getId()).close();
    }
    daemonStream.setDaemons(daemons);
    daemonStream.open(); // This will start the daemonStream
    daemons.put(daemonStream.getId(), daemonStream);
    rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon:" + daemonStream.getId() + " started on " + coreName));
  } else {
    rsp.add(StreamParams.RESULT_SET, new TimerStream(new ExceptionStream(tupleStream)));
  }
}
 
Example 19
Source File: TestSubQueryTransformer.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testJustJohnJavabin() throws Exception {
  final SolrQueryRequest johnTwoFL = req(johnAndNancyParams);
  ModifiableSolrParams params = new ModifiableSolrParams(johnTwoFL.getParams());
  params.set("q","name_s:john");
  params.set("wt","javabin");
  
  johnTwoFL.setParams(params);
  
  final NamedList<Object> unmarshalled;
  SolrCore core = johnTwoFL.getCore();
  SolrQueryResponse rsp = new SolrQueryResponse();
  SolrRequestInfo.setRequestInfo(new SolrRequestInfo(johnTwoFL, rsp));

  SolrQueryResponse response = h.queryAndResponse(
      johnTwoFL.getParams().get(CommonParams.QT), johnTwoFL);

  BinaryQueryResponseWriter responseWriter = (BinaryQueryResponseWriter) core.getQueryResponseWriter(johnTwoFL);
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  responseWriter.write(bytes, johnTwoFL, response);

  try (JavaBinCodec jbc = new JavaBinCodec()) {
    unmarshalled = (NamedList<Object>) jbc.unmarshal(
        new ByteArrayInputStream(bytes.toByteArray()));
  }

  johnTwoFL.close();
  SolrRequestInfo.clearRequestInfo();
  
  SolrDocumentList resultDocs = (SolrDocumentList)(unmarshalled.get("response"));
  
    Map<String,String> engText = new HashMap<>();
    engText.put("text_t", "These guys develop stuff");
    
    Map<String,String> engId = new HashMap<>();
    engId.put("text_t", "These guys develop stuff");
    engId.put("dept_id_s_dv", "Engineering");
    
    for (int docNum : new int []{0, peopleMultiplier-1}) {
      SolrDocument employeeDoc = resultDocs.get(docNum);
      assertEquals("john", employeeDoc.getFieldValue("name_s_dv"));
      for (String subResult : new String []{"depts", "depts_i"}) {

        SolrDocumentList subDoc = (SolrDocumentList)employeeDoc.getFieldValue(subResult);
        for (int deptNum : new int []{0, deptMultiplier-1}) {
          SolrDocument deptDoc = subDoc.get(deptNum);
          Object expectedDept = (subResult.equals("depts") ? engText : engId);
          assertTrue( "" + expectedDept + " equals to " + deptDoc,
              expectedDept.equals(deptDoc));
        }
    }
  }
}
 
Example 20
Source File: SentryIndexAuthorizationSingleton.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
/**
 * Attempt to authorize a collection action.
 *
 * @param req request to check
 * @param actions set of actions to check
 * @param collectionName the collection to check.  If null, the collection
 *   name is pulled from the request
 * @param errorIfNoCollection is true, throw an exception if collection
 *   cannot be located
 */
public void authorizeCollectionAction(SolrQueryRequest req,
    Set<SearchModelAction> actions, String operation, String collectionName,
    boolean errorIfNoCollection)
    throws SolrException {

  Subject superUser = new Subject(System.getProperty("solr.authorization.superuser", "solr"));
  Subject userName = new Subject(getUserName(req));
  long eventTime = req.getStartTime();
  String paramString = req.getParamString();
  String impersonator = getImpersonatorName(req);

  String ipAddress = null;
  HttpServletRequest sreq = (HttpServletRequest) req.getContext().get("httpRequest");
  if (sreq != null) {
    try {
      ipAddress = sreq.getRemoteAddr();
    } catch (AssertionError e) {
      // ignore
      // This is a work-around for "Unexpected method call getRemoteAddr()"
      // exception during unit test mocking at
      // com.sun.proxy.$Proxy28.getRemoteAddr(Unknown Source)
    }
  }

  if (collectionName == null) {
    SolrCore solrCore = req.getCore();
    if (solrCore == null) {
      String msg = "Unable to locate collection for sentry to authorize because "
        + "no SolrCore attached to request";
      if (errorIfNoCollection) {
        auditLogger.log(userName.getName(), impersonator, ipAddress,
            operation, paramString, eventTime, AuditLogger.UNAUTHORIZED, "");
        throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED, msg);
      } else { // just warn
        log.warn(msg);
        auditLogger.log(userName.getName(), impersonator, ipAddress,
            operation, paramString, eventTime, AuditLogger.ALLOWED, "");
        return;
      }
    }
    collectionName = solrCore.getCoreDescriptor().getCloudDescriptor().getCollectionName();
  }

  Collection collection = new Collection(collectionName);
  try {
    if (!superUser.getName().equals(userName.getName())) {
      binding.authorizeCollection(userName, collection, actions);
    }
  } catch (SentrySolrAuthorizationException ex) {
    auditLogger.log(userName.getName(), impersonator, ipAddress,
        operation, paramString, eventTime, AuditLogger.UNAUTHORIZED, collectionName);
    throw new SolrException(SolrException.ErrorCode.UNAUTHORIZED, ex);
  }

  auditLogger.log(userName.getName(), impersonator, ipAddress,
      operation, paramString, eventTime, AuditLogger.ALLOWED, collectionName);
}