org.apache.solr.common.util.SimpleOrderedMap Java Examples

The following examples show how to use org.apache.solr.common.util.SimpleOrderedMap. 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: SuggesterResponse.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public SuggesterResponse(Map<String, NamedList<Object>> suggestInfo) {
  for (Map.Entry<String, NamedList<Object>> entry : suggestInfo.entrySet()) {
    SimpleOrderedMap suggestionsNode = (SimpleOrderedMap) entry.getValue().getVal(0);
    List<SimpleOrderedMap> suggestionListToParse;
    List<Suggestion> suggestionList = new LinkedList<>();
    if (suggestionsNode != null) {

      suggestionListToParse = (List<SimpleOrderedMap>) suggestionsNode.get(SUGGESTIONS_NODE_NAME);
      for (SimpleOrderedMap suggestion : suggestionListToParse) {
        String term = (String) suggestion.get(TERM_NODE_NAME);
        long weight = (long) suggestion.get(WEIGHT_NODE_NAME);
        String payload = (String) suggestion.get(PAYLOAD_NODE_NAME);

        Suggestion parsedSuggestion = new Suggestion(term, weight, payload);
        suggestionList.add(parsedSuggestion);
      }
      suggestionsPerDictionary.put(entry.getKey(), suggestionList);
    }
  }
}
 
Example #2
Source File: SolrPluginUtils.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an NamedList of Explanations for each item in a list of docs.
 *
 * @param query The Query you want explanations in the context of
 * @param docs The Documents you want explained relative that query
 */
public static NamedList<Explanation> getExplanations
  (Query query,
   DocList docs,
   SolrIndexSearcher searcher,
   IndexSchema schema) throws IOException {

  NamedList<Explanation> explainList = new SimpleOrderedMap<>();
  DocIterator iterator = docs.iterator();
  for (int i=0; i<docs.size(); i++) {
    int id = iterator.nextDoc();

    Document doc = searcher.doc(id);
    String strid = schema.printableUniqueKey(doc);

    explainList.add(strid, searcher.explain(query, id) );
  }
  return explainList;
}
 
Example #3
Source File: AbstractXJoinTestCase.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected NamedList test(ModifiableSolrParams params, String componentName) {
  SolrCore core = h.getCore();

  SearchComponent sc = core.getSearchComponent(componentName);
  assertTrue("XJoinSearchComponent not found in solrconfig", sc != null);
    
  QParserPlugin qp = core.getQueryPlugin("xjoin");
  assertTrue("XJoinQParserPlugin not found in solrconfig", qp != null);
  
  params.add("q", "*:*");
  params.add("fq", "{!xjoin}" + componentName);

  SolrQueryResponse rsp = new SolrQueryResponse();
  rsp.add("responseHeader", new SimpleOrderedMap<>());
  SolrQueryRequest req = new LocalSolrQueryRequest(core, params);

  SolrRequestHandler handler = core.getRequestHandler("standard");
  handler.handleRequest(req, rsp);
  req.close();
  assertNull(rsp.getException());
    
  return rsp.getValues();
}
 
Example #4
Source File: TestJsonFacetRefinement.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Use SimpleOrderedMap rather than Map to match responses from shards
 */
public static Object fromJSON(String json) throws IOException {
  JSONParser parser = new JSONParser(json);
  ObjectBuilder ob = new ObjectBuilder(parser) {
    @Override
    @SuppressWarnings({"rawtypes"})
    public Object newObject() throws IOException {
      return new SimpleOrderedMap();
    }

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void addKeyVal(Object map, Object key, Object val) throws IOException {
      ((SimpleOrderedMap) map).add(key.toString(), val);
    }
  };

  return ob.getObject();
}
 
Example #5
Source File: TaggedQueryHighlighter.java    From solr-redis with Apache License 2.0 6 votes vote down vote up
/**
 * Merges all parial results to single response for Solr highlighting
 *
 * @param results Partial results from default highlighting and tagged queries highlighting.
 * @return Returns merged results of default highlighting and tagged queries highlighting.
 */
