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

The following examples show how to use org.apache.solr.request.SolrQueryRequest#getParams() . 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: DefaultSolrHighlighter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** Highlights and returns the highlight object for this field -- a String[] by default.  Null if none. */
@SuppressWarnings("unchecked")
protected Object doHighlightingByFastVectorHighlighter(SolrDocument doc, int docId,
                                                       SchemaField schemaField, FvhContainer fvhContainer,
                                                       IndexReader reader, SolrQueryRequest req) throws IOException {
  SolrParams params = req.getParams();
  String fieldName = schemaField.getName();
  SolrFragmentsBuilder solrFb = getSolrFragmentsBuilder(fieldName, params);

  String[] snippets = fvhContainer.fvh.getBestFragments(fvhContainer.fieldQuery, reader, docId, fieldName,
          params.getFieldInt(fieldName, HighlightParams.FRAGSIZE, 100),
          params.getFieldInt(fieldName, HighlightParams.SNIPPETS, 1),
          getFragListBuilder(fieldName, params),
          getFragmentsBuilder(fieldName, params),
          solrFb.getPreTags(params, fieldName),
          solrFb.getPostTags(params, fieldName),
          getEncoder(fieldName, params));
  if (snippets != null && snippets.length > 0)
    return snippets;
  return null;
}
 
Example 2
Source File: JSONResponseWriter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {
  final SolrParams params = req.getParams();
  final String wrapperFunction = params.get(JSONWriter.JSON_WRAPPER_FUNCTION);
  final String namedListStyle = params.get(JsonTextWriter.JSON_NL_STYLE, JsonTextWriter.JSON_NL_FLAT).intern();

  final JSONWriter w;
  if (namedListStyle.equals(JsonTextWriter.JSON_NL_ARROFNTV)) {
    w = new ArrayOfNameTypeValueJSONWriter(
        writer, req, rsp, wrapperFunction, namedListStyle, true);
  } else {
    w = new JSONWriter(
        writer, req, rsp, wrapperFunction, namedListStyle);
  }

  try {
    w.writeResponse();
  } finally {
    w.close();
  }
}
 
Example 3
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 4
Source File: MyHandler.java    From solr-custom-score with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest solrQueryRequest, SolrQueryResponse solrQueryResponse) throws Exception {
    numRequests++;
    long startTime=System.currentTimeMillis();
    try{
        HashMap<String,Integer> counts=new HashMap<String, Integer>();
        SolrParams params=solrQueryRequest.getParams();
        String q=params.get(CommonParams.Q);//从url中得到q参数

        for(String text:q.split(" ")){
            if(words.contains(text)){

                Integer ct=counts.containsKey(text)?counts.get(text):0;
                counts.put(text,ct+1);

            }else{
                log.warn("过滤掉此单词:{}",text);
            }

        }

        NamedList<Integer> re=new NamedList<Integer>();
        for(String word:words){
            re.add(word,counts.get(word));
        }

        solrQueryResponse.add("results",re);

    }catch (Exception e){
        numErrors++;
        log.error("统计出错: ",e.getMessage());
    }finally {
        totalTime+=System.currentTimeMillis()-startTime;
    }

}
 
Example 5
Source File: Cloud.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the doc list resulting from running the query
 * @param requestHandler the handler that handles the request
 * @param request the request object to put the query on
 * @param query the string that specifies the docs
 * @return the docs that come back from the query
 */
DocList getDocList(SolrRequestHandler requestHandler, SolrQueryRequest request, String query)
{
    // Getting the doc list is shard-specific, and not really cloud-friendly
    
    ModifiableSolrParams params = new ModifiableSolrParams(request.getParams());
    // Sets MAX_VALUE to get all the rows
    params.set("q", query).set("fl", QueryConstants.FIELD_SOLR4_ID).set("rows", Integer.MAX_VALUE);
    ResultContext rc = this.getResultContext(requestHandler, request, params);
    return rc != null ? rc.getDocList() : null;
}
 
Example 6
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.SolrTestCaseJ4#assertQ(String, SolrQueryRequest, String...)} in order not to
 * use the instance of the {@link org.apache.solr.util.TestHarness}.
 */
