Java Code Examples for org.apache.solr.response.SolrQueryResponse#add()

The following examples show how to use org.apache.solr.response.SolrQueryResponse#add() . 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: SpellcheckHandler.java    From customized-symspell with MIT License 6 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {

  if (spellChecker == null) {
    initSpellCheck();
  }
  String word = req.getParams().get(Constants.SPELLCHECK_Q, "");
  rsp.add("lookup_compound", createFeature(spellChecker.lookupCompound(word)));
  rsp.add("lookup", createFeature(spellChecker.lookup(word)));
  rsp.add("lookup_wordbreak", createFeatureComp(spellChecker.wordBreakSegmentation(word)));
  if (req.getParams().getBool(Constants.SPELLCHECK_DATALOAD_UNIGRAM, false)) {
    rsp.add("UNIGRAM", spellChecker.getDataHolder().getItemFrequency(word));
  }
  if (req.getParams().getBool(Constants.SPELLCHECK_DATALOAD_BIGRAM, false)) {
    rsp.add("BIGRAM", spellChecker.getDataHolder().getItemFrequencyBiGram(word));
  }
}
 
Example 2
Source File: TestConfigsApi.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void testCommands() throws Exception {

  try (ConfigSetsHandler handler = new ConfigSetsHandler(null) {
    @Override
    protected void sendToZk(SolrQueryResponse rsp,
                            ConfigSetOperation operation,
                            Map<String, Object> result)
        throws KeeperException, InterruptedException {
      result.put(QUEUE_OPERATION, operation.action.toLower());
      rsp.add(ZkNodeProps.class.getName(), new ZkNodeProps(result));
    }
  }) {
    ApiBag apiBag = new ApiBag(false);
    for (Api api : handler.getApis()) apiBag.register(api, EMPTY_MAP);
    compareOutput(apiBag, "/cluster/configs/sample", DELETE, null, null,
        "{name :sample, operation:delete}");

    compareOutput(apiBag, "/cluster/configs", POST, "{create:{name : newconf, baseConfigSet: sample }}", null,
        "{operation:create, name :newconf,  baseConfigSet: sample, immutable: false }");
  }
}
 
Example 3
Source File: ReplicationHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * This method adds an Object of FileStream to the response . The FileStream implements a custom protocol which is
 * understood by IndexFetcher.FileFetcher
 *
 * @see IndexFetcher.LocalFsFileFetcher
 * @see IndexFetcher.DirectoryFileFetcher
 */
private void getFileStream(SolrParams solrParams, SolrQueryResponse rsp) {
  ModifiableSolrParams rawParams = new ModifiableSolrParams(solrParams);
  rawParams.set(CommonParams.WT, FILE_STREAM);

  String cfileName = solrParams.get(CONF_FILE_SHORT);
  String tlogFileName = solrParams.get(TLOG_FILE);
  if (cfileName != null) {
    rsp.add(FILE_STREAM, new LocalFsConfFileStream(solrParams));
  } else if (tlogFileName != null) {
    rsp.add(FILE_STREAM, new LocalFsTlogFileStream(solrParams));
  } else {
    rsp.add(FILE_STREAM, new DirectoryFileStream(solrParams));
  }
  rsp.add(STATUS, OK_STATUS);
}
 