private SimpleOrderedMap mergeResults(final Map<String, SimpleOrderedMap> results) {
  final SimpleOrderedMap mergedResult = new SimpleOrderedMap();
  for (final Map.Entry<String, SimpleOrderedMap> partialResultEntry : results.entrySet()) {
    for (final Object subResultEntryObject : partialResultEntry.getValue()) {
      final Map.Entry<String, Object> subResultEntry = (Map.Entry<String, Object>) subResultEntryObject;
      for (final Object docEntryObject : (Iterable<? extends Object>) subResultEntry.getValue()) {
        final Map.Entry<String, Object> docEntry = (Map.Entry<String, Object>) docEntryObject;
        String fieldName = partialResultEntry.getKey();
        //If results are from main highlight we should add original field name. In other case we should use
        //field alias which comes from tagged query
        if (MAIN_HIGHLIGHT.equals(fieldName)) {
          fieldName = docEntry.getKey();
        }
        addFragmentToDoc(mergedResult, subResultEntry.getKey(), fieldName, (String[]) docEntry.getValue());
      }
    }
  }
  return mergedResult;
}
 
Example #6
Source File: MtasSolrResultUtil.java    From mtas with Apache License 2.0 6 votes vote down vote up
/**
 * Rewrite merge data.
 *
 * @param key the key
 * @param subKey the sub key
 * @param snl the snl
 * @param tnl the tnl
 */
@SuppressWarnings({ "unused", "unchecked" })
private static void rewriteMergeData(String key, String subKey,
    NamedList<Object> snl, NamedList<Object> tnl) {
  if (snl != null) {
    Object o = tnl.get(key);
    NamedList<Object> tnnnl;
    if (o != null && o instanceof NamedList) {
      tnnnl = (NamedList<Object>) o;
    } else {
      tnnnl = new SimpleOrderedMap<>();
      tnl.add(key, tnnnl);
    }
    tnnnl.add(subKey, snl);
  }
}
 
Example #7
Source File: HandlerReportHelper.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
static NamedList<Object> buildTxReport(TrackerRegistry trackerRegistry, InformationServer srv, String coreName, MetadataTracker tracker, Long txid) throws JSONException
{
    NamedList<Object> nr = new SimpleOrderedMap<>();
    nr.add("TXID", txid);
    nr.add("transaction", buildTrackerReport(trackerRegistry, srv, coreName, txid, txid, 0L, 0L, null, null));
    NamedList<Object> nodes = new SimpleOrderedMap<>();

    // add node reports ....
    List<Node> dbNodes = tracker.getFullNodesForDbTransaction(txid);
    for (Node node : dbNodes)
    {
        nodes.add("DBID " + node.getId(), buildNodeReport(tracker, node));
    }

    nr.add("txDbNodeCount", dbNodes.size());
    nr.add("nodes", nodes);
    return nr;
}
 
Example #8
Source File: FacetDebugInfo.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public SimpleOrderedMap<Object> getFacetDebugInfo() {
  SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
  
  if (filter != null) info.add("filter", filter);
  if (processor != null) info.add("processor", processor);
  if (elapse != -1) info.add("elapse", elapse);
  if (reqDescription != null) {
    info.addAll(reqDescription);
  } 
  info.addAll(this.info);
  
  if (children != null && children.size() > 0) {
    List<Object> subfacet = new ArrayList<Object>();
    info.add("sub-facet", subfacet);
    for (FacetDebugInfo child : children) {
      subfacet.add(child.getFacetDebugInfo());
    }
  }     
  return info;
}
 
Example #9
Source File: NodeNormalizer.java    From semantic-knowledge-graph with Apache License 2.0 6 votes vote down vote up
private void populateNorms(AggregationWaitable runner,
                           String requestValue,
                           LinkedList<String> normalizedStrings,
                           LinkedList<SimpleOrderedMap<String>> normalizedMaps) {
    for(SimpleOrderedMap<Object> bucket : runner.buckets)
    {
        SimpleOrderedMap<String> facetResult = runner.adapter.getMapValue(bucket);
        if(MapUtility.mapContainsValue(requestValue.toLowerCase(), facetResult))
        {
            normalizedStrings.add(runner.adapter.getStringValue(bucket));
            normalizedMaps.add(runner.adapter.getMapValue(bucket));
            return;
        }
    }
    normalizedStrings.add(requestValue);
    normalizedMaps.add(null);
}
 
