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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: V2ApiIntegrationTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private long getStatus(V2Response response) {
  Object header = response.getResponse().get("responseHeader");
  if (header instanceof NamedList) {
    return (int) ((NamedList) header).get("status");
  } else {
    return (long) ((Map) header).get("status");
  }
}
 
Example #18
Source File: QueryResponse.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void extractHighlightingInfo( NamedList<Object> info )
{
  _highlighting = new HashMap<>();
  for( Map.Entry<String, Object> doc : info ) {
    Map<String,List<String>> fieldMap = new HashMap<>();
    _highlighting.put( doc.getKey(), fieldMap );
    
    NamedList<List<String>> fnl = (NamedList<List<String>>)doc.getValue();
    for( Map.Entry<String, List<String>> field : fnl ) {
      fieldMap.put( field.getKey(), field.getValue() );
    }
  }
}
 
Example #19
Source File: SpellcheckComponent.java    From customized-symspell with MIT License 5 votes vote down vote up
private NamedList toNamedList(List<SuggestionItem> suggestionItems) {
  NamedList result = new NamedList();
  if (CollectionUtils.isEmpty(suggestionItems)) {
    return result;
  }
  Map<String, String> suggestions = suggestionItems.parallelStream().collect(
      Collectors.toMap(SuggestionItem::getTerm,
          s -> s.getCount() + "," + s.getDistance() + "," + s.getScore()));

  result.add("spellcheck", suggestions);
  result.add("correctlySpelled", suggestionItems.get(0).getDistance() == 0);
  return result;
}
 
Example #20
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 #21
Source File: SimpleTextCodecFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"rawtypes"})
public void init(NamedList args) {
  super.init(args);
  assert codec == null;
  codec = new SimpleTextCodec();
}
 
Example #22
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 #23
Source File: PluginInfo.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public PluginInfo(String type, Map<String, String> attrs, @SuppressWarnings({"rawtypes"})NamedList initArgs, List<PluginInfo> children) {
  this.type = type;
  this.name = attrs.get(NAME);
  Pair<String, String> parsed = parseClassName(attrs.get(CLASS_NAME));
  this.className = parsed.second();
  this.pkgName = parsed.first();
  this.initArgs = initArgs;
  attributes = unmodifiableMap(attrs);
  this.children = children == null ? Collections.<PluginInfo>emptyList(): unmodifiableList(children);
  isFromSolrConfig = false;
}
 
Example #24
Source File: DirectSolrSpellCheckerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  initCore("solrconfig-spellcheckcomponent.xml","schema.xml");
  //Index something with a title
  assertNull(h.validateUpdate(adoc("id", "0", "teststop", "This is a title")));
  assertNull(h.validateUpdate(adoc("id", "1", "teststop", "The quick reb fox jumped over the lazy brown dogs.")));
  assertNull(h.validateUpdate(adoc("id", "2", "teststop", "This is a Solr")));
  assertNull(h.validateUpdate(adoc("id", "3", "teststop", "solr foo")));
  assertNull(h.validateUpdate(adoc("id", "4", "teststop", "another foo")));
  assertNull(h.validateUpdate(commit()));
  queryConverter = new SimpleQueryConverter();
  queryConverter.init(new NamedList());
}
 
Example #25
Source File: SkipExistingDocumentsProcessorFactoryTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test(expected=SolrException.class)
public void testExceptionIfNextProcessorNotDistributed() {
  SkipExistingDocumentsProcessorFactory factory = new SkipExistingDocumentsProcessorFactory();
  NamedList<Object> initArgs = new NamedList<>();
  factory.init(initArgs);
  UpdateRequestProcessor next = new BufferingRequestProcessor(null);

  factory.getInstance(defaultRequest, new SolrQueryResponse(), next);
}
 
Example #26
Source File: SchemaResponse.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> getFields(
        @SuppressWarnings({"rawtypes"})Map schemaNamedList) {
  List<Map<String, Object>> fieldsAttributes = new LinkedList<>();
  List<NamedList<Object>> fieldsResponse = (List<NamedList<Object>>) schemaNamedList.get("fields");
  for (NamedList<Object> fieldNamedList : fieldsResponse) {
    Map<String, Object> fieldAttributes = new LinkedHashMap<>(extractAttributeMap(fieldNamedList));
    fieldsAttributes.add(fieldAttributes);
  }

  return fieldsAttributes;
}
 