Example 4
Source File: AggregationWaitableTest.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
@Test
public void parseResponse() {
    SolrQueryResponse resp = new SolrQueryResponse();
    SimpleOrderedMap<Object> root = new SimpleOrderedMap<>();
    SimpleOrderedMap<Object> queryFacet= new SimpleOrderedMap<>();
    SimpleOrderedMap<Object> fieldFacet= new SimpleOrderedMap<>();
    LinkedList<Object> buckets = new LinkedList<>();
    SimpleOrderedMap<Object> bucket1 = new SimpleOrderedMap<>();
    SimpleOrderedMap<Object> bucket2 = new SimpleOrderedMap<>();
    bucket1.add("val", "testValue1");
    bucket1.add("count", 1234);
    bucket2.add("val", "testValue2");
    bucket2.add("count", 4321);
    buckets.add(bucket1);
    buckets.add(bucket2);
    fieldFacet.add("buckets", buckets);
    queryFacet.add(AggregationWaitable.FIELD_FACET_NAME, fieldFacet);
    root.add(AggregationWaitable.QUERY_FACET_NAME, queryFacet);
    resp.add("facets", root);

    LinkedList<ResponseValue> expected = new LinkedList<>();
    expected.add(new ResponseValue("testValue1", 1234));
    expected.add(new ResponseValue("testValue2", 4321));


    AggregationWaitable target = new AggregationWaitable(context, adapter, "query", "testfield", 0,  0);

    Deencapsulation.invoke(target, "parseResponse", resp);

    Assert.assertEquals(expected.size(), target.buckets.size());
    for(int i  = 0; i < target.buckets.size(); ++i)
    {
        Assert.assertEquals(buckets.get(i), target.buckets.get(i));
    }
}
 
Example 5
Source File: AbstractIngestionHandler.java    From chronix.server with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    formatResponseAsJson(req);

    if (req.getContentStreams() == null) {
        LOGGER.warn("no content stream");
        rsp.add("error", "No content stream");
        return;
    }

    boolean commit = Boolean.parseBoolean(req.getParams().get("commit", "true"));

    InputStream stream = req.getContentStreams().iterator().next().getStream();
    stream = detectGzip(stream);

    MetricTimeSeriesConverter converter = new MetricTimeSeriesConverter();

    UpdateRequestProcessorChain processorChain = req.getCore().getUpdateProcessorChain(req.getParams());
    UpdateRequestProcessor processor = processorChain.createProcessor(req, rsp);
    try {
        for (MetricTimeSeries series : formatParser.parse(stream)) {
            SolrInputDocument document = new SolrInputDocument();
            converter.to(series).getFields().forEach(document::addField);
            storeDocument(document, processor, req);
        }

        if (commit) {
            LOGGER.debug("Committing transaction...");
            processor.processCommit(new CommitUpdateCommand(req, false));
            LOGGER.debug("Committed transaction");
        } else {
            LOGGER.debug("Only adding documents.");
        }
    } finally {
        processor.finish();
    }
}
 
Example 6
Source File: TestApiFramework.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@EndPoint(
    path = "/node/filestore/*",
    method = SolrRequest.METHOD.GET,
    permission = PermissionNameProvider.Name.ALL)
public void read(SolrQueryRequest req, SolrQueryResponse rsp) {
  rsp.add("FSRead.called", "true");
  rsp.add("path", req.getPathTemplateValues().get("*"));
}
 
Example 7
Source File: ReplicationHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void reportErrorOnResponse(SolrQueryResponse response, String message, Exception e) {
  response.add(STATUS, ERR_STATUS);
  response.add(MESSAGE, message);
  if (e != null) {
    response.add(EXCEPTION, e);
  }
}
 
Example 8
Source File: HttpSolrCall.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void writeResponse(SolrQueryResponse solrRsp, QueryResponseWriter responseWriter, Method reqMethod)
    throws IOException {
  try {
    Object invalidStates = solrReq.getContext().get(CloudSolrClient.STATE_VERSION);
    //This is the last item added to the response and the client would expect it that way.
    //If that assumption is changed , it would fail. This is done to avoid an O(n) scan on
    // the response for each request
    if (invalidStates != null) solrRsp.add(CloudSolrClient.STATE_VERSION, invalidStates);
    // Now write it out
    final String ct = responseWriter.getContentType(solrReq, solrRsp);
    // don't call setContentType on null
    if (null != ct) response.setContentType(ct);

    if (solrRsp.getException() != null) {
      @SuppressWarnings({"rawtypes"})
      NamedList info = new SimpleOrderedMap();
      int code = ResponseUtils.getErrorInfo(solrRsp.getException(), info, log);
      solrRsp.add("error", info);
      response.setStatus(code);
    }

    if (Method.HEAD != reqMethod) {
      OutputStream out = response.getOutputStream();
      QueryResponseWriterUtil.writeQueryResponse(out, responseWriter, solrReq, solrRsp, ct);
    }
    //else http HEAD request, nothing to write out, waited this long just to get ContentType
  } catch (EOFException e) {
    log.info("Unable to write response, client closed connection or we are shutting down", e);
  }
}
 