Example #10
Source File: PhrasesIdentificationComponent.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(ResponseBuilder rb) throws IOException {
  final PhrasesContextData contextData = (PhrasesContextData) rb.req.getContext().get(this.getClass());
  if (null == contextData) {
    // if prepare didn't give us anything to work with, then we should do nothing
    return;
  }

  // regardless of single node / shard, we need local stats...
  Phrase.populateStats(contextData.allPhrases, contextData.fieldWeights.keySet(), rb.req.getSearcher());

  if ( rb.req.getParams().getBool(ShardParams.IS_SHARD, false) ) {
    // shard request, return stats for all phrases (in original order)
    SimpleOrderedMap<Object> output = new SimpleOrderedMap<>();
    output.add("_all", Phrase.formatShardResponse(contextData.allPhrases));
    // TODO: might want to add numDocs() & getSumTotalTermFreq(f)/getDocCount(f) stats from each field...
    // so that we can sum/merge them for use in scoring?
    rb.rsp.add("phrases", output);
  } else {
    // full single node request...
    scoreAndAddResultsToResponse(rb, contextData);
  }
}
 
Example #11
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 #12
Source File: AbstractXJoinTestCase.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected NamedList test(ModifiableSolrParams params, String componentName) {
  SolrCore core = h.getCore();

  SearchComponent sc = core.getSearchComponent(componentName);
  assertTrue("XJoinSearchComponent not found in solrconfig", sc != null);
    
  QParserPlugin qp = core.getQueryPlugin("xjoin");
  assertTrue("XJoinQParserPlugin not found in solrconfig", qp != null);
  
  params.add("q", "*:*");
  params.add("fq", "{!xjoin}" + componentName);

  SolrQueryResponse rsp = new SolrQueryResponse();
  rsp.add("responseHeader", new SimpleOrderedMap<>());
  SolrQueryRequest req = new LocalSolrQueryRequest(core, params);

  SolrRequestHandler handler = core.getRequestHandler("standard");
  handler.handleRequest(req, rsp);
  req.close();
  assertNull(rsp.getException());
    
  return rsp.getValues();
}
 
Example #13
Source File: TestToleratedUpdateError.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void testParseMap() {
  // trivial
  @SuppressWarnings({"rawtypes"})
  SimpleOrderedMap valid = new SimpleOrderedMap<String>();
  valid.add("type", CmdType.ADD.toString());
  valid.add("id", "some id");
  valid.add("message", "some message");
  
  ToleratedUpdateError in = ToleratedUpdateError.parseMap(valid);
  compare(in, MAP_COPPIER);
  compare(in, METADATA_COPPIER);

  // randomized
  int numIters = atLeast(5000);
  for (int i = 0; i < numIters; i++) {
    valid = new SimpleOrderedMap<String>();
    valid.add("type", ALL_TYPES[TestUtil.nextInt(random(), 0, ALL_TYPES.length-1)].toString());
    valid.add("id", TestUtil.randomUnicodeString(random()));
    valid.add("message", TestUtil.randomUnicodeString(random()));
    
    in = ToleratedUpdateError.parseMap(valid);
    compare(in, MAP_COPPIER);
    compare(in, METADATA_COPPIER);
  }
}
 
Example #14
Source File: AlfrescoCoreAdminHandlerIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void coreNamesAreTrimmed_oneCoreNameAtTime() {
    AlfrescoCoreAdminHandler spy = spy(new AlfrescoCoreAdminHandler() {
        @Override
        protected NamedList<Object> newCore(String coreName, int numShards, StoreRef storeRef, String templateName, int replicationFactor, int nodeInstance, int numNodes, String shardIds, Properties extraProperties)
        {
            // Do nothing here otherwise we cannot spy it
            return new SimpleOrderedMap<>();
        }
    });

    // First let's try a list of names, one by one
    final List<String> coreNames =
            asList(
                    ARCHIVE_CORE_NAME + "  ", // whitespace char at the end
                    "\t " + ALFRESCO_CORE_NAME, // whitespace chars at the beginning
                    "   " + VERSION_CORE_NAME + "  \t", // beginning and end
                    "   \t"); // empty name

    coreNames.forEach(spy::setupNewDefaultCores);

    verify(spy).newCore(eq(ARCHIVE_CORE_NAME), eq(1), eq(STORE_REF_MAP.get(ARCHIVE_CORE_NAME)), anyString(), eq(1), eq(1), eq(1), eq(null), eq(null));
    verify(spy).newCore(eq(ALFRESCO_CORE_NAME), eq(1), eq(STORE_REF_MAP.get(ALFRESCO_CORE_NAME)), anyString(), eq(1), eq(1), eq(1), eq(null), eq(null));
    verify(spy).newCore(eq(VERSION_CORE_NAME), eq(1), eq(STORE_REF_MAP.get(VERSION_CORE_NAME)), anyString(), eq(1), eq(1), eq(1), eq(null), eq(null));
}
 
