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

The following examples show how to use org.apache.solr.common.util.NamedList. 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: 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 #2
Source File: AlfrescoSolrUtils.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Asserts that the input {@link ShardState} and the CoreAdmin.SUMMARY response give the same information.
 *
 * @param state the {@link ShardState} instance.
 * @param core the target {@link SolrCore} instance.
 */
public static void assertShardAndCoreSummaryConsistency(ShardState state, SolrCore core) {
    SolrParams params =
            new ModifiableSolrParams()
                    .add(CoreAdminParams.CORE, core.getName())
                    .add(CoreAdminParams.ACTION, "SUMMARY");

    SolrQueryRequest request = new LocalSolrQueryRequest(core, params);
    SolrQueryResponse response = new SolrQueryResponse();
    coreAdminHandler(core).handleRequest(request, response);

    NamedList<?> summary =
            ofNullable(response.getValues())
                    .map(values -> values.get("Summary"))
                    .map(NamedList.class::cast)
                    .map(values -> values.get(core.getName()))
                    .map(NamedList.class::cast)
                    .orElseGet(NamedList::new);

    assertEquals(state.getLastIndexedChangeSetId(), summary.get("Id for last Change Set in index"));
    assertEquals(state.getLastIndexedChangeSetCommitTime(), summary.get("Last Index Change Set Commit Time"));
    assertEquals(state.getLastIndexedTxCommitTime(), summary.get("Last Index TX Commit Time"));
    assertEquals(state.getLastIndexedTxId(), summary.get("Id for last TX in index"));
}
 
Example #3
Source File: IndexFetcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes"})
NamedList getDetails() throws IOException, SolrServerException {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set(COMMAND, CMD_DETAILS);
  params.set("slave", false);
  params.set(CommonParams.QT, ReplicationHandler.PATH);

  // TODO use shardhandler
  try (HttpSolrClient client = new HttpSolrClient.Builder(masterUrl)
      .withHttpClient(myHttpClient)
      .withConnectionTimeout(connTimeout)
      .withSocketTimeout(soTimeout)
      .build()) {
    QueryRequest request = new QueryRequest(params);
    return client.request(request);
  }
}
 
Example #4
Source File: TestFieldAppender.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void addNamedList() {
  FieldAppender fa = new FieldAppender(true);
  NamedList root = new NamedList();
  NamedList added = fa.addNamedList(root, "list", new Object() {
    @SuppressWarnings("unused")
    public String getFoo() {
      return "foo";
    }
    
    @SuppressWarnings("unused")
    public int getBar() {
      return 123;
    }
    
    @SuppressWarnings("unused")
    public boolean isBaz() {
      return true;
    }
  });
  assertEquals(added, root.get("list"));
  assertEquals("foo", added.get("foo"));
  assertEquals(123, added.get("bar"));
  assertTrue((boolean)added.get("baz"));
}
 
Example #5
Source File: DocumentAnalysisRequestHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
  super.init(args);

  inputFactory = XMLInputFactory.newInstance();
  EmptyEntityResolver.configureXMLInputFactory(inputFactory);
  inputFactory.setXMLReporter(xmllog);
  try {
    // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe
    // XMLInputFactory, as that implementation tries to cache and reuse the
    // XMLStreamReader.  Setting the parser-specific "reuse-instance" property to false
    // prevents this.
    // All other known open-source stax parsers (and the bea ref impl)
    // have thread-safe factories.
    inputFactory.setProperty("reuse-instance", Boolean.FALSE);
  } catch (IllegalArgumentException ex) {
    // Other implementations will likely throw this exception since "reuse-instance"
    // is implementation specific.
    log.debug("Unable to set the 'reuse-instance' property for the input factory: {}", inputFactory);
  }
}
 
