Java Code Examples for org.apache.solr.common.params.SolrParams#get()

The following examples show how to use org.apache.solr.common.params.SolrParams#get() . 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: StatusOp.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CoreAdminHandler.CallInfo it) throws Exception {
  SolrParams params = it.req.getParams();

  String cname = params.get(CoreAdminParams.CORE);
  String indexInfo = params.get(CoreAdminParams.INDEX_INFO);
  boolean isIndexInfoNeeded = Boolean.parseBoolean(null == indexInfo ? "true" : indexInfo);
  NamedList<Object> status = new SimpleOrderedMap<>();
  Map<String, Exception> failures = new HashMap<>();
  for (Map.Entry<String, CoreContainer.CoreLoadFailure> failure : it.handler.coreContainer.getCoreInitFailures().entrySet()) {
    failures.put(failure.getKey(), failure.getValue().exception);
  }
  if (cname == null) {
    for (String name : it.handler.coreContainer.getAllCoreNames()) {
      status.add(name, CoreAdminOperation.getCoreStatus(it.handler.coreContainer, name, isIndexInfoNeeded));
    }
    it.rsp.add("initFailures", failures);
  } else {
    failures = failures.containsKey(cname)
        ? Collections.singletonMap(cname, failures.get(cname))
            : Collections.<String, Exception>emptyMap();
        it.rsp.add("initFailures", failures);
        status.add(cname, CoreAdminOperation.getCoreStatus(it.handler.coreContainer, cname, isIndexInfoNeeded));
  }
  it.rsp.add("status", status);
}
 
Example 2
Source File: PrunerFactory.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
public Pruner constructPruner(SolrParams params) throws SyntaxError {
	Pruner pruner = null;
	
	String prunerParam = params.get(PRUNE_PARAM, componentParameters.getDefault(PRUNE_PARAM));
	
	if (StringUtils.isNotBlank(prunerParam)) {
		if (SIMPLE_PRUNER_VALUE.equals(prunerParam)) {
			pruner = new SimplePruner(params.getInt(SimplePruner.CHILD_COUNT_PARAM, SimplePruner.MIN_CHILD_COUNT));
		} else if (DATAPOINTS_PRUNER_VALUE.equals(prunerParam)) {
			int dp = params.getInt(DATAPOINTS_PARAM, componentParameters.getIntDefault(DATAPOINTS_PARAM));
			if (dp <= 0) {
				throw new SyntaxError("Datapoints parameter invalid");
			}
			pruner = new DatapointPruner(dp, 
					componentParameters.getDefault(FacetTreeParameters.DATAPOINTS_MORELABEL_PARAM,  DatapointPruner.DEFAULT_MORE_LABEL));
		}
	}
	
	return pruner;
}
 
Example 3
Source File: ReplicationHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * This method adds an Object of FileStream to the response . The FileStream implements a custom protocol which is
 * understood by IndexFetcher.FileFetcher
 *
 * @see IndexFetcher.LocalFsFileFetcher
 * @see IndexFetcher.DirectoryFileFetcher
 */
private void getFileStream(SolrParams solrParams, SolrQueryResponse rsp) {
  ModifiableSolrParams rawParams = new ModifiableSolrParams(solrParams);
  rawParams.set(CommonParams.WT, FILE_STREAM);

  String cfileName = solrParams.get(CONF_FILE_SHORT);
  String tlogFileName = solrParams.get(TLOG_FILE);
  if (cfileName != null) {
    rsp.add(FILE_STREAM, new LocalFsConfFileStream(solrParams));
  } else if (tlogFileName != null) {
    rsp.add(FILE_STREAM, new LocalFsTlogFileStream(solrParams));
  } else {
    rsp.add(FILE_STREAM, new DirectoryFileStream(solrParams));
  }
  rsp.add(STATUS, OK_STATUS);
}
 