Example #15
Source File: RangeFacetRequest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to merge range facet values from a shard's response to already accumulated
 * values for each range.
 *
 * @param rangeCounts a {@link LinkedHashMap} containing the accumulated values for each range
 *                    keyed by the 'key' of the facet.range. Must not be null.
 * @param shardRanges the facet_ranges response from a shard. Must not be null.
 */
public static void mergeFacetRangesFromShardResponse(LinkedHashMap<String, DistribRangeFacet> rangeCounts,
                                                     SimpleOrderedMap<SimpleOrderedMap<Object>> shardRanges) {
  assert shardRanges != null;
  assert rangeCounts != null;
  for (Map.Entry<String, SimpleOrderedMap<Object>> entry : shardRanges) {
    String rangeKey = entry.getKey();

    RangeFacetRequest.DistribRangeFacet existing = rangeCounts.get(rangeKey);
    if (existing == null) {
      rangeCounts.put(rangeKey, new RangeFacetRequest.DistribRangeFacet(entry.getValue()));
    } else {
      existing.mergeContributionFromShard(entry.getValue());
    }
  }
}
 
Example #16
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 #17
Source File: AlfrescoCoreAdminHandler.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
NamedList<Object> manageTransactionsToBeFixed(
        IOpenBitSet transactions,
        LongToIntFunction nodesCounter,
        Consumer<Long> scheduler,
        AtomicInteger limit)
{
    final NamedList<Object> transactionsList = new SimpleOrderedMap<>();

    long txid = -1;
    while ((txid = transactions.nextSetBit(txid + 1)) != -1 && limit.decrementAndGet() >= 0)
    {
        transactionsList.add(String.valueOf(txid), nodesCounter.applyAsInt(txid));
        scheduler.accept(txid);
    }

    return transactionsList;
}
 
Example #18
Source File: TreeFacetField.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * Convert this object to a SimpleOrderedMap, making it easier to serialize.
 * @return the equivalent SimpleOrderedMap for this object.
 */
public SimpleOrderedMap<Object> toMap() {
	SimpleOrderedMap<Object> map = new SimpleOrderedMap<>();
	
	if (label != null) {
		map.add(LABEL_KEY, label);
	}
	map.add(VALUE_KEY, value);
	map.add(COUNT_KEY, count);
	map.add(TOTAL_KEY, getTotal());
	if (hierarchy != null && hierarchy.size() > 0) {
		// Recurse through the child nodes, converting each to a map
		List<NamedList<Object>> hierarchyList = 
				hierarchy.stream().map(TreeFacetField::toMap).collect(Collectors.toList());
		map.add(HIERARCHY_KEY, hierarchyList);
	}
	
	return map;
}
 
Example #19
Source File: UniqueSlotAcc.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private Object getShardHLL(int slot) throws IOException {
  FixedBitSet ords = arr[slot];
  if (ords == null) return HLLAgg.NO_VALUES;

  HLL hll = factory.getHLL();
  long maxOrd = ords.length();
  Hash.LongPair hashResult = new Hash.LongPair();
  for(int ord=-1; ++ord < maxOrd;) {
    ord = ords.nextSetBit(ord);
    if (ord == DocIdSetIterator.NO_MORE_DOCS) break;
    BytesRef val = lookupOrd(ord);
    // way to avoid recomputing hash across slots?  Prob not worth space
    Hash.murmurhash3_x64_128(val.bytes, val.offset, val.length, 0, hashResult);
    // idea: if the set is small enough, just send the hashes?  We can add at the top
    // level or even just do a hash table at the top level.
    hll.addRaw(hashResult.val1);
  }

  SimpleOrderedMap map = new SimpleOrderedMap();
  map.add("hll", hll.toBytes());
  return map;
}
 