Example #6
Source File: TestZKPropertiesWriter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Code copied with some adaptations from {@link org.apache.solr.util.TestHarness.LocalRequestFactory#makeRequest(String...)}.
 */
@SuppressWarnings({"unchecked"})
private static LocalSolrQueryRequest localMakeRequest(SolrCore core, String ... q) {
  if (q.length==1) {
    Map<String, String> args = new HashMap<>();
    args.put(CommonParams.VERSION,"2.2");

    return new LocalSolrQueryRequest(core, q[0], "", 0, 20, args);
  }
  if (q.length%2 != 0) {
    throw new RuntimeException("The length of the string array (query arguments) needs to be even");
  }
  @SuppressWarnings({"rawtypes"})
  Map.Entry<String, String> [] entries = new NamedList.NamedListEntry[q.length / 2];
  for (int i = 0; i < q.length; i += 2) {
    entries[i/2] = new NamedList.NamedListEntry<>(q[i], q[i+1]);
  }
  @SuppressWarnings({"rawtypes"})
  NamedList nl = new NamedList(entries);
  if(nl.get("wt" ) == null) nl.add("wt","xml");
  return new LocalSolrQueryRequest(core, nl);
}
 
Example #7
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 #8
Source File: TestRequestStatusCollectionAPI.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to send a status request with specific retry limit and return
 * the message/null from the success response.
 */
private NamedList<Object> sendStatusRequestWithRetry(ModifiableSolrParams params, int maxCounter)
    throws SolrServerException, IOException{
  NamedList<Object> r = null;
  while (maxCounter-- > 0) {
    r = sendRequest(params);
    @SuppressWarnings("unchecked")
    final NamedList<Object> status = (NamedList<Object>) r.get("status");
    final RequestStatusState state = RequestStatusState.fromKey((String) status.get("state"));

    if (state == RequestStatusState.COMPLETED || state == RequestStatusState.FAILED) {
      return r;
    }

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

  }
  // Return last state?
  return r;
}
 
Example #9
Source File: AbstractFullDistribZkTestBase.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected long getIndexVersion(Replica replica) throws IOException {
  try (HttpSolrClient client = new HttpSolrClient.Builder(replica.getCoreUrl()).build()) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set("qt", "/replication");
    params.set(ReplicationHandler.COMMAND, ReplicationHandler.CMD_SHOW_COMMITS);
    try {
      QueryResponse response = client.query(params);
      @SuppressWarnings("unchecked")
      List<NamedList<Object>> commits = (List<NamedList<Object>>)response.getResponse().get(ReplicationHandler.CMD_SHOW_COMMITS);
      Collections.max(commits, (a,b)->((Long)a.get("indexVersion")).compareTo((Long)b.get("indexVersion")));
      return (long) Collections.max(commits, (a,b)->((Long)a.get("indexVersion")).compareTo((Long)b.get("indexVersion"))).get("indexVersion");
    } catch (SolrServerException e) {
      log.warn("Exception getting version from {}, will return an invalid version to retry.", replica.getName(), e);
      return -1;
    }
  }
}
 
Example #10
Source File: TestCollectionAPI.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void clusterStatusNoCollection() throws Exception {

    try (CloudSolrClient client = createCloudClient(null)) {
      ModifiableSolrParams params = new ModifiableSolrParams();
      params.set("action", CollectionParams.CollectionAction.CLUSTERSTATUS.toString());
      @SuppressWarnings({"rawtypes"})
      SolrRequest request = new QueryRequest(params);
      request.setPath("/admin/collections");

      NamedList<Object> rsp = client.request(request);
      @SuppressWarnings({"unchecked"})
      NamedList<Object> cluster = (NamedList<Object>) rsp.get("cluster");
      assertNotNull("Cluster state should not be null", cluster);
      @SuppressWarnings({"unchecked"})
      NamedList<Object> collections = (NamedList<Object>) cluster.get("collections");
      assertNotNull("Collections should not be null in cluster state", collections);
      assertNotNull(collections.get(COLLECTION_NAME1));
      assertEquals(4, collections.size());

      @SuppressWarnings({"unchecked"})
      List<String> liveNodes = (List<String>) cluster.get("live_nodes");
      assertNotNull("Live nodes should not be null", liveNodes);
      assertFalse(liveNodes.isEmpty());
    }

  }
 
Example #11
Source File: TestSimpleXJoinResultsFactory.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test(expected=PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() 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, "$.no.ids.at.this.path");
  
  SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
  factory.init(args);
  
  SolrParams params = new ModifiableSolrParams();
  XJoinResults<String> results = factory.getResults(params);
  
  assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}
 