Example 4
Source File: CollectionsHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  // Make sure the cores is enabled
  CoreContainer cores = getCoreContainer();
  if (cores == null) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Core container instance missing");
  }

  // Make sure that the core is ZKAware
  if (!cores.isZooKeeperAware()) {
    throw new SolrException(ErrorCode.BAD_REQUEST,
        "Solr instance is not running in SolrCloud mode.");
  }

  // Pick the action
  SolrParams params = req.getParams();
  String a = params.get(CoreAdminParams.ACTION);
  if (a != null) {
    CollectionAction action = CollectionAction.get(a);
    if (action == null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unknown action: " + a);
    }
    CollectionOperation operation = CollectionOperation.get(action);
    if (log.isInfoEnabled()) {
      log.info("Invoked Collection Action :{} with params {} and sendToOCPQueue={}"
          , action.toLower(), req.getParamString(), operation.sendToOCPQueue);
    }
    MDCLoggingContext.setCollection(req.getParams().get(COLLECTION));
    invokeAction(req, rsp, cores, action, operation);
  } else {
    throw new SolrException(ErrorCode.BAD_REQUEST, "action is a required param");
  }
  rsp.setHttpCaching(false);
}
 
Example 5
Source File: RequestReplicaListTransformerGenerator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public ReplicaListTransformer getReplicaListTransformer(final SolrParams requestParams, String defaultShardPreferences, String nodeName, String localHostAddress, NodesSysPropsCacher sysPropsCacher) {
  @SuppressWarnings("deprecation")
  final boolean preferLocalShards = requestParams.getBool(CommonParams.PREFER_LOCAL_SHARDS, false);
  defaultShardPreferences = Optional.ofNullable(defaultShardPreferences).orElse(this.defaultShardPreferences);
  final String shardsPreferenceSpec = requestParams.get(ShardParams.SHARDS_PREFERENCE, defaultShardPreferences);

  if (preferLocalShards || !shardsPreferenceSpec.isEmpty()) {
    if (preferLocalShards && !shardsPreferenceSpec.isEmpty()) {
      throw new SolrException(
          ErrorCode.BAD_REQUEST,
          "preferLocalShards is deprecated and must not be used with shards.preference"
      );
    }
    List<PreferenceRule> preferenceRules = PreferenceRule.from(shardsPreferenceSpec);
    if (preferLocalShards) {
      preferenceRules.add(new PreferenceRule(ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION, ShardParams.REPLICA_LOCAL));
    }

    NodePreferenceRulesComparator replicaComp =
        new NodePreferenceRulesComparator(
            preferenceRules,
            requestParams,
            Optional.ofNullable(nodeName).orElse(this.nodeName),
            Optional.ofNullable(localHostAddress).orElse(this.localHostAddress),
            Optional.ofNullable(sysPropsCacher).orElse(this.sysPropsCacher),
            defaultRltFactory,
            stableRltFactory);
    ReplicaListTransformer baseReplicaListTransformer = replicaComp.getBaseReplicaListTransformer();
    if (replicaComp.getSortRules() == null) {
      // only applying base transformation
      return baseReplicaListTransformer;
    } else {
      return new TopLevelReplicaListTransformer(replicaComp, baseReplicaListTransformer);
    }
  }

  return defaultRltFactory.getInstance(null, requestParams, RANDOM_RLTF);
}
 
Example 6
Source File: URLClassifyProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void initParameters(SolrParams parameters) {
  if (parameters != null) {
    this.setEnabled(parameters.getBool("enabled", true));
    this.urlFieldname = parameters.get(INPUT_FIELD_PARAM, DEFAULT_URL_FIELDNAME);
    this.lengthFieldname = parameters.get(OUTPUT_LENGTH_FIELD_PARAM, DEFAULT_LENGTH_FIELDNAME);
    this.levelsFieldname = parameters.get(OUTPUT_LEVELS_FIELD_PARAM, DEFAULT_LEVELS_FIELDNAME);
    this.toplevelpageFieldname = parameters.get(OUTPUT_TOPLEVEL_FIELD_PARAM, DEFAULT_TOPLEVEL_FIELDNAME);
    this.landingpageFieldname = parameters.get(OUTPUT_LANDINGPAGE_FIELD_PARAM, DEFAULT_LANDINGPAGE_FIELDNAME);
    this.domainFieldname = parameters.get(OUTPUT_DOMAIN_FIELD_PARAM);
    this.canonicalUrlFieldname = parameters.get(OUTPUT_CANONICALURL_FIELD_PARAM);
  }
}
 