Example #20
Source File: SystemInfoHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Get system info
 */
public static SimpleOrderedMap<Object> getSystemInfo() {
  SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
  
  OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
  info.add(NAME, os.getName()); // add at least this one
  // add remaining ones dynamically using Java Beans API
  // also those from JVM implementation-specific classes
  MetricUtils.addMXBeanMetrics(os, MetricUtils.OS_MXBEAN_CLASSES, null, (name, metric) -> {
    if (info.get(name) == null) {
      info.add(name, ((Gauge) metric).getValue());
    }
  });

  return info;
}
 
Example #21
Source File: NodeGeneratorTest.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
@Test
public void addGeneratedValues() throws IOException
{
    ResponseNode response = new ResponseNode("testField");
    response.values = new ResponseValue[2];

    runner.buckets = new LinkedList<>();
    SimpleOrderedMap<Object> generatedValue1 = new SimpleOrderedMap<>();
    generatedValue1.add("val", "generatedValue1");
    SimpleOrderedMap<Object> generatedValue2 = new SimpleOrderedMap<>();
    generatedValue2.add("val", "generatedValue2");
    runner.buckets.add(generatedValue1);
    runner.buckets.add(generatedValue2);
    ResponseValue [] expecteds = new ResponseValue[2];
    expecteds[0] = new ResponseValue("generatedValue1");
    expecteds[0].normalizedValue = new SimpleOrderedMap<>();
    expecteds[0].normalizedValue.add("name", "generatedValue1");
    expecteds[1] = new ResponseValue("generatedValue2");
    expecteds[1].normalizedValue = new SimpleOrderedMap<>();
    expecteds[1].normalizedValue.add("name", "generatedValue2");

    NodeGenerator target = new NodeGenerator();
    Deencapsulation.invoke(target, "addGeneratedValues", response, runner, 0);

    Assert.assertEquals(2, response.values.length);
    for(int i = 0; i < expecteds.length; ++i) {
        Assert.assertTrue(response.values[i].equals(expecteds[i]));
        Assert.assertTrue(MapUtility.mapsEqual(response.values[i].normalizedValue, expecteds[i].normalizedValue));
    }
}
 
Example #22
Source File: TestSolrQueryResponse.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseHeader() throws Exception {
  final SolrQueryResponse response = new SolrQueryResponse();
  assertEquals("responseHeader initially present", null, response.getResponseHeader());
  final NamedList<Object> newValue = new SimpleOrderedMap<>();
  newValue.add("key1", "value1");
  response.add("key2", "value2");
  response.addResponseHeader(newValue);
  assertEquals("responseHeader new value", newValue, response.getResponseHeader());
  response.removeResponseHeader();
  assertEquals("responseHeader removed value", null, response.getResponseHeader());
}
 
Example #23
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 #24
Source File: BaseHttpClusterStateProvider.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes"})
private static Set<String> fetchLiveNodes(SolrClient client) throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set("action", "CLUSTERSTATUS");
  QueryRequest request = new QueryRequest(params);
  request.setPath("/admin/collections");
  NamedList cluster = (SimpleOrderedMap) client.request(request).get("cluster");
  return (Set<String>) new HashSet((List<String>)(cluster.get("live_nodes")));
}
 
Example #25
Source File: ResponseValueTest.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
@Test
public void valuesEqual_equal()
{
    ResponseValue r1 = new ResponseValue("test1", 1.0);
    ResponseValue r2 = new ResponseValue("12 test1", 1.0);

    r2.normalizedValue = new SimpleOrderedMap<>();
    r2.normalizedValue.add("testkey1", "12");
    r2.normalizedValue.add("testkey2", "test1");

    Assert.assertTrue(r1.valuesEqual(r2));
    Assert.assertTrue(r2.valuesEqual(r1));
}
 