private static void localAssertQ(String message, SolrQueryRequest req, String... tests) {
  try {
    String m = (null == message) ? "" : message + " "; // TODO log 'm' !!!
    //since the default (standard) response format is now JSON
    //need to explicitly request XML since this class uses XPath
    ModifiableSolrParams xmlWriterTypeParams = new ModifiableSolrParams(req.getParams());
    xmlWriterTypeParams.set(CommonParams.WT,"xml");
    //for tests, let's turn indention off so we don't have to handle extraneous spaces
    xmlWriterTypeParams.set("indent", xmlWriterTypeParams.get("indent", "off"));
    req.setParams(xmlWriterTypeParams);
    String response = localQuery(req.getParams().get(CommonParams.QT), req);

    if (req.getParams().getBool("facet", false)) {
      // add a test to ensure that faceting did not throw an exception
      // internally, where it would be added to facet_counts/exception
      String[] allTests = new String[tests.length+1];
      System.arraycopy(tests,0,allTests,1,tests.length);
      allTests[0] = "*[count(//lst[@name='facet_counts']/*[@name='exception'])=0]";
      tests = allTests;
    }

    String results = BaseTestHarness.validateXPath(response, tests);

    if (null != results) {
      String msg = "REQUEST FAILED: xpath=" + results
          + "\n\txml response was: " + response
          + "\n\trequest was:" + req.getParamString();

      log.error(msg);
      throw new RuntimeException(msg);
    }

  } catch (XPathExpressionException e1) {
    throw new RuntimeException("XPath is invalid", e1);
  } catch (Exception e2) {
    SolrException.log(log,"REQUEST FAILED: " + req.getParamString(), e2);
    throw new RuntimeException("Exception during query", e2);
  }
}
 