Example #12
Source File: RangeFacetRequest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Removes all counts under the given minCount from the accumulated facet_ranges.
 * <p>
 * Note: this method should only be called after all shard responses have been
 * accumulated using {@link #mergeContributionFromShard(SimpleOrderedMap)}
 *
 * @param minCount the minimum allowed count for any range
 */
public void removeRangeFacetsUnderLimits(int minCount) {
  boolean replace = false;

  @SuppressWarnings("unchecked")
  NamedList<Number> vals = (NamedList<Number>) rangeFacet.get("counts");
  NamedList<Number> newList = new NamedList<>();
  for (Map.Entry<String, Number> pair : vals) {
    if (pair.getValue().longValue() >= minCount) {
      newList.add(pair.getKey(), pair.getValue());
    } else {
      replace = true;
    }
  }
  if (replace) {
    vals.clear();
    vals.addAll(newList);
  }
}
 
Example #13
Source File: DistributedDebugComponentTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testTolerantSearch() throws SolrServerException, IOException {
  String badShard = DEAD_HOST_1;
  SolrQuery query = new SolrQuery();
  query.setQuery("*:*");
  query.set("debug",  "true");
  query.set("distrib", "true");
  query.setFields("id", "text");
  query.set("shards", shard1 + "," + shard2 + "," + badShard);

  // verify that the request would fail if shards.tolerant=false
  ignoreException("Server refused connection");
  expectThrows(SolrException.class, () -> collection1.query(query));

  query.set(ShardParams.SHARDS_TOLERANT, "true");
  QueryResponse response = collection1.query(query);
  assertTrue((Boolean)response.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
  @SuppressWarnings("unchecked")
  NamedList<String> badShardTrack =
          (((NamedList<NamedList<NamedList<String>>>)response.getDebugMap().get("track")).get("EXECUTE_QUERY")).get(badShard);
  assertEquals("Unexpected response size for shard", 1, badShardTrack.size());
  Entry<String, String> exception = badShardTrack.iterator().next();
  assertEquals("Expected key 'Exception' not found", "Exception", exception.getKey());
  assertNotNull("Exception message should not be null", exception.getValue());
  unIgnoreException("Server refused connection");
}
 
Example #14
Source File: PhrasesIdentificationComponent.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Format the phrases suitable for returning in a shard response
 * @see #populateStats(List,List)
 */
public static List<NamedList<Object>> formatShardResponse(final List<Phrase> phrases) {
  List<NamedList<Object>> results = new ArrayList<>(phrases.size());
  for (Phrase p : phrases) {
    NamedList<Object> data = new SimpleOrderedMap<>();
    // quick and dirty way to validate that our shards aren't using different analyzers
    // so the coordinating node can fail fast when mergingthe results
    data.add("checksum", p.getChecksum());
    if (p.is_indexed) {
      data.add("ttf", new NamedList<Object>(p.phrase_ttf));
      data.add("df", new NamedList<Object>(p.phrase_df));
    }
    data.add("conj_dc", new NamedList<Object>(p.subTerms_conjunctionCounts));

    results.add(data);
  }
  return results;
}
 
Example #15
Source File: CdcrRequestHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Long call() throws Exception {
  try (HttpSolrClient server = new HttpSolrClient.Builder(baseUrl)
      .withConnectionTimeout(15000)
      .withSocketTimeout(60000)
      .build()) {

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(CommonParams.ACTION, CdcrParams.CdcrAction.SHARDCHECKPOINT.toString());

    @SuppressWarnings({"rawtypes"})
    SolrRequest request = new QueryRequest(params);
    request.setPath(cdcrPath);

    @SuppressWarnings({"rawtypes"})
    NamedList response = server.request(request);
    return (Long) response.get(CdcrParams.CHECKPOINT);
  }
}
 
Example #16
Source File: TestFieldAppender.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void addNamedList() {
  FieldAppender fa = new FieldAppender(true);
  NamedList root = new NamedList();
  NamedList added = fa.addNamedList(root, "list", new Object() {
    @SuppressWarnings("unused")
    public String getFoo() {
      return "foo";
    }
    
    @SuppressWarnings("unused")
    public int getBar() {
      return 123;
    }
    
    @SuppressWarnings("unused")
    public boolean isBaz() {
      return true;
    }
  });
  assertEquals(added, root.get("list"));
  assertEquals("foo", added.get("foo"));
  assertEquals(123, added.get("bar"));
  assertTrue((boolean)added.get("baz"));
}
 
Example #17
Source File: DymReSearcher.java    From solr-researcher with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private boolean checkCustomSpellcheckingSuggestionPossible(ResponseBuilder rb, NamedList suggestions,
    int spellcheckCount, long originalQueryHits) {
  if (suggestions == null || suggestions.size() == 0) {
    // if there are no spellchecking suggestions, we can't create spellchecking suggestions
    return false;
  }

  if (originalQueryHits > getMaxOriginalResults()) {
    return false;
  }

  return true;
}
 
Example #18
Source File: PeerSyncWithLeader.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private NamedList<Object> request(ModifiableSolrParams params, String onFail) {
  try {
    QueryResponse rsp = new QueryRequest(params, SolrRequest.METHOD.POST).process(clientToLeader);
    Exception exception = rsp.getException();
    if (exception != null) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, onFail);
    }
    return rsp.getResponse();
  } catch (SolrServerException | IOException e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, onFail);
  }
}
 
