Java Code Examples for org.apache.solr.common.util.NamedList#add()

The following examples show how to use org.apache.solr.common.util.NamedList#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: AlfrescoCoreAdminHandler.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Add a nodeid, txid, acltxid, aclid or SOLR query to be reindexed on the
 * next maintenance operation performed by MetadataTracker and AclTracker.
 *
 * Asynchronous execution
 *
 * @param params Query Request with following parameters:
 * - core, mandatory: The name of the SOLR Core
 * - txid, optional, the number of the Transaction to reindex
 * - acltxid, optional, the number of the ACL Transaction to reindex
 * - nodeId, optional, the number of the node to reindex
 * - aclid, optional, the number of the ACL to reindex
 * - query, optional, SOLR Query to reindex results
 * @return Response including the action result:
 * - action.status: scheduled, as it will be executed by Trackers on the next maintenance operation
 */
private NamedList<Object> actionREINDEX(SolrParams params)
{
    Consumer<String> reindexOnSpecificCore = coreName -> {
        final MetadataTracker metadataTracker = trackerRegistry.getTrackerForCore(coreName, MetadataTracker.class);
        final AclTracker aclTracker = trackerRegistry.getTrackerForCore(coreName, AclTracker.class);

        apply(params, ARG_TXID, metadataTracker::addTransactionToReindex);
        apply(params, ARG_ACLTXID, aclTracker::addAclChangeSetToReindex);
        apply(params, ARG_NODEID, metadataTracker::addNodeToReindex);
        apply(params, ARG_ACLID, aclTracker::addAclToReindex);

        ofNullable(params.get(ARG_QUERY)).ifPresent(metadataTracker::addQueryToReindex);
    };

    String requestedCoreName = coreName(params);

    coreNames().stream()
            .filter(coreName -> requestedCoreName == null || coreName.equals(requestedCoreName))
            .filter(this::isMasterOrStandalone)
            .forEach(reindexOnSpecificCore);

    NamedList<Object> response = new SimpleOrderedMap<>();
    response.add(ACTION_STATUS_LABEL, ACTION_STATUS_SCHEDULED);
    return response;
}
 
Example 2
Source File: SignatureUpdateProcessorFactoryTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailNonIndexedSigWithOverwriteDupes() throws Exception {
  SolrCore core = h.getCore();
  SignatureUpdateProcessorFactory f = new SignatureUpdateProcessorFactory();
  NamedList<String> initArgs = new NamedList<>();
  initArgs.add("overwriteDupes", "true");
  initArgs.add("signatureField", "signatureField_sS");
  f.init(initArgs);
  boolean exception_ok = false;
  try {
    f.inform(core);
  } catch (Exception e) {
    exception_ok = true;
  }
  assertTrue("Should have gotten an exception from inform(SolrCore)", 
             exception_ok);
}
 
Example 3
Source File: DebugComponent.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private NamedList<String> getTrackResponse(ShardResponse shardResponse) {
  NamedList<String> namedList = new SimpleOrderedMap<>();
  if (shardResponse.getException() != null) {
    namedList.add("Exception", shardResponse.getException().getMessage());
    return namedList;
  }
  NamedList<Object> responseNL = shardResponse.getSolrResponse().getResponse();
  @SuppressWarnings("unchecked")
  NamedList<Object> responseHeader = (NamedList<Object>)responseNL.get("responseHeader");
  if(responseHeader != null) {
    namedList.add("QTime", responseHeader.get("QTime").toString());
  }
  namedList.add("ElapsedTime", String.valueOf(shardResponse.getSolrResponse().getElapsedTime()));
  namedList.add("RequestPurpose", shardResponse.getShardRequest().params.get(CommonParams.REQUEST_PURPOSE));
  SolrDocumentList docList = (SolrDocumentList)shardResponse.getSolrResponse().getResponse().get("response");
  if(docList != null) {
    namedList.add("NumFound", String.valueOf(docList.getNumFound()));
  }
  namedList.add("Response", String.valueOf(responseNL));
  return namedList;
}
 
Example 4
Source File: TestSimpleXJoinResultsFactory.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testJson() throws IOException {
  NamedList args = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());
  
  NamedList globalPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
  globalPaths.add("total", "$.count");
  
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.hits[*].id");
  
  NamedList resultPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_RESULT_FIELD_PATHS, resultPaths);
  resultPaths.add("colour", "$.hits[?(@.id == 'JOINID')].colour");
  resultPaths.add("value", "$.meta[?(@.id == 'JOINID')].value");
  
  testResultsFile(args, true, true);
}
 