Example 7
Source File: AlfrescoCoreAdminHandler.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates new default cores using default values.
 *
 * Synchronous execution
 *
 * @param req Query Request including following parameters:
 * - coreName, mandatory, the name of the core to be created
 * - storeRef, optional, the storeRef for the SOLR Core (workspace://SpacesStore, archive://SpacesStore)
 * - template, optional, the name of the SOLR template used to create the core (rerank, norerank)
 * @return Response including the action result:
 * - status: success, when the resource has been reloaded
 * - status: error, when the resource has NOT been reloaded
 * - errorMessage: message, if action status is "error" an error message node is included
 */
private NamedList<Object> newDefaultCore(SolrQueryRequest req)
{

    NamedList<Object> response = new SimpleOrderedMap<>();

    SolrParams params = req.getParams();
    String coreName = ofNullable(coreName(params)).orElse(ALFRESCO_CORE_NAME);
    String templateName =
            params.get("template") != null
                    ? params.get("template")
                    : DEFAULT_TEMPLATE;

    Properties extraProperties = extractCustomProperties(params);

    response = newDefaultCore(
            coreName,
            ofNullable(params.get("storeRef"))
                    .map(StoreRef::new)
                    .orElse(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE),
            templateName,
            extraProperties);
    if (!Objects.equals(response.get(ACTION_STATUS_LABEL), ACTION_STATUS_ERROR))
    {
        response.add(ACTION_STATUS_LABEL, ACTION_STATUS_SUCCESS);
    }
    return response;
}
 
Example 8
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** Validates a query matches some XPath test expressions and closes the query */
public static void assertQ(String message, SolrQueryRequest req, String... tests) {
  try {
    String m = (null == message) ? "" : message + " "; // TODO log 'm' !!!
    //since the default (standard) response format is now JSON
    //need to explicitly request XML since this class uses XPath
    ModifiableSolrParams xmlWriterTypeParams = new ModifiableSolrParams(req.getParams());
    xmlWriterTypeParams.set(CommonParams.WT,"xml");
    //for tests, let's turn indention off so we don't have to handle extraneous spaces
    xmlWriterTypeParams.set("indent", xmlWriterTypeParams.get("indent", "off"));
    req.setParams(xmlWriterTypeParams);
    String response = h.query(req);

    if (req.getParams().getBool("facet", false)) {
      // add a test to ensure that faceting did not throw an exception
      // internally, where it would be added to facet_counts/exception
      String[] allTests = new String[tests.length+1];
      System.arraycopy(tests,0,allTests,1,tests.length);
      allTests[0] = "*[count(//lst[@name='facet_counts']/*[@name='exception'])=0]";
      tests = allTests;
    }

    String results = BaseTestHarness.validateXPath(response, tests);

    if (null != results) {
      String msg = "REQUEST FAILED: xpath=" + results
          + "\n\txml response was: " + response
          + "\n\trequest was:" + req.getParamString();

      log.error(msg);
      throw new RuntimeException(msg);
    }

  } catch (XPathExpressionException e1) {
    throw new RuntimeException("XPath is invalid", e1);
  } catch (Exception e2) {
    SolrException.log(log,"REQUEST FAILED: " + req.getParamString(), e2);
    throw new RuntimeException("Exception during query", e2);
  }
}
 
Example 9
Source File: AlfrescoCoreAdminHandler.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Update memory loading from "shared.properties" file for each Core
 *
 * Synchronous execution
 *
 * @param req Query Request with no parameters
 * @return Response including the action result:
 * - status: success, when the properties has been reloaded
 * - status: error, when the properties has NOT been reloaded
 * - errorMessage: message, if action status is "error" an error message node is included
 */
private NamedList<Object> updateShared(SolrQueryRequest req)
{
    SolrParams params = req.getParams();
    NamedList<Object> response = new SimpleOrderedMap<>();

    try
    {
        File config = new File(AlfrescoSolrDataModel.getResourceDirectory(), AlfrescoSolrDataModel.SHARED_PROPERTIES);
        updateSharedProperties(params, config, hasAlfrescoCore(coreContainer.getCores()));

        coreContainer.getCores().stream()
                .map(SolrCore::getName)
                .forEach(coreContainer::reload);

        response.add(ACTION_STATUS_LABEL, ACTION_STATUS_SUCCESS);

    }
    catch (IOException e)
    {
        LOGGER.error("Failed to update Shared properties ", e);
        response.add(ACTION_STATUS_LABEL, ACTION_STATUS_ERROR);
        response.add(ACTION_ERROR_MESSAGE_LABEL, "Shared properties couldn't be reloaded for some core. Check the log to find out the reason.");
        return response;
    }
    return response;
}
 
Example 10
Source File: ConfigSetsHandler.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 {
  if (coreContainer == null) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Core container instance missing");
  }

  // Make sure that the core is ZKAware
  if (!coreContainer.isZooKeeperAware()) {
    throw new SolrException(ErrorCode.BAD_REQUEST,
        "Solr instance is not running in SolrCloud mode.");
  }

  // Pick the action
  SolrParams params = req.getParams();
  String a = params.get(ConfigSetParams.ACTION);
  if (a != null) {
    ConfigSetAction action = ConfigSetAction.get(a);
    if (action == null)
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unknown action: " + a);
    if (action == ConfigSetAction.UPLOAD) {
      handleConfigUploadRequest(req, rsp);
      return;
    }
    invokeAction(req, rsp, action);
  } else {
    throw new SolrException(ErrorCode.BAD_REQUEST, "action is a required param");
  }

  rsp.setHttpCaching(false);
}
 
Example 11
Source File: UpdateRequestHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setDefaultWT(SolrQueryRequest req, ContentStreamLoader loader) {
  SolrParams params = req.getParams();
  if( params.get(CommonParams.WT) == null ) {
    String wt = loader.getDefaultWT();
    // Make sure it is a valid writer
    if(req.getCore().getQueryResponseWriter(wt)!=null) {
      Map<String,String> map = new HashMap<>(1);
      map.put(CommonParams.WT, wt);
      req.setParams(SolrParams.wrapDefaults(params,
          new MapSolrParams(map)));
    }
  }
}
 
Example 12
Source File: SetLocaleComponent.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void prepare(ResponseBuilder rb) throws IOException
{
    SolrQueryRequest req = rb.req;
    SolrParams params = req.getParams();
    String localeStr = params.get("locale");
    Locale locale = I18NUtil.parseLocale(localeStr);
    I18NUtil.setLocale(locale);
    log.info("Set locale to " + localeStr);
}
 
Example 13
Source File: RequestHandlerUtils.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * @since 6.7
 */