Example #19
Source File: BackupStatusChecker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Does a single check of the replication handler's status to determine if the specified name matches 
 * the most recently deleted backup, and if deleting that backup was a success.
 * Throws a test assertion failure if the status is about this backupName but the starts message 
 * with <code>"Unable to delete"</code>
 *
 * @returns true if the replication status info indicates the backup was deleted, false otherwise
 * @see #waitForBackupDeletionSuccess(String,TimeOut)
 */
public boolean checkBackupDeletionSuccess(final String backupName) throws Exception {
  assertNotNull("backumpName must not be null", backupName);
  final SimpleSolrResponse rsp = new GenericSolrRequest(GenericSolrRequest.METHOD.GET, path,
                                                        params("command", "details")).process(client);
  @SuppressWarnings({"rawtypes"})
  final NamedList data = rsp.getResponse();
  log.info("Checking Deletion Status of {}: {}", backupName, data);
  @SuppressWarnings({"unchecked"})
  final NamedList<String> backupData = (NamedList<String>) data.findRecursive("details","backup");
  if (null == backupData
      || null == backupData.get("status")
      || ! backupName.equals(backupData.get("snapshotName")) ) {
    // either no backup activity at all,
    // or most recent activity isn't something we can infer anything from,
    // or is not about the backup we care about...
    return false;
  }
  
  final Object status = backupData.get("status");
  if (status.toString().startsWith("Unable to delete")) {
    // we already know backupData is about our backup
    assertNull("Backup Deleting failure: " + backupName, status);
  }

  if ("success".equals(status) && null != backupData.get("snapshotDeletedAt")) {
    return true; // backup done
  }
  
  // if we're still here then this status is about our backup, but doesn't seem to be a deletion
  return false;
}
 
Example #20
Source File: SolrInformationServer.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void setDuplicates(IndexHealthReport report, SolrQueryRequest request, String docType,
                           SetDuplicatesCommand cmd)
{
    // A mincount of 2 checks for duplicates in solr
    NamedList<Integer> dbIdCounts = getFacets(request, FIELD_DOC_TYPE + ":" + docType, FIELD_DBID, 2);
    for (Map.Entry<String, Integer> dbId : dbIdCounts)
    {
        long duplicatedDbId = Long.parseLong(dbId.getKey());
        cmd.execute(report, duplicatedDbId);
    }
}
 
Example #21
Source File: OverseerConfigSetMessageHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void deleteConfigSet(String configSetName, boolean force) throws IOException {
  ZkConfigManager configManager = new ZkConfigManager(zkStateReader.getZkClient());
  if (!configManager.configExists(configSetName)) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "ConfigSet does not exist to delete: " + configSetName);
  }

  for (Map.Entry<String, DocCollection> entry : zkStateReader.getClusterState().getCollectionsMap().entrySet()) {
    String configName = null;
    try {
      configName = zkStateReader.readConfigName(entry.getKey());
    } catch (KeeperException ex) {
      throw new SolrException(ErrorCode.BAD_REQUEST,
          "Can not delete ConfigSet as it is currently being used by collection [" + entry.getKey() + "]");
    }
    if (configSetName.equals(configName))
      throw new SolrException(ErrorCode.BAD_REQUEST,
          "Can not delete ConfigSet as it is currently being used by collection [" + entry.getKey() + "]");
  }

  String propertyPath = ConfigSetProperties.DEFAULT_FILENAME;
  @SuppressWarnings({"rawtypes"})
  NamedList properties = getConfigSetProperties(getPropertyPath(configSetName, propertyPath));
  if (properties != null) {
    Object immutable = properties.get(ConfigSetProperties.IMMUTABLE_CONFIGSET_ARG);
    boolean isImmutableConfigSet = immutable != null ? Boolean.parseBoolean(immutable.toString()) : false;
    if (!force && isImmutableConfigSet) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Requested delete of immutable ConfigSet: " + configSetName);
    }
  }
  configManager.deleteConfigDir(configSetName);
}
 