Example 9
Source File: KnowledgeGraphHandler.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest solrReq, SolrQueryResponse solrRsp)
        throws Exception {
    KnowledgeGraphRequest request = parsePost(solrReq);
    new RequestValidator(solrReq, request).validate();
    ParameterSet parameterSet = new ParameterSet(solrReq.getParams(), defaults, invariants);
    NodeContext context = new NodeContext(request, solrReq, parameterSet);
    RequestTreeRecurser recurser = new RequestTreeRecurser(context);
    KnowledgeGraphResponse response = new KnowledgeGraphResponse();
    response.data = recurser.score();
    solrRsp.add("relatednessResponse", response);
}
 
Example 10
Source File: SecurityConfHandlerZk.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected void getConf(SolrQueryResponse rsp, String key) {
  ZkStateReader.ConfigData map = cores.getZkController().getZkStateReader().getSecurityProps(false);
  Object o = map == null ? null : map.data.get(key);
  if (o == null) {
    rsp.add(CommandOperation.ERR_MSGS, Collections.singletonList("No " + key + " configured"));
  } else {
    rsp.add(key+".enabled", getPlugin(key)!=null);
    rsp.add(key, o);
  }
}
 
Example 11
Source File: CdcrRequestHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void handleDisableBufferAction(SolrQueryRequest req, SolrQueryResponse rsp) {
  if (bufferStateManager.getState() == CdcrParams.BufferState.ENABLED) {
    bufferStateManager.setState(CdcrParams.BufferState.DISABLED);
    bufferStateManager.synchronize();
  }

  rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
 
Example 12
Source File: ContainerPluginsApi.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@EndPoint(method = METHOD.GET,
    path = "/cluster/plugin",
    permission = PermissionNameProvider.Name.COLL_READ_PERM)
public void list(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {
  rsp.add(PLUGIN, plugins(zkClientSupplier));
}
 
Example 13
Source File: StreamHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void handleAdmin(SolrQueryRequest req, SolrQueryResponse rsp, SolrParams params) {
  String action = params.get("action").toLowerCase(Locale.ROOT).trim();
  if ("plugins".equals(action)) {
    rsp.add("plugins", (MapWriter) ew -> streamFactory.getFunctionNames().forEach((s, classSupplier) -> ew.putNoEx(s, classSupplier.get().getName())));
    return;
  }

  if ("list".equals(action)) {
    Collection<DaemonStream> vals = daemons.values();
    rsp.add(StreamParams.RESULT_SET, new DaemonCollectionStream(vals));
    return;
  }

  String id = params.get(ID);
  DaemonStream d = daemons.get(id);
  if (d == null) {
    rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon:" + id + " not found on " + coreName));
    return;
  }

  switch (action) {
    case "stop":
      d.close();
      rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon:" + id + " stopped on " + coreName));
      break;

    case "start":
      try {
        d.open();
      } catch (IOException e) {
        rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon: " + id + " error: " + e.getMessage()));
      }
      rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon:" + id + " started on " + coreName));
      break;

    case "kill":
      daemons.remove(id);
      d.close(); // we already found it in the daemons list, so we don't need to verify we removed it.
      rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon:" + id + " killed on " + coreName));
      break;

    default:
      rsp.add(StreamParams.RESULT_SET, new DaemonResponseStream("Daemon:" + id + " action '"
          + action + "' not recognized on " + coreName));
      break;
  }
}
 
Example 14
Source File: CdcrRequestHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void handleCancelBootstrap(SolrQueryRequest req, SolrQueryResponse rsp) {
  BootstrapCallable callable = (BootstrapCallable)core.getSolrCoreState().getCdcrBootstrapCallable();
  IOUtils.closeQuietly(callable);
  rsp.add(RESPONSE_STATUS, "cancelled");
}
 
Example 15
Source File: RequestHandlerUtils.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * A common way to mark the response format as experimental
 */
public static void addExperimentalFormatWarning( SolrQueryResponse rsp )
{
  rsp.add( "WARNING", "This response format is experimental.  It is likely to change in the future." ); 
}
 
Example 16
Source File: SchemaHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void handleGET(SolrQueryRequest req, SolrQueryResponse rsp) {
  try {
    String path = (String) req.getContext().get("path");
    switch (path) {
      case "/schema":
        rsp.add(IndexSchema.SCHEMA, req.getSchema().getNamedPropertyValues());
        break;
      case "/schema/version":
        rsp.add(IndexSchema.VERSION, req.getSchema().getVersion());
        break;
      case "/schema/uniquekey":
        rsp.add(IndexSchema.UNIQUE_KEY, req.getSchema().getUniqueKeyField().getName());
        break;
      case "/schema/similarity":
        rsp.add(IndexSchema.SIMILARITY, req.getSchema().getSimilarityFactory().getNamedPropertyValues());
        break;
      case "/schema/name": {
        final String schemaName = req.getSchema().getSchemaName();
        if (null == schemaName) {
          String message = "Schema has no name";
          throw new SolrException(SolrException.ErrorCode.NOT_FOUND, message);
        }
        rsp.add(IndexSchema.NAME, schemaName);
        break;
      }
      case "/schema/zkversion": {
        int refreshIfBelowVersion = req.getParams().getInt("refreshIfBelowVersion");
        int zkVersion = -1;
        IndexSchema schema = req.getSchema();
        if (schema instanceof ManagedIndexSchema) {
          ManagedIndexSchema managed = (ManagedIndexSchema) schema;
          zkVersion = managed.getSchemaZkVersion();
          if (refreshIfBelowVersion != -1 && zkVersion < refreshIfBelowVersion) {
            log.info("REFRESHING SCHEMA (refreshIfBelowVersion={}, currentVersion={}) before returning version!"
                , refreshIfBelowVersion, zkVersion);
            ZkSolrResourceLoader zkSolrResourceLoader = (ZkSolrResourceLoader) req.getCore().getResourceLoader();
            ZkIndexSchemaReader zkIndexSchemaReader = zkSolrResourceLoader.getZkIndexSchemaReader();
            managed = zkIndexSchemaReader.refreshSchemaFromZk(refreshIfBelowVersion);
            zkVersion = managed.getSchemaZkVersion();
          }
        }
        rsp.add("zkversion", zkVersion);
        break;
      }
      default: {
        List<String> parts = StrUtils.splitSmart(path, '/', true);
        if (parts.size() > 1 && level2.containsKey(parts.get(1))) {
          String realName = parts.get(1);
          String fieldName = IndexSchema.nameMapping.get(realName);

          String pathParam = level2.get(realName);
          if (parts.size() > 2) {
            req.setParams(SolrParams.wrapDefaults(new MapSolrParams(singletonMap(pathParam, parts.get(2))), req.getParams()));
          }
          @SuppressWarnings({"rawtypes"})
          Map propertyValues = req.getSchema().getNamedPropertyValues(realName, req.getParams());
          Object o = propertyValues.get(fieldName);
          if(parts.size()> 2) {
            String name = parts.get(2);
            if (o instanceof List) {
              @SuppressWarnings({"rawtypes"})
              List list = (List) o;
              for (Object obj : list) {
                if (obj instanceof SimpleOrderedMap) {
                  @SuppressWarnings({"rawtypes"})
                  SimpleOrderedMap simpleOrderedMap = (SimpleOrderedMap) obj;
                  if(name.equals(simpleOrderedMap.get("name"))) {
                    rsp.add(fieldName.substring(0, realName.length() - 1), simpleOrderedMap);
                    return;
                  }
                }
              }
            }
            throw new SolrException(SolrException.ErrorCode.NOT_FOUND, "No such path " + path);
          } else {
            rsp.add(fieldName, o);
          }
          return;
        }

        throw new SolrException(SolrException.ErrorCode.NOT_FOUND, "No such path " + path);
      }
    }

  } catch (Exception e) {
    rsp.setException(e);
  }
}
 
Example 17
Source File: BlobStoreTestRequestHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {
  super.handleRequestBody(req, rsp);
  rsp.add("class", this.getClass().getName());
  rsp.add("x", watchedVal);
}
 
Example 18
Source File: CdcrRequestHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void handleStatusAction(SolrQueryRequest req, SolrQueryResponse rsp) {
  rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
 
Example 19
Source File: ShowFileRequestHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void showFromZooKeeper(SolrQueryRequest req, SolrQueryResponse rsp,
    CoreContainer coreContainer) throws KeeperException,
    InterruptedException, UnsupportedEncodingException {

  SolrZkClient zkClient = coreContainer.getZkController().getZkClient();

  String adminFile = getAdminFileFromZooKeeper(req, rsp, zkClient, hiddenFiles);

  if (adminFile == null) {
    return;
  }

  // Show a directory listing
  List<String> children = zkClient.getChildren(adminFile, null, true);
  if (children.size() > 0) {
    
    NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>();
    for (String f : children) {
      if (isHiddenFile(req, rsp, f, false, hiddenFiles)) {
        continue;
      }

      SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>();
      files.add(f, fileInfo);
      List<String> fchildren = zkClient.getChildren(adminFile + "/" + f, null, true);
      if (fchildren.size() > 0) {
        fileInfo.add("directory", true);
      } else {
        // TODO? content type
        fileInfo.add("size", f.length());
      }
      // TODO: ?
      // fileInfo.add( "modified", new Date( f.lastModified() ) );
    }
    rsp.add("files", files);
  } else {
    // Include the file contents
    // The file logic depends on RawResponseWriter, so force its use.
    ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
    params.set(CommonParams.WT, "raw");
    req.setParams(params);
    ContentStreamBase content = new ContentStreamBase.ByteArrayStream(zkClient.getData(adminFile, null, null, true), adminFile);
    content.setContentType(req.getParams().get(USE_CONTENT_TYPE));
    
    rsp.add(RawResponseWriter.CONTENT, content);
  }
  rsp.setHttpCaching(false);
}
 
Example 20
Source File: FeaturesRequestHandler.java    From ltr4l with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  SimpleOrderedMap<Object> results = new SimpleOrderedMap<Object>();
  String command = req.getParams().required().get("command");
  results.add("command", command);

  if(command.equals("extract")){
    Iterable<ContentStream> ite = req.getContentStreams();
    if(ite == null){
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "no queries found");
    }
    else{
      handleExtract(req, ite, results);
    }
  }
  else if(command.equals("progress")){
    handleProgress(req, results);
  }
  else if(command.equals("download")){
    long procId = req.getParams().required().getLong("procId");
    final boolean delete = req.getParams().getBool("delete", false);
    SimpleOrderedMap<Object> data = download(procId, delete);
    results.add("procId", procId);
    if(data == null){
      FeaturesExtractorManager manager = getManager(procId);
      results.add("done?", manager.isDone());
      results.add("progress", manager.getProgress());
      results.add("result", "the process still runs...");
    }
    else{
      if(delete){
        results.add("deleted", "the process has been removed and the procId is no longer valid");
      }
      results.add("result", data);
    }
  }
  else if(command.equals("delete")){
    handleDelete(req, results);
  }
  else{
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unknown command " + command);
  }

  rsp.add("results", results);
}