public static void setWt(SolrQueryRequest req, String wt) {
  SolrParams params = req.getParams();
  if (params.get(CommonParams.WT) != null) return;//wt is set by user
  Map<String, String> map = new HashMap<>(1);
  map.put(CommonParams.WT, wt);
  map.put("indent", "true");
  req.setParams(SolrParams.wrapDefaults(params, new MapSolrParams(map)));
}
 
Example 14
Source File: RealTimeGetComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void processGetFingeprint(ResponseBuilder rb) throws IOException {
  TestInjection.injectFailIndexFingerprintRequests();

  SolrQueryRequest req = rb.req;
  SolrParams params = req.getParams();

  long maxVersion = params.getLong("getFingerprint", Long.MAX_VALUE);
  if (TestInjection.injectWrongIndexFingerprint())  {
    maxVersion = -1;
  }
  IndexFingerprint fingerprint = IndexFingerprint.getFingerprint(req.getCore(), Math.abs(maxVersion));
  rb.rsp.add("fingerprint", fingerprint);
}
 
Example 15
Source File: ZookeeperInfoHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  final SolrParams params = req.getParams();
  Map<String, String> map = new HashMap<>(1);
  map.put(WT, "raw");
  map.put(OMIT_HEADER, "true");
  req.setParams(SolrParams.wrapDefaults(new MapSolrParams(map), params));
  synchronized (this) {
    if (pagingSupport == null) {
      pagingSupport = new PagedCollectionSupport();
      ZkController zkController = cores.getZkController();
      if (zkController != null) {
        // get notified when the ZK session expires (so we can clear the cached collections and rebuild)
        zkController.addOnReconnectListener(pagingSupport);
      }
    }
  }

  String path = params.get(PATH);

  if (params.get("addr") != null) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Illegal parameter \"addr\"");
  }

  String detailS = params.get("detail");
  boolean detail = detailS != null && detailS.equals("true");

  String dumpS = params.get("dump");
  boolean dump = dumpS != null && dumpS.equals("true");

  int start = params.getInt("start", 0); // Note start ignored if rows not specified
  int rows = params.getInt("rows", -1);

  String filterType = params.get("filterType");
  if (filterType != null) {
    filterType = filterType.trim().toLowerCase(Locale.ROOT);
    if (filterType.length() == 0)
      filterType = null;
  }
  FilterType type = (filterType != null) ? FilterType.valueOf(filterType) : FilterType.none;

  String filter = (type != FilterType.none) ? params.get("filter") : null;
  if (filter != null) {
    filter = filter.trim();
    if (filter.length() == 0)
      filter = null;
  }

  ZKPrinter printer = new ZKPrinter(cores.getZkController());
  printer.detail = detail;
  printer.dump = dump;
  boolean isGraphView = "graph".equals(params.get("view"));
  // There is no znode /clusterstate.json (removed in Solr 9), but we do as if there's one and return collection listing
  // Need to change services.js if cleaning up here, collection list is used from Admin UI Cloud - Graph
  boolean paginateCollections = (isGraphView && "/clusterstate.json".equals(path));
  printer.page = paginateCollections ? new PageOfCollections(start, rows, type, filter) : null;
  printer.pagingSupport = pagingSupport;

  try {
    if (paginateCollections) {
      // List collections and allow pagination, but no specific znode info like when looking at a normal ZK path
      printer.printPaginatedCollections();
    } else {
      printer.print(path);
    }
  } finally {
    printer.close();
  }
  rsp.getValues().add(RawResponseWriter.CONTENT,printer);
}
 