Example #22
Source File: TestXJoinValueSourceParser.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
private FunctionValues functionValues(NamedList initArgs, String arg) throws Exception {
  FunctionQParser fqp = mockFunctionQParser(arg);
  XJoinValueSourceParser vsp = new XJoinValueSourceParser();
  vsp.init(initArgs);
  ValueSource vs = vsp.parse(fqp);
  return vs.getValues(null, searcher.getLeafReader().getContext());
}
 
Example #23
Source File: TermVectorComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void finishStage(ResponseBuilder rb) {
  if (rb.stage == ResponseBuilder.STAGE_GET_FIELDS) {
    
    NamedList<Object> termVectorsNL = new NamedList<>();

    @SuppressWarnings({"unchecked", "rawtypes"})
    Map.Entry<String, Object>[] arr = new NamedList.NamedListEntry[rb.resultIds.size()];

    for (ShardRequest sreq : rb.finished) {
      if ((sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS) == 0 || !sreq.params.getBool(COMPONENT_NAME, false)) {
        continue;
      }
      for (ShardResponse srsp : sreq.responses) {
        @SuppressWarnings({"unchecked"})
        NamedList<Object> nl = (NamedList<Object>)srsp.getSolrResponse().getResponse().get(TERM_VECTORS);

        // Add metadata (that which isn't a uniqueKey value):
        Object warningsNL = nl.get(TV_KEY_WARNINGS);
        // assume if that if warnings is already present; we don't need to merge.
        if (warningsNL != null && termVectorsNL.indexOf(TV_KEY_WARNINGS, 0) < 0) {
          termVectorsNL.add(TV_KEY_WARNINGS, warningsNL);
        }

        // UniqueKey data
        SolrPluginUtils.copyNamedListIntoArrayByDocPosInResponse(nl, rb.resultIds, arr);
      }
    }
    // remove nulls in case not all docs were able to be retrieved
    SolrPluginUtils.removeNulls(arr, termVectorsNL);
    rb.rsp.add(TERM_VECTORS, termVectorsNL);
  }
}
 
Example #24
Source File: HttpShardHandlerFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void initReplicaListTransformers(@SuppressWarnings({"rawtypes"})NamedList routingConfig) {
  String defaultRouting = null;
  ReplicaListTransformerFactory stableRltFactory = null;
  ReplicaListTransformerFactory defaultRltFactory;
  if (routingConfig != null && routingConfig.size() > 0) {
    Iterator<Entry<String,?>> iter = routingConfig.iterator();
    do {
      Entry<String, ?> e = iter.next();
      String key = e.getKey();
      switch (key) {
        case ShardParams.REPLICA_RANDOM:
          // Only positive assertion of default status (i.e., default=true) is supported.
          // "random" is currently the implicit default, so explicitly configuring
          // "random" as default would not currently be useful, but if the implicit default
          // changes in the future, checkDefault could be relevant here.
          defaultRouting = checkDefaultReplicaListTransformer(getNamedList(e.getValue()), key, defaultRouting);
          break;
        case ShardParams.REPLICA_STABLE:
          NamedList<?> c = getNamedList(e.getValue());
          defaultRouting = checkDefaultReplicaListTransformer(c, key, defaultRouting);
          stableRltFactory = new AffinityReplicaListTransformerFactory(c);
          break;
        default:
          throw new IllegalArgumentException("invalid replica routing spec name: " + key);
      }
    } while (iter.hasNext());
  }
  if (stableRltFactory == null) {
    stableRltFactory = new AffinityReplicaListTransformerFactory();
  }
  if (ShardParams.REPLICA_STABLE.equals(defaultRouting)) {
    defaultRltFactory = stableRltFactory;
  } else {
    defaultRltFactory = RequestReplicaListTransformerGenerator.RANDOM_RLTF;
  }
  this.requestReplicaListTransformerGenerator = new RequestReplicaListTransformerGenerator(defaultRltFactory, stableRltFactory);
}
 