Example #26
Source File: CustomHighlightComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getAllHighlights(Object[] objArr) {
  @SuppressWarnings({"rawtypes"})
  final SimpleOrderedMap[] mapArr = (SimpleOrderedMap[])objArr;
  // remove nulls in case not all docs were able to be retrieved
  @SuppressWarnings({"rawtypes"})
  ArrayList<SimpleOrderedMap> mapList = new ArrayList<>();
  for (@SuppressWarnings({"rawtypes"})SimpleOrderedMap map : mapArr) {
    if (map != null) {
      mapList.add(map);
    }
  }
  return mapList;
}
 
Example #27
Source File: FacetModule.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResponses(ResponseBuilder rb, ShardRequest sreq) {
  FacetComponentState facetState = getFacetComponentState(rb);
  if (facetState == null) return;

  for (ShardResponse shardRsp : sreq.responses) {
    SolrResponse rsp = shardRsp.getSolrResponse();
    NamedList<Object> top = rsp.getResponse();
    if (top == null) continue; // shards.tolerant=true will cause this to happen on exceptions/errors
    Object facet = top.get("facets");
    if (facet == null) {
      @SuppressWarnings("rawtypes") SimpleOrderedMap shardResponseHeader = (SimpleOrderedMap) rsp.getResponse().get("responseHeader");
      if (Boolean.TRUE.equals(shardResponseHeader.getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY))) {
        rb.rsp.getResponseHeader().asShallowMap().put(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY, Boolean.TRUE);
      }
      continue;
    }
    if (facetState.merger == null) {
      facetState.merger = facetState.facetRequest.createFacetMerger(facet);
      facetState.mcontext = new FacetMerger.Context(sreq.responses.size());
    }

    if ((sreq.purpose & PURPOSE_REFINE_JSON_FACETS) != 0) {
      // System.err.println("REFINE FACET RESULT FROM SHARD = " + facet);
      // call merge again with a diff flag set on the context???
      facetState.mcontext.root = facet;
      facetState.mcontext.setShard(shardRsp.getShard());  // TODO: roll newShard into setShard?
      facetState.merger.merge(facet, facetState.mcontext);
      return;
    }

    // System.err.println("MERGING FACET RESULT FROM SHARD = " + facet);
    facetState.mcontext.root = facet;
    facetState.mcontext.newShard(shardRsp.getShard());
    facetState.merger.merge(facet, facetState.mcontext);
  }
}
 
Example #28
Source File: DistributedSuggestComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void validateControlData(QueryResponse control) throws Exception
{    
  NamedList<Object> nl = control.getResponse();
  @SuppressWarnings("unchecked")
  Map<String, SimpleOrderedMap<NamedList<Object>>> sc = (Map<String, SimpleOrderedMap<NamedList<Object>>>) nl.get("suggest");
  String command = (String) nl.get("command");
  if(sc.size() == 0 && command == null) {
    Assert.fail("Control data did not return any suggestions or execute any command");
  }
}
 
Example #29
Source File: FacetFieldProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void setValues(SimpleOrderedMap<Object> bucket, int slotNum) throws IOException {
  if (collectAcc != null) {
    collectAcc.setValues(bucket, collectAccSlot);
  }
  if (otherAccs != null) {
    for (SlotAcc otherAcc : otherAccs) {
      otherAcc.setValues(bucket, otherAccsSlot);
    }
  }
}
 
Example #30
Source File: RewriteFacetCountsComponent.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void processPivot(ResponseBuilder rb, String[] fromParts, String[] toParts, Collection<NamedList<Object>> current, int level)
{
    for(NamedList<Object> entry : current)
    {
        for(int i = 0; i < entry.size(); i++)
        {
            String name = entry.getName(i);
            if(name.equals("field"))
            {
                entry.setVal(i, fromParts[level].trim());
            }
            else if(name.equals("pivot"))
            {
                Collection<NamedList<Object>> pivot = (Collection<NamedList<Object>>)entry.getVal(i);
                processPivot(rb, fromParts, toParts, pivot, level+1);
            }
            else if(name.equals("ranges"))
            {
            	SimpleOrderedMap ranges = (SimpleOrderedMap)entry.getVal(i);
            	processRanges(rb, ranges);
            }
            else
            {
                // leave alone
            }
        }
    }
}