Example 16
Source File: AlfrescoLukeRequestHandler.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static SimpleOrderedMap<Object> getIndexedFieldsInfo(
		SolrQueryRequest req) throws Exception {

	SolrIndexSearcher searcher = req.getSearcher();
	SolrParams params = req.getParams();

	Set<String> fields = null;
	String fl = params.get(CommonParams.FL);
	if (fl != null) {
		fields = new TreeSet<>(Arrays.asList(fl.split("[,\\s]+")));
	}

	LeafReader reader = searcher.getSlowAtomicReader();
	IndexSchema schema = searcher.getSchema();

	// Don't be tempted to put this in the loop below, the whole point here
	// is to alphabetize the fields!
	Set<String> fieldNames = new TreeSet<>();
	for (FieldInfo fieldInfo : reader.getFieldInfos()) {
		fieldNames.add(fieldInfo.name);
	}

	// Walk the term enum and keep a priority queue for each map in our set
	SimpleOrderedMap<Object> vInfo = new SimpleOrderedMap<>();
	SimpleOrderedMap<Object> aInfo = new SimpleOrderedMap<>();

	for (String fieldName : fieldNames) {
		if (fields != null && !fields.contains(fieldName)
				&& !fields.contains("*")) {
			continue; // we're not interested in this field Still an issue
						// here
		}

		SimpleOrderedMap<Object> fieldMap = new SimpleOrderedMap<>();

		SchemaField sfield = schema.getFieldOrNull(fieldName);
		FieldType ftype = (sfield == null) ? null : sfield.getType();

		fieldMap.add("type", (ftype == null) ? null : ftype.getTypeName());
		fieldMap.add("schema", getFieldFlags(sfield));
		if (sfield != null && schema.isDynamicField(sfield.getName())
				&& schema.getDynamicPattern(sfield.getName()) != null) {
			fieldMap.add("dynamicBase",
					schema.getDynamicPattern(sfield.getName()));
		}
		Terms terms = reader.fields().terms(fieldName);
		if (terms == null) { // Not indexed, so we need to report what we
								// can (it made it through the fl param if
								// specified)
			vInfo.add(AlfrescoSolrDataModel.getInstance()
					.getAlfrescoPropertyFromSchemaField(fieldName),
					fieldMap);
			aInfo.add(fieldName, fieldMap);
			continue;
		}

		if (sfield != null && sfield.indexed()) {
			if (params.getBool(INCLUDE_INDEX_FIELD_FLAGS, true)) {
				Document doc = getFirstLiveDoc(terms, reader);

				if (doc != null) {
					// Found a document with this field
					try {
						IndexableField fld = doc.getField(fieldName);
						if (fld != null) {
							fieldMap.add("index", getFieldFlags(fld));
						} else {
							// it is a non-stored field...
							fieldMap.add("index", "(unstored field)");
						}
					} catch (Exception ex) {
						log.warn("error reading field: " + fieldName);
					}
				}
			}
			fieldMap.add("docs", terms.getDocCount());

		}
		if (fields != null
				&& (fields.contains(fieldName) || fields.contains("*"))) {
			getDetailedFieldInfo(req, fieldName, fieldMap);
		}
		// Add the field
		vInfo.add(fieldName, fieldMap);
		aInfo.add(AlfrescoSolrDataModel.getInstance()
				.getAlfrescoPropertyFromSchemaField(fieldName), fieldMap);
	}

	SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<>();
	finfo.addAll(vInfo);
	// finfo.add("mimetype()", finfo.get("cm:content.mimetype"));
	// finfo.add("contentSize()", finfo.get("cm:content.size"));
	finfo.addAll(aInfo);
	return finfo;
}
 
Example 17
Source File: DocumentAnalysisRequestHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Resolves the {@link DocumentAnalysisRequest} from the given solr request.
 *
 * @param req The solr request.
 *
 * @return The resolved document analysis request.
 *
 * @throws IOException        Thrown when reading/parsing the content stream of the request fails.
 * @throws XMLStreamException Thrown when reading/parsing the content stream of the request fails.
 */
DocumentAnalysisRequest resolveAnalysisRequest(SolrQueryRequest req) throws IOException, XMLStreamException {

  DocumentAnalysisRequest request = new DocumentAnalysisRequest();

  SolrParams params = req.getParams();

  String query = params.get(AnalysisParams.QUERY, params.get(CommonParams.Q, null));
  request.setQuery(query);

  boolean showMatch = params.getBool(AnalysisParams.SHOW_MATCH, false);
  request.setShowMatch(showMatch);

  ContentStream stream = extractSingleContentStream(req);
  InputStream is = null;
  XMLStreamReader parser = null;
  
  try {
    is = stream.getStream();
    final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());
    parser = (charset == null) ?
      inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset);

    while (true) {
      int event = parser.next();
      switch (event) {
        case XMLStreamConstants.END_DOCUMENT: {
          parser.close();
          return request;
        }
        case XMLStreamConstants.START_ELEMENT: {
          String currTag = parser.getLocalName();
          if ("doc".equals(currTag)) {
            log.trace("Reading doc...");
            SolrInputDocument document = readDocument(parser, req.getSchema());
            request.addDocument(document);
          }
          break;
        }
      }
    }

  } finally {
    if (parser != null) parser.close();
    IOUtils.closeQuietly(is);
  }
}
 