Example 7
Source File: SetLocaleComponent.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void prepare(ResponseBuilder rb) throws IOException
{
    SolrQueryRequest req = rb.req;
    SolrParams params = req.getParams();
    String localeStr = params.get("locale");
    Locale locale = I18NUtil.parseLocale(localeStr);
    I18NUtil.setLocale(locale);
    log.info("Set locale to " + localeStr);
}
 
Example 8
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Long deleteAndGetVersion(String id, SolrParams params) throws Exception {
  if (params==null || params.get("versions") == null) {
    ModifiableSolrParams mparams = new ModifiableSolrParams(params);
    mparams.set("versions","true");
    params = mparams;
  }
  String response = updateJ(jsonDelId(id), params);
  @SuppressWarnings({"rawtypes"})
  Map rsp = (Map)ObjectBuilder.fromJSON(response);
  @SuppressWarnings({"rawtypes"})
  List lst = (List)rsp.get("deletes");
  if (lst == null || lst.size() == 0) return null;
  return (Long) lst.get(1);
}
 
Example 9
Source File: SpellcheckComponent.java    From customized-symspell with MIT License 5 votes vote down vote up
@Override
public void process(ResponseBuilder rb) throws IOException {
  if (!rb.req.getParams().getBool(Constants.SPELLCHECK_ENABLE, true) || SearchRequestUtil
      .resultGreaterThanThreshold(rb.rsp, threshold)) {
    log.debug("Spellcheck is disbaled either by query or result  greater than threshold [{}]",
        threshold);
    return;
  }
  SolrParams params = rb.req.getParams();
  String q = params.get(Constants.SPELLCHECK_Q, params.get(CommonParams.Q));
  boolean sow = params.getBool(Constants.SPELLCHECK_SOW, true);
  List<SuggestionItem> suggestions;
  try {
    if (sow) {
      suggestions = spellChecker.lookupCompound(q);
    } else {
      suggestions = spellChecker.lookupCompound(q, 2, false);
    }
    if (!CollectionUtils.isEmpty(suggestions)) {
      addToResponse(rb, suggestions);
    }
  } catch (SpellCheckException ex) {
    log.error("exception occured while looking for spelling suggestions");
    throw new IOException(ex);
  }

}
 
Example 10
Source File: AffinityReplicaListTransformer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param dividendParam int param to be used directly for mod-based routing
 * @param hashParam String param to be hashed into an int for mod-based routing
 * @param requestParams the parameters of the Solr request
 * @return null if specified routing vals are not able to be parsed properly
 */
public static ReplicaListTransformer getInstance(String dividendParam, String hashParam, SolrParams requestParams) {
  Integer dividendVal;
  if (dividendParam != null && (dividendVal = requestParams.getInt(dividendParam)) != null) {
    return new AffinityReplicaListTransformer(dividendVal);
  }
  String hashVal;
  if (hashParam != null && (hashVal = requestParams.get(hashParam)) != null && !hashVal.isEmpty()) {
    return new AffinityReplicaListTransformer(hashVal);
  } else {
    return null;
  }
}
 
Example 11
Source File: PhmmerXJoinResultsFactory.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Override
public XJoinResults<String> getResults(SolrParams params) throws IOException {
  String sequence = params.get(PHMMER_SEQUENCE);
  if (sequence == null || sequence.length() == 0) {
    throw new RuntimeException("Missing or empty sequence");
  }
  PhmmerJob job = new PhmmerJob(client, database, sequence);
  return new Results(job.runJob());
}
 
Example 12
Source File: ClassificationUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private int getIntParam(SolrParams params, String name, int defaultValue) {
  String paramString = params.get(name);
  int paramInt;
  if (paramString != null && !paramString.isEmpty()) {
    paramInt = Integer.parseInt(paramString);
  } else {
    paramInt = defaultValue;
  }
  return paramInt;
}
 