Example 5
Source File: HandlerReportHelper.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
static NamedList<Object> buildAclTxReport(TrackerRegistry trackerRegistry, InformationServer srv, String coreName, AclTracker tracker, Long acltxid) throws JSONException
{
    try {
        NamedList<Object> nr = new SimpleOrderedMap<>();
        nr.add("TXID", acltxid);
        nr.add("transaction", buildTrackerReport(trackerRegistry, srv, coreName, 0L, 0L, acltxid, acltxid, null, null));
        NamedList<Object> nodes = new SimpleOrderedMap<>();

        // add node reports ....
        List<Long> dbAclIds = tracker.getAclsForDbAclTransaction(acltxid);
        for (Long aclid : dbAclIds) {
            nodes.add("ACLID " + aclid, buildAclReport(tracker, aclid));
        }
        nr.add("aclTxDbAclCount", dbAclIds.size());
        nr.add("nodes", nodes);
        return nr;
    }
    catch (Exception exception)
    {
        throw new AlfrescoRuntimeException("", exception);
    }
}
 
Example 6
Source File: QueryDocAuthorizationComponentTest.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
/**
 * Test a request from a user coming from an empty group.
 * This request should be rejected because otherwise document-level
 * filtering will be skipped.
 */
@Test
public void testEmptyGroup() throws Exception {
  String user = "bogusUser";
  try {
    NamedList args = new NamedList();
    args.add(QueryDocAuthorizationComponent.ENABLED_PROP, "true");
    ResponseBuilder builder = runComponent(user, args, null);

    checkParams(null, builder);
    Assert.fail("Expected SolrException");
  } catch (SolrException ex) {
    assertEquals(ex.code(), SolrException.ErrorCode.UNAUTHORIZED.code);
    assertTrue(ex.getMessage().contains(
      user + " rejected because user is not associated with any roles"));
  }
}
 
Example 7
Source File: SkipExistingDocumentsProcessorFactoryTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testSkipUpdatesTrueIfInitArgsFalseButTrueStringInRequest() {
  SkipExistingDocumentsProcessorFactory factory = new SkipExistingDocumentsProcessorFactory();
  NamedList<Object> initArgs = new NamedList<>();
  initArgs.add("skipInsertIfExists", true);
  initArgs.add("skipUpdateIfMissing", false);
  factory.init(initArgs);
  NamedList<Object> requestArgs = new NamedList<>();
  requestArgs.add("skipUpdateIfMissing", "true");
  SolrQueryRequest req = new LocalSolrQueryRequest(null, requestArgs);
  UpdateRequestProcessor next = Mockito.mock(DistributedUpdateProcessor.class);

  SkipExistingDocumentsUpdateProcessor processor = factory.getInstance(req, new SolrQueryResponse(), next);
  assertTrue("Expected skipInsertIfExists to be true", processor.isSkipInsertIfExists());
  assertTrue("Expected skipUpdateIfMissing to be true", processor.isSkipUpdateIfMissing());
}
 
Example 8
Source File: ContentSizeGroupingCollector.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void finish() throws IOException 
{
    NamedList<Object> analytics = new NamedList<>();
    rb.rsp.add("analytics", analytics);
    NamedList<Object> fieldCounts = new NamedList<>(); 
    analytics.add("contentSize()", fieldCounts);

    for(Bucket bucket :stats.getHistogram())
    {
        fieldCounts.add("["+(long)Math.ceil(bucket.leftBoundary)+ " TO "+(long)Math.ceil(bucket.rightBoundary)+">", (long)roundEven(bucket.countLeft + bucket.countRight));
    }


    if(this.delegate instanceof DelegatingCollector) {
        ((DelegatingCollector)this.delegate).finish();
    }
}
 
Example 9
Source File: PerSegmentSingleValuedFaceting.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private NamedList<Integer> finalize(NamedList<Integer> res, int missingCount, boolean hasMissingCount)
    throws IOException {
  if (missing) {
    if (!hasMissingCount) {
      missingCount = SimpleFacets.getFieldMissingCount(searcher,docs,fieldName);
    }
    res.add(null, missingCount);
  }

  return res;
}
 
Example 10
Source File: DocValuesFacets.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** finalizes result: computes missing count if applicable */
static NamedList<Integer> finalize(NamedList<Integer> res, SolrIndexSearcher searcher, SchemaField schemaField, DocSet docs, int missingCount, boolean missing) throws IOException {
  if (missing) {
    if (missingCount < 0) {
      missingCount = SimpleFacets.getFieldMissingCount(searcher,docs,schemaField.getName());
    }
    res.add(null, missingCount);
  }
  
  return res;
}
 