Example 18
Source File: SecureCollectionsHandler.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  // Pick the action
  SolrParams params = req.getParams();
  CollectionAction action = null;
  String a = params.get(CoreAdminParams.ACTION);
  String collection = null;
  if (a != null) {
    action = CollectionAction.get(a);
  }
  if (action != null) {
    switch (action) {
      case CREATE:
      case DELETE:
      case RELOAD:
      case CREATEALIAS: // FixMe: do we need to check the underlying "collections" as well?
      case DELETEALIAS:
      {
        collection = req.getParams().required().get("name");
        break;
      }
      case SYNCSHARD:
      case SPLITSHARD:
      case DELETESHARD: {
        collection = req.getParams().required().get("collection");
        break;
      }
      default: {
        collection = null;
        break;
      }
    }
  }
  // all actions require UPDATE privileges
  SecureRequestHandlerUtil.checkSentryAdmin(req, SecureRequestHandlerUtil.UPDATE_ONLY,
    (action != null ? "CollectionAction." + action.toString() : getClass().getName() + "/" + a), true, collection);
  super.handleRequestBody(req, rsp);

  /**
   * Attempt to sync collection privileges with Sentry when the metadata has changed.
   * ex: When the collection has been deleted, the privileges related to the collection
   * were also needed to drop.
   */
  if (CollectionAction.DELETE.equals(action)) {
    SecureRequestHandlerUtil.syncDeleteCollection(collection);
  }

}
 
Example 19
Source File: Sparql11GraphStoreProtocolHandler.java    From SolRDF with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequestBody(
		final SolrQueryRequest request, 
		final SolrQueryResponse response) throws Exception {
	
	final HttpServletRequest httpRequest = (HttpServletRequest) request.getContext().get(Names.HTTP_REQUEST_KEY);
	final String method = httpRequest.getMethod();

	final SolrParams parameters = request.getParams();
	final String graphUri = parameters.get(Names.DEFAULT_GRAPH_PARAMETER_NAME) != null 
			? null 
			: parameters.get(Names.GRAPH_URI_PARAMETER_NAME);
	
	LOGGER.debug(MessageCatalog._00093_GSP_REQUEST, method, graphUri != null ? graphUri : "default");
	
	// Although a stupid Map could (apparently) avoid the conditional logic, here we have just 4 
	// possible entries (GET, POST, PUT and DELETE), so a set of if statements is almost innocue.
	if ("GET".equals(method)) {
		request.setParams(
				new ModifiableSolrParams(parameters)
					.add(CommonParams.Q, constructQuery(graphUri)));
		
		forward(request, response, SEARCH_HANDLER_PARAMETER_NAME, DEFAULT_SEARCH_HANDLER_NAME);
	} else if ("POST".equals(method)) {
		if (request.getContentStreams() == null || !request.getContentStreams().iterator().hasNext()) {
			throw new SolrException(ErrorCode.BAD_REQUEST, "Empty RDF Payload");
		}
		
		if (graphUri != null) {
			request.setParams(
					new ModifiableSolrParams(parameters).add(
							Names.GRAPH_URI_ATTRIBUTE_NAME, 
							graphUri));
		}			
		forward(request, response, BULK_UPDATE_HANDLER_PARAMETER_NAME, DEFAULT_BULK_UPDATE_HANDLER_NAME);
	} else if ("PUT".equals(method)) {
		// Unfortunately we never fall within this case (see class comments)
		if (request.getContentStreams() == null || !request.getContentStreams().iterator().hasNext()) {
			throw new SolrException(ErrorCode.BAD_REQUEST, "Emtpty RDF Payload");
		}
		
		final String q = new StringBuilder("DROP SILENT ")
			.append(graphUri != null ? "GRAPH <" + graphUri + "> " : "DEFAULT" )
			.toString();
		
		request.setParams(new ModifiableSolrParams(parameters).add(CommonParams.Q, q));

		forward(request, response, UPDATE_HANDLER_PARAMETER_NAME, DEFAULT_UPDATE_HANDLER_NAME);
		forward(request, response, BULK_UPDATE_HANDLER_PARAMETER_NAME, DEFAULT_BULK_UPDATE_HANDLER_NAME);
	} else if ("DELETE".equals(method)) {
		// Unfortunately we never fall within this case (see class comments)
	}
}
 