Example 13
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 14
Source File: ReplicationHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void restore(SolrParams params, SolrQueryResponse rsp, SolrQueryRequest req) throws IOException {
  if (restoreFuture != null && !restoreFuture.isDone()) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Restore in progress. Cannot run multiple restore operations" +
        "for the same core");
  }
  String name = params.get(NAME);
  String location = params.get(CoreAdminParams.BACKUP_LOCATION);
  String repoName = params.get(CoreAdminParams.BACKUP_REPOSITORY);
  CoreContainer cc = core.getCoreContainer();
  BackupRepository repo = null;
  if (repoName != null) {
    repo = cc.newBackupRepository(Optional.of(repoName));
    location = repo.getBackupLocation(location);
    if (location == null) {
      throw new IllegalArgumentException("location is required");
    }
  } else {
    repo = new LocalFileSystemRepository();
    //If location is not provided then assume that the restore index is present inside the data directory.
    if (location == null) {
      location = core.getDataDir();
    }
  }
  if ("file".equals(repo.createURI("x").getScheme())) {
    core.getCoreContainer().assertPathAllowed(Paths.get(location));
  }

  URI locationUri = repo.createURI(location);

  //If name is not provided then look for the last unnamed( the ones with the snapshot.timestamp format)
  //snapshot folder since we allow snapshots to be taken without providing a name. Pick the latest timestamp.
  if (name == null) {
    String[] filePaths = repo.listAll(locationUri);
    List<OldBackupDirectory> dirs = new ArrayList<>();
    for (String f : filePaths) {
      OldBackupDirectory obd = new OldBackupDirectory(locationUri, f);
      if (obd.getTimestamp().isPresent()) {
        dirs.add(obd);
      }
    }
    Collections.sort(dirs);
    if (dirs.size() == 0) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "No backup name specified and none found in " + core.getDataDir());
    }
    name = dirs.get(0).getDirName();
  } else {
    //"snapshot." is prefixed by snapshooter
    name = "snapshot." + name;
  }

  RestoreCore restoreCore = new RestoreCore(repo, core, locationUri, name);
  try {
    MDC.put("RestoreCore.core", core.getName());
    MDC.put("RestoreCore.backupLocation", location);
    MDC.put("RestoreCore.backupName", name);
    restoreFuture = restoreExecutor.submit(restoreCore);
    currentRestoreName = name;
    rsp.add(STATUS, OK_STATUS);
  } finally {
    MDC.remove("RestoreCore.core");
    MDC.remove("RestoreCore.backupLocation");
    MDC.remove("RestoreCore.backupName");
  }
}
 
Example 15
Source File: SolrResourceLocator.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public SolrResourceLocator(SolrCore core, SolrParams initParams) {
  resourceLoader = core.getResourceLoader();
  
  String resourcesDir = initParams.get(CarrotParams.RESOURCES_DIR);
  carrot2ResourcesDir = firstNonNull(resourcesDir, CarrotClusteringEngine.CARROT_RESOURCES_PREFIX);
}
 
Example 16
Source File: SolrCore.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Put status, QTime, and possibly request handler and params, in the response header
 */
public static void postDecorateResponse
(SolrRequestHandler handler, SolrQueryRequest req, SolrQueryResponse rsp) {
  // TODO should check that responseHeader has not been replaced by handler
  NamedList<Object> responseHeader = rsp.getResponseHeader();
  final int qtime = (int) (req.getRequestTimer().getTime());
  int status = 0;
  Exception exception = rsp.getException();
  if (exception != null) {
    if (exception instanceof SolrException)
      status = ((SolrException) exception).code();
    else
      status = 500;
  }
  responseHeader.add("status", status);
  responseHeader.add("QTime", qtime);

  if (rsp.getToLog().size() > 0) {
    rsp.getToLog().add("status", status);
    rsp.getToLog().add("QTime", qtime);
  }

  SolrParams params = req.getParams();
  if (null != handler && params.getBool(CommonParams.HEADER_ECHO_HANDLER, false)) {
    responseHeader.add("handler", handler.getName());
  }

  // Values for echoParams... false/true/all or false/explicit/all ???
  String ep = params.get(CommonParams.HEADER_ECHO_PARAMS, null);
  if (ep != null) {
    EchoParamStyle echoParams = EchoParamStyle.get(ep);
    if (echoParams == null) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid value '" + ep + "' for " + CommonParams.HEADER_ECHO_PARAMS
          + " parameter, use '" + EchoParamStyle.EXPLICIT + "' or '" + EchoParamStyle.ALL + "'");
    }
    if (echoParams == EchoParamStyle.EXPLICIT) {
      responseHeader.add("params", req.getOriginalParams().toNamedList());
    } else if (echoParams == EchoParamStyle.ALL) {
      responseHeader.add("params", req.getParams().toNamedList());
    }
  }
}
 