Example 11
Source File: TestRedisQParserPlugin.java    From solr-redis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConfigurePoolWithCustomTimeout() {
  final NamedList<String> list = new NamedList<>();
  list.add("timeout", "100");
  parserPlugin.init(list);

  verify(parserPlugin).createPool(poolConfigArgument.capture(), eq(HostAndPort.LOCALHOST_STR),
      eq(Protocol.DEFAULT_PORT), eq(100), passwordArgument.capture(),
      eq(Protocol.DEFAULT_DATABASE));
  verify(parserPlugin).createCommandHandler(poolArgument.capture(), eq(1));

  assertNull(passwordArgument.getValue());
  assertEquals(5, poolConfigArgument.getValue().getMaxTotal());
}
 
Example 12
Source File: AlfrescoLukeRequestHandler.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
public NamedList<Integer> toNamedList() {
	NamedList<Integer> nl = new NamedList<>();
	for (int bucket = 0; bucket <= _maxBucket; bucket++) {
		nl.add("" + (1 << bucket), _buckets[bucket]);
	}
	return nl;
}
 
Example 13
Source File: SpatialHeatmapFacets.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** Called by FacetComponent's impl of
 * {@link org.apache.solr.handler.component.SearchComponent#finishStage(ResponseBuilder)}. */
@SuppressWarnings({"unchecked", "rawtypes"})
public static NamedList distribFinish(LinkedHashMap<String, HeatmapFacet> heatmapInfos, ResponseBuilder rb) {
  NamedList<NamedList<Object>> result = new SimpleOrderedMap<>();
  for (Map.Entry<String, HeatmapFacet> entry : heatmapInfos.entrySet()) {
    final HeatmapFacet facet = entry.getValue();
    result.add(entry.getKey(), (NamedList<Object>) facet.jsonFacetMerger.getMergedResult());
  }
  return result;
}
 
Example 14
Source File: DeleteNodeCmd.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void call(ClusterState state, ZkNodeProps message, @SuppressWarnings({"rawtypes"})NamedList results) throws Exception {
  ocmh.checkRequired(message, "node");
  String node = message.getStr("node");
  List<ZkNodeProps> sourceReplicas = ReplaceNodeCmd.getReplicasOfNode(node, state);
  List<String> singleReplicas = verifyReplicaAvailability(sourceReplicas, state);
  if (!singleReplicas.isEmpty()) {
    results.add("failure", "Can't delete the only existing non-PULL replica(s) on node " + node + ": " + singleReplicas.toString());
  } else {
    cleanupReplicas(results, state, sourceReplicas, ocmh, node, message.getStr(ASYNC));
  }
}
 
Example 15
Source File: AnalyticsGroupingManager.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Create the response for this grouping, but in the old style of response.
 * This response has a bucket for the following if they are contained in the grouping:
 * FieldFacets, RangeFacets and QueryFacets.
 * Each facet's name and response are put into the bucket corresponding to its type.
 * <p>
 * Since groupings in the old notation must also return overall results, the overall results are
 * passed in and the values are used to populate the grouping response.
 *
 * @param overallResults of the expressions to add to the grouping response
 * @return the named list representation of the response
 */
public NamedList<Object> createOldResponse(Map<String,Object> overallResults) {
  NamedList<Object> response = new NamedList<>();

  topLevelExpressions.forEach( expression -> response.add(expression.getName(), overallResults.get(name + expression.getName())));

  NamedList<Object> fieldFacetResults = new NamedList<>();
  NamedList<Object> rangeFacetResults = new NamedList<>();
  NamedList<Object> queryFacetResults = new NamedList<>();
  // Add the field facet buckets to the output
  facets.forEach( (name, facet) -> {
    // The old style of request only accepts field facets
    // So we can assume that all value facets are field facets
    if (facet instanceof ValueFacet) {
      fieldFacetResults.add(name, facet.createOldResponse());
    } else if (facet instanceof RangeFacet) {
      rangeFacetResults.add(name, facet.createOldResponse());
    } else if (facet instanceof QueryFacet) {
      queryFacetResults.add(name, facet.createOldResponse());
    }
  });
  if (fieldFacetResults.size() > 0) {
    response.add(AnalyticsResponseHeadings.FIELD_FACETS, fieldFacetResults);
  }
  if (rangeFacetResults.size() > 0) {
    response.add(AnalyticsResponseHeadings.RANGE_FACETS, rangeFacetResults);
  }
  if (queryFacetResults.size() > 0) {
    response.add(AnalyticsResponseHeadings.QUERY_FACETS, queryFacetResults);
  }
  return response;
}
 
Example 16
Source File: MappingJacksonResponseParser.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public NamedList<Object> processResponse(InputStream body, String encoding) {

	NamedList<Object> result = new NamedList<Object>();
	try {
		result.add("json", StreamUtils.copyToString(body, Charset.forName(encoding)));
	} catch (IOException e) {
		throw new InvalidDataAccessResourceUsageException("Unable to read json from stream.", e);
	}
	return result;
}
 
Example 17
Source File: SkipExistingDocumentsProcessorFactoryTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipUpdatesFalseIfInitArgsTrueButFalseBooleanInRequest() {
  SkipExistingDocumentsProcessorFactory factory = new SkipExistingDocumentsProcessorFactory();
  NamedList<Object> initArgs = new NamedList<>();
  initArgs.add("skipUpdateIfMissing", true);
  factory.init(initArgs);
  NamedList<Object> requestArgs = new NamedList<>();
  requestArgs.add("skipUpdateIfMissing", false);
  SolrQueryRequest req = new LocalSolrQueryRequest(null, requestArgs);
  UpdateRequestProcessor next = Mockito.mock(DistributedUpdateProcessor.class);

  SkipExistingDocumentsUpdateProcessor processor = factory.getInstance(req, new SolrQueryResponse(), next);
  assertTrue("Expected skipInsertIfExists to be true", processor.isSkipInsertIfExists());
  assertFalse("Expected skipUpdateIfMissing to be false", processor.isSkipUpdateIfMissing());
}
 
Example 18
Source File: BoostQParserPlugin.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
  return new QParser(qstr, localParams, params, req) {
    QParser baseParser;
    ValueSource vs;
    String b;

    @Override
    public Query parse() throws SyntaxError {
      b = localParams.get(BOOSTFUNC);
      baseParser = subQuery(localParams.get(QueryParsing.V), null);
      Query q = baseParser.getQuery();

      if (b == null) return q;
      Query bq = subQuery(b, FunctionQParserPlugin.NAME).getQuery();
      if (bq instanceof FunctionQuery) {
        vs = ((FunctionQuery)bq).getValueSource();
      } else {
        vs = new QueryValueSource(bq, 0.0f);
      }
      return FunctionScoreQuery.boostByValue(q, vs.asDoubleValuesSource());
    }


    @Override
    public String[] getDefaultHighlightFields() {
      return baseParser.getDefaultHighlightFields();
    }
                                         
    @Override
    public Query getHighlightQuery() throws SyntaxError {
      return baseParser.getHighlightQuery();
    }

    @Override
    public void addDebugInfo(NamedList<Object> debugInfo) {
      // encapsulate base debug info in a sub-list?
      baseParser.addDebugInfo(debugInfo);
      debugInfo.add("boost_str",b);
      debugInfo.add("boost_parsed",vs);
    }
  };
}
 