Example #25
Source File: TestSimpleXJoinResultsFactory.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoResultPaths() 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");
  
  testResultsFile(args, true, false);
}
 
Example #26
Source File: CustomHighlightComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
protected Object convertHighlights(@SuppressWarnings({"rawtypes"})NamedList hl) {
  @SuppressWarnings({"rawtypes"})
  final ArrayList<SimpleOrderedMap> hlMaps = new ArrayList<>();
  for (int i=0; i<hl.size(); ++i) {
      @SuppressWarnings({"rawtypes"})
      SimpleOrderedMap hlMap = new SimpleOrderedMap<Object>();
      hlMap.add(id_key, hl.getName(i));
      hlMap.add(snippets_key, hl.getVal(i));
      hlMaps.add(hlMap);
  }
  return hlMaps;
}
 
Example #27
Source File: TimeSeriesStream.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void getTuples(@SuppressWarnings({"rawtypes"})NamedList response,
                       String field,
                       Metric[] metrics) {

  Tuple tuple = new Tuple();
  @SuppressWarnings({"rawtypes"})
  NamedList facets = (NamedList)response.get("facets");
  fillTuples(tuples, tuple, facets, field, metrics);
}
 
Example #28
Source File: SolrTarget04.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void getRequiredFieldNames() throws SolrServerException, IOException {
  QueryRequest request = new QueryRequest();
  request.setPath(SCHEMA_PATH);
  NamedList queryResponse = solrClient.request(request);

  SimpleOrderedMap simpleOrderedMap = (SimpleOrderedMap) queryResponse.get("schema");
  ArrayList<SimpleOrderedMap> fields = (ArrayList<SimpleOrderedMap>) simpleOrderedMap.get("fields");

  for (SimpleOrderedMap field : fields) {
    if (field.get(REQUIRED) != null && field.get(REQUIRED).equals(true)) {
      requiredFieldNamesMap.add(field.get(NAME).toString());
    }
  }
}
 
Example #29
Source File: ManagedSynonymFilterFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Called once, during core initialization, to initialize any analysis components
 * that depend on the data managed by this resource. It is important that the
 * analysis component is only initialized once during core initialization so that
 * text analysis is consistent, especially in a distributed environment, as we
 * don't want one server applying a different set of stop words than other servers.
 */
@SuppressWarnings("unchecked")
@Override
public void onManagedResourceInitialized(NamedList<?> initArgs, final ManagedResource res) 
    throws SolrException
{    
  NamedList<Object> args = (NamedList<Object>)initArgs;    
  args.add("synonyms", getResourceId());
  args.add("expand", "false");
  args.add("format", "solr");
  
  Map<String,String> filtArgs = new HashMap<>();
  for (Map.Entry<String,?> entry : args) {
    filtArgs.put(entry.getKey(), entry.getValue().toString());
  }
  // create the actual filter factory that pulls the synonym mappings
  // from synonymMappings using a custom parser implementation
  delegate = new SynonymFilterFactory(filtArgs) {
    @Override
    protected SynonymMap loadSynonyms
        (ResourceLoader loader, String cname, boolean dedup, Analyzer analyzer)
        throws IOException, ParseException {

      ManagedSynonymParser parser =
          new ManagedSynonymParser((SynonymManager)res, dedup, analyzer);
      // null is safe here because there's no actual parsing done against a input Reader
      parser.parse(null);
      return parser.build(); 
    }
  };
  try {
    delegate.inform(res.getResourceLoader());
  } catch (IOException e) {
    throw new SolrException(ErrorCode.SERVER_ERROR, e);
  }    
}
 
Example #30
Source File: DistributedDebugComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private void assertSameKeys(NamedList object, NamedList object2) {
  Iterator<Map.Entry<String,Object>> iteratorObj2 = (object2).iterator();
  for (Map.Entry<String,Object> entry:(NamedList<Object>)object) {
    assertTrue(iteratorObj2.hasNext());
    Map.Entry<String,Object> entry2 = iteratorObj2.next();
    assertEquals(entry.getKey(), entry2.getKey());
    if (entry.getValue() instanceof NamedList) {
      assertTrue(entry2.getValue() instanceof NamedList);
      assertSameKeys((NamedList)entry.getValue(), (NamedList)entry2.getValue());
    }
  }
  assertFalse(iteratorObj2.hasNext());
}