Example 20
Source File: ReplicationHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  rsp.setHttpCaching(false);
  final SolrParams solrParams = req.getParams();
  String command = solrParams.required().get(COMMAND);

  // This command does not give the current index version of the master
  // It gives the current 'replicateable' index version
  if (command.equals(CMD_INDEX_VERSION)) {
    IndexCommit commitPoint = indexCommitPoint;  // make a copy so it won't change

    if (commitPoint == null) {
      // if this handler is 'lazy', we may not have tracked the last commit
      // because our commit listener is registered on inform
      commitPoint = core.getDeletionPolicy().getLatestCommit();
    }

    if (commitPoint != null && replicationEnabled.get()) {
      //
      // There is a race condition here.  The commit point may be changed / deleted by the time
      // we get around to reserving it.  This is a very small window though, and should not result
      // in a catastrophic failure, but will result in the client getting an empty file list for
      // the CMD_GET_FILE_LIST command.
      //
      core.getDeletionPolicy().setReserveDuration(commitPoint.getGeneration(), reserveCommitDuration);
      rsp.add(CMD_INDEX_VERSION, IndexDeletionPolicyWrapper.getCommitTimestamp(commitPoint));
      rsp.add(GENERATION, commitPoint.getGeneration());
      rsp.add(STATUS, OK_STATUS);
    } else {
      // This happens when replication is not configured to happen after startup and no commit/optimize
      // has happened yet.
      rsp.add(CMD_INDEX_VERSION, 0L);
      rsp.add(GENERATION, 0L);
      rsp.add(STATUS, OK_STATUS);
    }
  } else if (command.equals(CMD_GET_FILE)) {
    getFileStream(solrParams, rsp);
  } else if (command.equals(CMD_GET_FILE_LIST)) {
    getFileList(solrParams, rsp);
  } else if (command.equalsIgnoreCase(CMD_BACKUP)) {
    doSnapShoot(new ModifiableSolrParams(solrParams), rsp, req);
  } else if (command.equalsIgnoreCase(CMD_RESTORE)) {
    restore(new ModifiableSolrParams(solrParams), rsp, req);
  } else if (command.equalsIgnoreCase(CMD_RESTORE_STATUS)) {
    populateRestoreStatus(rsp);
  } else if (command.equalsIgnoreCase(CMD_DELETE_BACKUP)) {
    deleteSnapshot(new ModifiableSolrParams(solrParams), rsp);
  } else if (command.equalsIgnoreCase(CMD_FETCH_INDEX)) {
    fetchIndex(solrParams, rsp);
  } else if (command.equalsIgnoreCase(CMD_DISABLE_POLL)) {
    disablePoll(rsp);
  } else if (command.equalsIgnoreCase(CMD_ENABLE_POLL)) {
    enablePoll(rsp);
  } else if (command.equalsIgnoreCase(CMD_ABORT_FETCH)) {
    if (abortFetch()) {
      rsp.add(STATUS, OK_STATUS);
    } else {
      reportErrorOnResponse(rsp, "No slave configured", null);
    }
  } else if (command.equals(CMD_SHOW_COMMITS)) {
    populateCommitInfo(rsp);
  } else if (command.equals(CMD_DETAILS)) {
    getReplicationDetails(rsp, solrParams.getBool("slave", true));
  } else if (CMD_ENABLE_REPL.equalsIgnoreCase(command)) {
    replicationEnabled.set(true);
    rsp.add(STATUS, OK_STATUS);
  } else if (CMD_DISABLE_REPL.equalsIgnoreCase(command)) {
    replicationEnabled.set(false);
    rsp.add(STATUS, OK_STATUS);
  }
}