Example 17
Source File: SchemaSimilarityFactory.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void init(SolrParams args) {
  defaultSimFromFieldType = args.get(INIT_OPT, null);
  super.init(args);
}
 
Example 18
Source File: SecureCollectionsHandler.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  // Pick the action
  SolrParams params = req.getParams();
  CollectionAction action = null;
  String a = params.get(CoreAdminParams.ACTION);
  String collection = null;
  if (a != null) {
    action = CollectionAction.get(a);
  }
  if (action != null) {
    switch (action) {
      case CREATE:
      case DELETE:
      case RELOAD:
      case CREATEALIAS: // FixMe: do we need to check the underlying "collections" as well?
      case DELETEALIAS:
      {
        collection = req.getParams().required().get("name");
        break;
      }
      case SYNCSHARD:
      case SPLITSHARD:
      case DELETESHARD: {
        collection = req.getParams().required().get("collection");
        break;
      }
      default: {
        collection = null;
        break;
      }
    }
  }
  // all actions require UPDATE privileges
  SecureRequestHandlerUtil.checkSentryAdmin(req, SecureRequestHandlerUtil.UPDATE_ONLY,
    (action != null ? "CollectionAction." + action.toString() : getClass().getName() + "/" + a), true, collection);
  super.handleRequestBody(req, rsp);

  /**
   * Attempt to sync collection privileges with Sentry when the metadata has changed.
   * ex: When the collection has been deleted, the privileges related to the collection
   * were also needed to drop.
   */
  if (CollectionAction.DELETE.equals(action)) {
    SecureRequestHandlerUtil.syncDeleteCollection(collection);
  }

}
 
Example 19
Source File: FacetModule.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void prepare(ResponseBuilder rb) throws IOException {
  Map<String, Object> json = rb.req.getJSON();
  Map<String, Object> jsonFacet = null;
  if (json == null) {
    int version = rb.req.getParams().getInt("facet.version", 1);
    if (version <= 1) return;
    boolean facetsEnabled = rb.req.getParams().getBool(FacetParams.FACET, false);
    if (!facetsEnabled) return;
    jsonFacet = new LegacyFacet(rb.req.getParams()).getLegacy();
  } else {
    Object jsonObj = json.get("facet");
    if (jsonObj instanceof Map) {
      jsonFacet = (Map<String, Object>) jsonObj;
    } else if (jsonObj != null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
          "Expected Map for 'facet', received " + jsonObj.getClass().getSimpleName() + "=" + jsonObj);
    }
  }
  if (jsonFacet == null) return;

  SolrParams params = rb.req.getParams();

  boolean isShard = params.getBool(ShardParams.IS_SHARD, false);
  @SuppressWarnings({"unchecked"})
  Map<String, Object> facetInfo = null;
  if (isShard) {
    String jfacet = params.get(FACET_INFO);
    if (jfacet == null) {
      // if this is a shard request, but there is no _facet_ info, then don't do anything.
      return;
    }
    facetInfo = (Map<String, Object>) fromJSONString(jfacet);
  }

  // At this point, we know we need to do something.  Create and save the state.
  rb.setNeedDocSet(true);

  // Parse the facet in the prepare phase?
  FacetRequest facetRequest = FacetRequest.parse(rb.req, jsonFacet);

  FacetComponentState fcState = new FacetComponentState();
  fcState.rb = rb;
  fcState.isShard = isShard;
  fcState.facetInfo = facetInfo;
  fcState.facetCommands = jsonFacet;
  fcState.facetRequest = facetRequest;

  rb.req.getContext().put(FacetComponentState.class, fcState);
}
 
Example 20
Source File: Sparql11SearchHandler.java    From SolRDF with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if the current request contains the "update" parameter.
 * 
 * @param parameters the parameters associated with the current request.
 * @return true if the current request contains the "update" parameter.
 */
boolean containsUpdateParameter(final SolrParams parameters) {
	return parameters.get(Names.UPDATE_PARAMETER_NAME) != null;
}