Example 19
Source File: AutoCompleteRequestHandler.java    From solr-autocomplete with Apache License 2.0 3 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest request, SolrQueryResponse response) throws Exception {

    String searchString = request.getParams().get("searchString");

    searchString = searchString.trim();

    try {
        DLLIterator it = service.matchPrefix(searchString).iterator();

        List<NamedList<String>> matches = new ArrayList<NamedList<String>>();

        while (it.hasNext()) {
            String word = (String) it.next();

            NamedList<String> node = new SimpleOrderedMap<String>();
            node.add("Title", word);

            matches.add(node);
        }

        if (matches.size() > 0) {

            response.add("ResultSet", matches);
        }
    }

    catch (RuntimeException e) {
        response.add("status", "failed");
    }

}
 
Example 20
Source File: SolrStartupListener.java    From apache-solr-essentials with Apache License 2.0 3 votes vote down vote up
/**
* Add the {@link org.apache.solr.common.params.EventParams#EVENT} with either the {@link org.apache.solr.common.params.EventParams#NEW_SEARCHER}
* or {@link org.apache.solr.common.params.EventParams#FIRST_SEARCHER} values depending on the value of currentSearcher.
* <p/>
*
* Note: this method has been copied from {@link AbstractSolrEventListener}. 
* It wasn't possible to directly subclass that supertype because it requires a constructor that accepts a {@link SolrCore}, 
* which we don't have in this event listener (at construction time).
*
* @param currentSearcher If null, add FIRST_SEARCHER, otherwise NEW_SEARCHER
* @param args The named list to add the EVENT value to
*/
@SuppressWarnings("unchecked")
void addEventParms(final SolrIndexSearcher currentSearcher, final NamedList args) {
	if (currentSearcher != null) {
		args.add(EventParams.EVENT, EventParams.NEW_SEARCHER);
	} else {
		args.add(EventParams.EVENT, EventParams.FIRST_SEARCHER);
	}
}