Example #27
Source File: SchemaResponse.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void setResponse(NamedList<Object> response) {
  super.setResponse(response);

  fieldTypes = SchemaResponse.getFieldTypeRepresentations(response.asShallowMap());
}
 
Example #28
Source File: AlfrescoCoreAdminHandler.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get a report from a txId with detailed information related with the Transaction
 *
 * Synchronous execution
 *
 * @param params Query Request with following parameters:
 * - txId, mandatory, the number of the Transaction to build the report
 * - core, The name of the SOLR Core or "null" to get the report for every core
 * @return Response including the action result:
 * - report: an Object with the details of the report
 * - error: When mandatory parameters are not set, an error node is returned
 *
 * @throws JSONException
 */
private NamedList<Object> actionTXREPORT(SolrParams params) throws JSONException
{
    NamedList<Object> report = new SimpleOrderedMap<>();

    if (params.get(ARG_TXID) == null)
    {
        report.add(ACTION_STATUS_ERROR, "No " + ARG_TXID + " parameter set.");
        return report;
    }

    Long txid = Long.valueOf(params.get(ARG_TXID));
    String requestedCoreName = coreName(params);

    coreNames().stream()
            .filter(coreName -> requestedCoreName == null || coreName.equals(requestedCoreName))
            .map(coreName -> new Pair<>(coreName, trackerRegistry.getTrackerForCore(coreName, MetadataTracker.class)))
            .filter(coreNameAndMetadataTracker -> coreNameAndMetadataTracker.getSecond() != null)
            .forEach(coreNameAndMetadataTracker ->
                    report.add(
                            coreNameAndMetadataTracker.getFirst(),
                            buildTxReport(
                                    trackerRegistry,
                                    informationServers.get(coreNameAndMetadataTracker.getFirst()),
                                    coreNameAndMetadataTracker.getFirst(),
                                    coreNameAndMetadataTracker.getSecond(),
                                    txid)));

    if (report.size() == 0)
    {
        addAlertMessage(report);
    }
    return report;

}
 
Example #29
Source File: WiseOwlQParserPlugin.java    From wiseowl with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void init(NamedList initArgs) {
	
    SolrParams params = SolrParams.toSolrParams(initArgs);
    String modelDirectory = params.get("modelDirectory",
            System.getProperty("model.dir"));//<co id="qqpp.model"/>
    String wordnetDirectory = params.get("wordnetDirectory",
            System.getProperty("wordnet.dir"));//<co id="qqpp.wordnet"/>
    if (modelDirectory != null) {
      File modelsDir = new File(modelDirectory);
      try {
        InputStream chunkerStream = new FileInputStream(
            new File(modelsDir,"en-chunker.bin"));
        ChunkerModel chunkerModel = new ChunkerModel(chunkerStream);
        chunker = new ChunkerME(chunkerModel); //<co id="qqpp.chunker"/>
        InputStream posStream = new FileInputStream(
            new File(modelsDir,"en-pos-maxent.bin"));
        POSModel posModel = new POSModel(posStream);
        tagger =  new POSTaggerME(posModel); //<co id="qqpp.tagger"/>
       // model = new DoccatModel(new FileInputStream( //<co id="qqpp.theModel"/>
     //       new File(modelDirectory,"en-answer.bin"))).getMaxentModel();
        model = new SuffixSensitiveGISModelReader(new File(modelDirectory+"/qa/ans.bin")).getModel();
        //GISModel m = new SuffixSensitiveGISModelReader(new File(modelFileName)).getModel(); 
        probs = new double[model.getNumOutcomes()];
        atcg = new AnswerTypeContextGenerator(
                new File(wordnetDirectory, "dict"));//<co id="qqpp.context"/>
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
 
Example #30
Source File: ExpandComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void addGroupSliceToOutputMap(FieldType fieldType, IntObjectHashMap<BytesRef> ordBytes,
                                      @SuppressWarnings({"rawtypes"})NamedList outMap, CharsRefBuilder charsRef, long groupValue, DocSlice slice) {
  if(fieldType instanceof StrField) {
    final BytesRef bytesRef = ordBytes.get((int)groupValue);
    fieldType.indexedToReadable(bytesRef, charsRef);
    String group = charsRef.toString();
    outMap.add(group, slice);
  } else {
    outMap.add(numericToString(fieldType, groupValue), slice);
  }
}