SOLR-14533: Fix or suppress warnings in solr/handler/admin

This commit is contained in:
Erick Erickson 2020-06-04 07:02:55 -04:00
parent 08a13ce589
commit bab4fccba2
54 changed files with 271 additions and 154 deletions

View File

@ -280,6 +280,8 @@ Other Changes
* SOLR-14526: fix or suppress warnings in apache/solr/core (Erick Erickson) * SOLR-14526: fix or suppress warnings in apache/solr/core (Erick Erickson)
* SOLR-14533: Fix or suppress warnings in solr/handler/admin (Andras Salamon, Erick Erickson)
================== 8.5.2 ================== ================== 8.5.2 ==================
Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release. Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release.

View File

@ -122,7 +122,8 @@ public class GraphHandler extends RequestHandlerBase implements SolrCoreAware, P
Expressible.class); Expressible.class);
streamFactory.withFunctionName(key, clazz); streamFactory.withFunctionName(key, clazz);
} else { } else {
StreamHandler.ExpressibleHolder holder = new StreamHandler.ExpressibleHolder(pluginInfo, core, SolrConfig.classVsSolrPluginInfo.get(Expressible.class)); @SuppressWarnings("resource")
StreamHandler.ExpressibleHolder holder = new StreamHandler.ExpressibleHolder(pluginInfo, core, SolrConfig.classVsSolrPluginInfo.get(Expressible.class.getName()));
streamFactory.withFunctionName(key, () -> holder.getClazz()); streamFactory.withFunctionName(key, () -> holder.getClazz());
} }

View File

@ -199,6 +199,7 @@ public abstract class RequestHandlerBase implements SolrRequestHandler, SolrInfo
} }
} }
Timer.Context timer = requestTimes.time(); Timer.Context timer = requestTimes.time();
@SuppressWarnings("resource")
Timer.Context dTimer = distrib ? distribRequestTimes.time() : localRequestTimes.time(); Timer.Context dTimer = distrib ? distribRequestTimes.time() : localRequestTimes.time();
try { try {
if (pluginInfo != null && pluginInfo.attributes.containsKey(USEPARAM)) if (pluginInfo != null && pluginInfo.attributes.containsKey(USEPARAM))

View File

@ -561,7 +561,9 @@ public class SolrConfigHandler extends RequestHandlerBase implements SolrCoreAwa
return overlay; return overlay;
} }
try { try {
new PluginBag.RuntimeLib(req.getCore()).init(new PluginInfo(info.tag, op.getDataMap())); try (PluginBag.RuntimeLib rtl = new PluginBag.RuntimeLib(req.getCore())) {
rtl.init(new PluginInfo(info.tag, op.getDataMap()));
}
} catch (Exception e) { } catch (Exception e) {
op.addError(e.getMessage()); op.addError(e.getMessage());
log.error("can't load this plugin ", e); log.error("can't load this plugin ", e);
@ -599,6 +601,7 @@ public class SolrConfigHandler extends RequestHandlerBase implements SolrCoreAwa
//this is not dynamically loaded so we can verify the class right away //this is not dynamically loaded so we can verify the class right away
try { try {
if(expected == Expressible.class) { if(expected == Expressible.class) {
@SuppressWarnings("resource")
SolrResourceLoader resourceLoader = info.pkgName == null ? SolrResourceLoader resourceLoader = info.pkgName == null ?
req.getCore().getResourceLoader() : req.getCore().getResourceLoader() :
req.getCore().getResourceLoader(info.pkgName); req.getCore().getResourceLoader(info.pkgName);

View File

@ -128,7 +128,8 @@ public class StreamHandler extends RequestHandlerBase implements SolrCoreAware,
List<PluginInfo> pluginInfos = core.getSolrConfig().getPluginInfos(Expressible.class.getName()); List<PluginInfo> pluginInfos = core.getSolrConfig().getPluginInfos(Expressible.class.getName());
for (PluginInfo pluginInfo : pluginInfos) { for (PluginInfo pluginInfo : pluginInfos) {
if (pluginInfo.pkgName != null) { if (pluginInfo.pkgName != null) {
ExpressibleHolder holder = new ExpressibleHolder(pluginInfo, core, SolrConfig.classVsSolrPluginInfo.get(Expressible.class)); @SuppressWarnings("resource")
ExpressibleHolder holder = new ExpressibleHolder(pluginInfo, core, SolrConfig.classVsSolrPluginInfo.get(Expressible.class.getName()));
streamFactory.withFunctionName(pluginInfo.name, streamFactory.withFunctionName(pluginInfo.name,
() -> holder.getClazz()); () -> holder.getClazz());
} else { } else {
@ -188,6 +189,7 @@ public class StreamHandler extends RequestHandlerBase implements SolrCoreAware,
final SolrCore core = req.getCore(); // explicit check for null core (temporary?, for tests) final SolrCore core = req.getCore(); // explicit check for null core (temporary?, for tests)
@SuppressWarnings("resource")
ZkController zkController = core == null ? null : core.getCoreContainer().getZkController(); ZkController zkController = core == null ? null : core.getCoreContainer().getZkController();
RequestReplicaListTransformerGenerator requestReplicaListTransformerGenerator; RequestReplicaListTransformerGenerator requestReplicaListTransformerGenerator;
if (zkController != null) { if (zkController != null) {

View File

@ -69,6 +69,7 @@ public class AdminHandlersProxy {
Set<String> nodes; Set<String> nodes;
String pathStr = req.getPath(); String pathStr = req.getPath();
@SuppressWarnings({"unchecked"})
Map<String,String> paramsMap = req.getParams().toMap(new HashMap<>()); Map<String,String> paramsMap = req.getParams().toMap(new HashMap<>());
paramsMap.remove(PARAM_NODES); paramsMap.remove(PARAM_NODES);
SolrParams params = new MapSolrParams(paramsMap); SolrParams params = new MapSolrParams(paramsMap);
@ -125,6 +126,7 @@ public class AdminHandlersProxy {
log.debug("Proxying {} request to node {}", endpoint, nodeName); log.debug("Proxying {} request to node {}", endpoint, nodeName);
URL baseUrl = new URL(zkController.zkStateReader.getBaseUrlForNodeName(nodeName)); URL baseUrl = new URL(zkController.zkStateReader.getBaseUrlForNodeName(nodeName));
HttpSolrClient solr = new HttpSolrClient.Builder(baseUrl.toString()).build(); HttpSolrClient solr = new HttpSolrClient.Builder(baseUrl.toString()).build();
@SuppressWarnings({"rawtypes"})
SolrRequest proxyReq = new GenericSolrRequest(SolrRequest.METHOD.GET, endpoint, params); SolrRequest proxyReq = new GenericSolrRequest(SolrRequest.METHOD.GET, endpoint, params);
HttpSolrClient.HttpUriRequestResponse proxyResp = solr.httpUriRequest(proxyReq); HttpSolrClient.HttpUriRequestResponse proxyResp = solr.httpUriRequest(proxyReq);
return new Pair<>(proxyResp.future, solr); return new Pair<>(proxyResp.future, solr);

View File

@ -100,6 +100,7 @@ public class AutoscalingHistoryHandler extends RequestHandlerBase implements Per
} }
@Override @Override
@SuppressWarnings({"unchecked"})
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams()); ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
String collection = params.get(SYSTEM_COLLECTION_PARAM, CollectionAdminParams.SYSTEM_COLL); String collection = params.get(SYSTEM_COLLECTION_PARAM, CollectionAdminParams.SYSTEM_COLL);

View File

@ -132,6 +132,7 @@ public abstract class BaseHandlerApiSupport implements ApiSupport {
/** /**
* Wrapper for SolrParams that wraps V2 params and exposes them as V1 params. * Wrapper for SolrParams that wraps V2 params and exposes them as V1 params.
*/ */
@SuppressWarnings({"unchecked"})
private static void wrapParams(final SolrQueryRequest req, final CommandOperation co, final ApiCommand cmd, final boolean useRequestParams) { private static void wrapParams(final SolrQueryRequest req, final CommandOperation co, final ApiCommand cmd, final boolean useRequestParams) {
final Map<String, String> pathValues = req.getPathTemplateValues(); final Map<String, String> pathValues = req.getPathTemplateValues();
final Map<String, Object> map = co == null || !(co.getCommandData() instanceof Map) ? final Map<String, Object> map = co == null || !(co.getCommandData() instanceof Map) ?
@ -158,6 +159,7 @@ public abstract class BaseHandlerApiSupport implements ApiSupport {
if (o == null) o = pathValues.get(param); if (o == null) o = pathValues.get(param);
if (o == null && useRequestParams) o = origParams.getParams(param); if (o == null && useRequestParams) o = origParams.getParams(param);
if (o instanceof List) { if (o instanceof List) {
@SuppressWarnings({"rawtypes"})
List l = (List) o; List l = (List) o;
return l.toArray(new String[l.size()]); return l.toArray(new String[l.size()]);
} }
@ -179,7 +181,7 @@ public abstract class BaseHandlerApiSupport implements ApiSupport {
} }
@Override @Override
public Map toMap(Map<String, Object> suppliedMap) { public Map<String, Object> toMap(Map<String, Object> suppliedMap) {
for(Iterator<String> it=getParameterNamesIterator(); it.hasNext(); ) { for(Iterator<String> it=getParameterNamesIterator(); it.hasNext(); ) {
final String param = it.next(); final String param = it.next();
String key = cmd.meta().getParamSubstitute(param); String key = cmd.meta().getParamSubstitute(param);
@ -197,6 +199,7 @@ public abstract class BaseHandlerApiSupport implements ApiSupport {
Boolean.class.isAssignableFrom(oClass)) { Boolean.class.isAssignableFrom(oClass)) {
suppliedMap.put(param,String.valueOf(o)); suppliedMap.put(param,String.valueOf(o));
} else if (List.class.isAssignableFrom(oClass) && ((List)o).get(0) instanceof String ) { } else if (List.class.isAssignableFrom(oClass) && ((List)o).get(0) instanceof String ) {
@SuppressWarnings({"unchecked"})
List<String> l = (List<String>) o; List<String> l = (List<String>) o;
suppliedMap.put( param, l.toArray(new String[0])); suppliedMap.put( param, l.toArray(new String[0]));
} else { } else {

View File

@ -55,7 +55,7 @@ public class ClusterStatus {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void getClusterStatus(NamedList results) public void getClusterStatus(@SuppressWarnings({"rawtypes"})NamedList results)
throws KeeperException, InterruptedException { throws KeeperException, InterruptedException {
// read aliases // read aliases
Aliases aliases = zkStateReader.getAliases(); Aliases aliases = zkStateReader.getAliases();
@ -72,6 +72,7 @@ public class ClusterStatus {
} }
} }
@SuppressWarnings({"rawtypes"})
Map roles = null; Map roles = null;
if (zkStateReader.getZkClient().exists(ZkStateReader.ROLES, true)) { if (zkStateReader.getZkClient().exists(ZkStateReader.ROLES, true)) {
roles = (Map) Utils.fromJSON(zkStateReader.getZkClient().getData(ZkStateReader.ROLES, null, null, true)); roles = (Map) Utils.fromJSON(zkStateReader.getZkClient().getData(ZkStateReader.ROLES, null, null, true));
@ -165,6 +166,7 @@ public class ClusterStatus {
clusterStatus.add("collections", collectionProps); clusterStatus.add("collections", collectionProps);
// read cluster properties // read cluster properties
@SuppressWarnings({"rawtypes"})
Map clusterProps = zkStateReader.getClusterProperties(); Map clusterProps = zkStateReader.getClusterProperties();
if (clusterProps != null && !clusterProps.isEmpty()) { if (clusterProps != null && !clusterProps.isEmpty()) {
clusterStatus.add("properties", clusterProps); clusterStatus.add("properties", clusterProps);

View File

@ -71,6 +71,7 @@ public class ColStatus {
this.clusterState = clusterState; this.clusterState = clusterState;
} }
@SuppressWarnings({"unchecked"})
public void getColStatus(NamedList<Object> results) { public void getColStatus(NamedList<Object> results) {
Collection<String> collections; Collection<String> collections;
String col = props.getStr(ZkStateReader.COLLECTION_PROP); String col = props.getStr(ZkStateReader.COLLECTION_PROP);

View File

@ -204,7 +204,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
} }
@Override @Override
final public void init(NamedList args) { final public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
} }
@ -261,6 +261,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
rsp.setHttpCaching(false); rsp.setHttpCaching(false);
} }
@SuppressWarnings({"unchecked"})
void invokeAction(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer cores, CollectionAction action, CollectionOperation operation) throws Exception { void invokeAction(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer cores, CollectionAction action, CollectionOperation operation) throws Exception {
if (!coreContainer.isZooKeeperAware()) { if (!coreContainer.isZooKeeperAware()) {
throw new SolrException(BAD_REQUEST, throw new SolrException(BAD_REQUEST,
@ -514,6 +515,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
return copyPropertiesWithPrefix(req.getParams(), props, "router."); return copyPropertiesWithPrefix(req.getParams(), props, "router.");
}), }),
@SuppressWarnings({"unchecked"})
COLSTATUS_OP(COLSTATUS, (req, rsp, h) -> { COLSTATUS_OP(COLSTATUS, (req, rsp, h) -> {
Map<String, Object> props = copy(req.getParams(), null, Map<String, Object> props = copy(req.getParams(), null,
COLLECTION_PROP, COLLECTION_PROP,
@ -603,6 +605,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
return null; return null;
}), }),
@SuppressWarnings({"unchecked"})
CREATEALIAS_OP(CREATEALIAS, (req, rsp, h) -> { CREATEALIAS_OP(CREATEALIAS, (req, rsp, h) -> {
String alias = req.getParams().get(NAME); String alias = req.getParams().get(NAME);
SolrIdentifierValidator.validateAliasName(alias); SolrIdentifierValidator.validateAliasName(alias);
@ -617,7 +620,6 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
// we'll throw this later if we are in fact creating a routed alias. // we'll throw this later if we are in fact creating a routed alias.
ex = e; ex = e;
} }
@SuppressWarnings("unchecked")
ModifiableSolrParams finalParams = new ModifiableSolrParams(); ModifiableSolrParams finalParams = new ModifiableSolrParams();
for (Map.Entry<String, Object> entry : possiblyModifiedParams.entrySet()) { for (Map.Entry<String, Object> entry : possiblyModifiedParams.entrySet()) {
if (entry.getValue().getClass().isArray() ) { if (entry.getValue().getClass().isArray() ) {
@ -705,6 +707,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
/** /**
* List the aliases and associated properties. * List the aliases and associated properties.
*/ */
@SuppressWarnings({"unchecked"})
LISTALIASES_OP(LISTALIASES, (req, rsp, h) -> { LISTALIASES_OP(LISTALIASES, (req, rsp, h) -> {
ZkStateReader zkStateReader = h.coreContainer.getZkController().getZkStateReader(); ZkStateReader zkStateReader = h.coreContainer.getZkController().getZkStateReader();
// if someone calls listAliases, lets ensure we return an up to date response // if someone calls listAliases, lets ensure we return an up to date response
@ -852,6 +855,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
cp.setCollectionProperty(collection, name, val); cp.setCollectionProperty(collection, name, val);
return null; return null;
}), }),
@SuppressWarnings({"unchecked"})
REQUESTSTATUS_OP(REQUESTSTATUS, (req, rsp, h) -> { REQUESTSTATUS_OP(REQUESTSTATUS, (req, rsp, h) -> {
req.getParams().required().check(REQUESTID); req.getParams().required().check(REQUESTID);
@ -952,6 +956,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
* Handle list collection request. * Handle list collection request.
* Do list collection request to zk host * Do list collection request to zk host
*/ */
@SuppressWarnings({"unchecked"})
LIST_OP(LIST, (req, rsp, h) -> { LIST_OP(LIST, (req, rsp, h) -> {
NamedList<Object> results = new NamedList<>(); NamedList<Object> results = new NamedList<>();
Map<String, DocCollection> collections = h.coreContainer.getZkController().getZkStateReader().getClusterState().getCollectionsMap(); Map<String, DocCollection> collections = h.coreContainer.getZkController().getZkStateReader().getClusterState().getCollectionsMap();
@ -1448,9 +1453,11 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
} }
public static void verifyRuleParams(CoreContainer cc, Map<String, Object> m) { public static void verifyRuleParams(CoreContainer cc, Map<String, Object> m) {
@SuppressWarnings({"rawtypes"})
List l = (List) m.get(RULE); List l = (List) m.get(RULE);
if (l != null) { if (l != null) {
for (Object o : l) { for (Object o : l) {
@SuppressWarnings({"rawtypes"})
Map map = (Map) o; Map map = (Map) o;
try { try {
new Rule(map); new Rule(map);
@ -1476,6 +1483,7 @@ public class CollectionsHandler extends RequestHandlerBase implements Permission
val.add(v.toString()); val.add(v.toString());
} }
if (val.size() > 0) { if (val.size() > 0) {
@SuppressWarnings({"rawtypes"})
ArrayList<Map> l = new ArrayList<>(); ArrayList<Map> l = new ArrayList<>();
for (String rule : val) l.add(Rule.parseRule(rule)); for (String rule : val) l.add(Rule.parseRule(rule));
props.put(key, l); props.put(key, l);

View File

@ -209,6 +209,7 @@ public class ConfigSetsHandler extends RequestHandlerBase implements PermissionN
} }
} }
@SuppressWarnings({"unchecked"})
private void handleResponse(String operation, ZkNodeProps m, private void handleResponse(String operation, ZkNodeProps m,
SolrQueryResponse rsp, long timeout) throws KeeperException, InterruptedException { SolrQueryResponse rsp, long timeout) throws KeeperException, InterruptedException {
long time = System.nanoTime(); long time = System.nanoTime();
@ -219,6 +220,7 @@ public class ConfigSetsHandler extends RequestHandlerBase implements PermissionN
if (event.getBytes() != null) { if (event.getBytes() != null) {
SolrResponse response = OverseerSolrResponseSerializer.deserialize(event.getBytes()); SolrResponse response = OverseerSolrResponseSerializer.deserialize(event.getBytes());
rsp.getValues().addAll(response.getResponse()); rsp.getValues().addAll(response.getResponse());
@SuppressWarnings({"rawtypes"})
SimpleOrderedMap exp = (SimpleOrderedMap) response.getResponse().get("exception"); SimpleOrderedMap exp = (SimpleOrderedMap) response.getResponse().get("exception");
if (exp != null) { if (exp != null) {
Integer code = (Integer) exp.get("rspCode"); Integer code = (Integer) exp.get("rspCode");
@ -282,6 +284,7 @@ public class ConfigSetsHandler extends RequestHandlerBase implements PermissionN
return CollectionsHandler.copy(req.getParams().required(), null, NAME); return CollectionsHandler.copy(req.getParams().required(), null, NAME);
} }
}, },
@SuppressWarnings({"unchecked"})
LIST_OP(LIST) { LIST_OP(LIST) {
@Override @Override
Map<String, Object> call(SolrQueryRequest req, SolrQueryResponse rsp, ConfigSetsHandler h) throws Exception { Map<String, Object> call(SolrQueryRequest req, SolrQueryResponse rsp, ConfigSetsHandler h) throws Exception {

View File

@ -245,6 +245,7 @@ enum CoreAdminOperation implements CoreAdminOp {
RESTORECORE_OP(RESTORECORE, new RestoreCoreOp()), RESTORECORE_OP(RESTORECORE, new RestoreCoreOp()),
CREATESNAPSHOT_OP(CREATESNAPSHOT, new CreateSnapshotOp()), CREATESNAPSHOT_OP(CREATESNAPSHOT, new CreateSnapshotOp()),
DELETESNAPSHOT_OP(DELETESNAPSHOT, new DeleteSnapshotOp()), DELETESNAPSHOT_OP(DELETESNAPSHOT, new DeleteSnapshotOp()),
@SuppressWarnings({"unchecked"})
LISTSNAPSHOTS_OP(LISTSNAPSHOTS, it -> { LISTSNAPSHOTS_OP(LISTSNAPSHOTS, it -> {
final SolrParams params = it.req.getParams(); final SolrParams params = it.req.getParams();
String cname = params.required().get(CoreAdminParams.CORE); String cname = params.required().get(CoreAdminParams.CORE);
@ -257,6 +258,7 @@ enum CoreAdminOperation implements CoreAdminOp {
} }
SolrSnapshotMetaDataManager mgr = core.getSnapshotMetaDataManager(); SolrSnapshotMetaDataManager mgr = core.getSnapshotMetaDataManager();
@SuppressWarnings({"rawtypes"})
NamedList result = new NamedList(); NamedList result = new NamedList();
for (String name : mgr.listSnapshots()) { for (String name : mgr.listSnapshots()) {
Optional<SnapshotMetaData> metadata = mgr.getSnapshotMetaData(name); Optional<SnapshotMetaData> metadata = mgr.getSnapshotMetaData(name);
@ -296,6 +298,7 @@ enum CoreAdminOperation implements CoreAdminOp {
* @return - a named list of key/value pairs from the core. * @return - a named list of key/value pairs from the core.
* @throws IOException - LukeRequestHandler can throw an I/O exception * @throws IOException - LukeRequestHandler can throw an I/O exception
*/ */
@SuppressWarnings({"unchecked", "rawtypes"})
static NamedList<Object> getCoreStatus(CoreContainer cores, String cname, boolean isIndexInfoNeeded) throws IOException { static NamedList<Object> getCoreStatus(CoreContainer cores, String cname, boolean isIndexInfoNeeded) throws IOException {
NamedList<Object> info = new SimpleOrderedMap<>(); NamedList<Object> info = new SimpleOrderedMap<>();

View File

@ -78,7 +78,7 @@ public class HealthCheckHandler extends RequestHandlerBase {
} }
@Override @Override
final public void init(NamedList args) { final public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
} }
public CoreContainer getCoreContainer() { public CoreContainer getCoreContainer() {

View File

@ -194,6 +194,7 @@ public class IndexSizeEstimator {
this.samplingPercent = percent; this.samplingPercent = percent;
} }
@SuppressWarnings({"unchecked"})
public Estimate estimate() throws Exception { public Estimate estimate() throws Exception {
Map<String, Object> details = new LinkedHashMap<>(); Map<String, Object> details = new LinkedHashMap<>();
Map<String, Object> summary = new LinkedHashMap<>(); Map<String, Object> summary = new LinkedHashMap<>();
@ -244,6 +245,7 @@ public class IndexSizeEstimator {
return new Estimate(fieldsBySize, typesBySize, withSummary ? newSummary : null, withDetails ? details : null); return new Estimate(fieldsBySize, typesBySize, withSummary ? newSummary : null, withDetails ? details : null);
} }
@SuppressWarnings({"unchecked"})
private void convert(Map<String, Object> result) { private void convert(Map<String, Object> result) {
for (Map.Entry<String, Object> entry : result.entrySet()) { for (Map.Entry<String, Object> entry : result.entrySet()) {
Object value = entry.getValue(); Object value = entry.getValue();
@ -266,6 +268,7 @@ public class IndexSizeEstimator {
} }
} }
@SuppressWarnings({"unchecked"})
private void estimateSummary(Map<String, Object> details, Map<String, Object> summary) { private void estimateSummary(Map<String, Object> details, Map<String, Object> summary) {
log.info("- preparing summary..."); log.info("- preparing summary...");
details.forEach((type, perType) -> { details.forEach((type, perType) -> {

View File

@ -56,7 +56,7 @@ public class InfoHandler extends RequestHandlerBase {
@Override @Override
final public void init(NamedList args) { final public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
} }

View File

@ -47,6 +47,7 @@ import org.slf4j.LoggerFactory;
public class LoggingHandler extends RequestHandlerBase implements SolrCoreAware { public class LoggingHandler extends RequestHandlerBase implements SolrCoreAware {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@SuppressWarnings({"rawtypes"})
private LogWatcher watcher; private LogWatcher watcher;
public LoggingHandler(CoreContainer cc) { public LoggingHandler(CoreContainer cc) {
@ -139,6 +140,7 @@ public class LoggingHandler extends RequestHandlerBase implements SolrCoreAware
else { else {
rsp.add("levels", watcher.getAllLevels()); rsp.add("levels", watcher.getAllLevels());
@SuppressWarnings({"unchecked"})
List<LoggerInfo> loggers = new ArrayList<>(watcher.getAllLoggers()); List<LoggerInfo> loggers = new ArrayList<>(watcher.getAllLoggers());
Collections.sort(loggers); Collections.sort(loggers);

View File

@ -750,6 +750,7 @@ public class LukeRequestHandler extends RequestHandlerBase
/** /**
* Private internal class that counts up frequent terms * Private internal class that counts up frequent terms
*/ */
@SuppressWarnings("rawtypes")
private static class TopTermQueue extends PriorityQueue private static class TopTermQueue extends PriorityQueue
{ {
static class TermInfo { static class TermInfo {

View File

@ -93,7 +93,7 @@ public class MetricsCollectorHandler extends RequestHandlerBase {
} }
@Override @Override
public void init(NamedList initArgs) { public void init(@SuppressWarnings({"rawtypes"})NamedList initArgs) {
super.init(initArgs); super.init(initArgs);
if (initArgs != null) { if (initArgs != null) {
params = initArgs.toSolrParams(); params = initArgs.toSolrParams();

View File

@ -103,6 +103,7 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName
handleRequest(req.getParams(), (k, v) -> rsp.add(k, v)); handleRequest(req.getParams(), (k, v) -> rsp.add(k, v));
} }
@SuppressWarnings({"unchecked"})
public void handleRequest(SolrParams params, BiConsumer<String, Object> consumer) throws Exception { public void handleRequest(SolrParams params, BiConsumer<String, Object> consumer) throws Exception {
boolean compact = params.getBool(COMPACT_PARAM, true); boolean compact = params.getBool(COMPACT_PARAM, true);
String[] keys = params.getParams(KEY_PARAM); String[] keys = params.getParams(KEY_PARAM);
@ -116,9 +117,11 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName
List<MetricFilter> metricFilters = metricTypes.stream().map(MetricType::asMetricFilter).collect(Collectors.toList()); List<MetricFilter> metricFilters = metricTypes.stream().map(MetricType::asMetricFilter).collect(Collectors.toList());
Set<String> requestedRegistries = parseRegistries(params); Set<String> requestedRegistries = parseRegistries(params);
@SuppressWarnings({"rawtypes"})
NamedList response = new SimpleOrderedMap(); NamedList response = new SimpleOrderedMap();
for (String registryName : requestedRegistries) { for (String registryName : requestedRegistries) {
MetricRegistry registry = metricManager.registry(registryName); MetricRegistry registry = metricManager.registry(registryName);
@SuppressWarnings({"rawtypes"})
SimpleOrderedMap result = new SimpleOrderedMap(); SimpleOrderedMap result = new SimpleOrderedMap();
MetricUtils.toMaps(registry, metricFilters, mustMatchFilter, propertyFilter, false, MetricUtils.toMaps(registry, metricFilters, mustMatchFilter, propertyFilter, false,
false, compact, false, (k, v) -> result.add(k, v)); false, compact, false, (k, v) -> result.add(k, v));
@ -129,6 +132,7 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName
consumer.accept("metrics", response); consumer.accept("metrics", response);
} }
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleKeyRequest(String[] keys, BiConsumer<String, Object> consumer) throws Exception { public void handleKeyRequest(String[] keys, BiConsumer<String, Object> consumer) throws Exception {
SimpleOrderedMap result = new SimpleOrderedMap(); SimpleOrderedMap result = new SimpleOrderedMap();
SimpleOrderedMap errors = new SimpleOrderedMap(); SimpleOrderedMap errors = new SimpleOrderedMap();
@ -345,9 +349,10 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName
public static final String SUPPORTED_TYPES_MSG = EnumSet.allOf(MetricType.class).toString(); public static final String SUPPORTED_TYPES_MSG = EnumSet.allOf(MetricType.class).toString();
@SuppressWarnings({"rawtypes"})
private final Class klass; private final Class klass;
MetricType(Class klass) { MetricType(@SuppressWarnings({"rawtypes"})Class klass) {
this.klass = klass; this.klass = klass;
} }

View File

@ -185,6 +185,7 @@ public class MetricsHistoryHandler extends RequestHandlerBase implements Permiss
} }
// override from ZK if available // override from ZK if available
if (cloudManager != null) { if (cloudManager != null) {
@SuppressWarnings({"unchecked"})
Map<String, Object> props = (Map<String, Object>)cloudManager.getClusterStateProvider() Map<String, Object> props = (Map<String, Object>)cloudManager.getClusterStateProvider()
.getClusterProperty("metrics", Collections.emptyMap()) .getClusterProperty("metrics", Collections.emptyMap())
.getOrDefault("history", Collections.emptyMap()); .getOrDefault("history", Collections.emptyMap());
@ -379,6 +380,7 @@ public class MetricsHistoryHandler extends RequestHandlerBase implements Permiss
ExecutorUtil.setServerThreadFlag(false); ExecutorUtil.setServerThreadFlag(false);
} }
@SuppressWarnings({"unchecked", "rawtypes"})
private void collectLocalReplicaMetrics() { private void collectLocalReplicaMetrics() {
List<Group> groups = new ArrayList<>(); List<Group> groups = new ArrayList<>();
if (enableNodes) { if (enableNodes) {
@ -800,6 +802,7 @@ public class MetricsHistoryHandler extends RequestHandlerBase implements Permiss
rsp.getResponseHeader().add("zkConnected", cloudManager != null); rsp.getResponseHeader().add("zkConnected", cloudManager != null);
} }
@SuppressWarnings({"unchecked"})
private NamedList<Object> handleRemoteRequest(String nodeName, SolrQueryRequest req) { private NamedList<Object> handleRemoteRequest(String nodeName, SolrQueryRequest req) {
String baseUrl = Utils.getBaseUrlForNodeName(nodeName, overseerUrlScheme); String baseUrl = Utils.getBaseUrlForNodeName(nodeName, overseerUrlScheme);
String url; String url;
@ -827,6 +830,7 @@ public class MetricsHistoryHandler extends RequestHandlerBase implements Permiss
} }
} }
@SuppressWarnings({"unchecked", "rawtypes"})
private void mergeRemoteRes(SolrQueryResponse rsp, NamedList<Object> remoteRes) { private void mergeRemoteRes(SolrQueryResponse rsp, NamedList<Object> remoteRes) {
if (remoteRes == null || remoteRes.get("metrics") == null) { if (remoteRes == null || remoteRes.get("metrics") == null) {
return; return;

View File

@ -110,6 +110,7 @@ class RebalanceLeaders {
final static String INACTIVE_PREFERREDS = "inactivePreferreds"; final static String INACTIVE_PREFERREDS = "inactivePreferreds";
final static String ALREADY_LEADERS = "alreadyLeaders"; final static String ALREADY_LEADERS = "alreadyLeaders";
final static String SUMMARY = "Summary"; final static String SUMMARY = "Summary";
@SuppressWarnings({"rawtypes"})
final SimpleOrderedMap results = new SimpleOrderedMap(); final SimpleOrderedMap results = new SimpleOrderedMap();
final Map<String, String> pendingOps = new HashMap<>(); final Map<String, String> pendingOps = new HashMap<>();
private String collectionName; private String collectionName;
@ -122,6 +123,7 @@ class RebalanceLeaders {
coreContainer = collectionsHandler.getCoreContainer(); coreContainer = collectionsHandler.getCoreContainer();
} }
@SuppressWarnings({"unchecked", "rawtypes"})
void execute() throws KeeperException, InterruptedException { void execute() throws KeeperException, InterruptedException {
DocCollection dc = checkParams(); DocCollection dc = checkParams();
@ -286,6 +288,7 @@ class RebalanceLeaders {
// Provide some feedback to the user about what actually happened, or in this case where no action was // Provide some feedback to the user about what actually happened, or in this case where no action was
// possible // possible
@SuppressWarnings({"unchecked", "rawtypes"})
private void addInactiveToResults(Slice slice, Replica replica) { private void addInactiveToResults(Slice slice, Replica replica) {
SimpleOrderedMap inactives = (SimpleOrderedMap) results.get(INACTIVE_PREFERREDS); SimpleOrderedMap inactives = (SimpleOrderedMap) results.get(INACTIVE_PREFERREDS);
if (inactives == null) { if (inactives == null) {
@ -300,6 +303,7 @@ class RebalanceLeaders {
// Provide some feedback to the user about what actually happened, or in this case where no action was // Provide some feedback to the user about what actually happened, or in this case where no action was
// necesary since this preferred replica was already the leader // necesary since this preferred replica was already the leader
@SuppressWarnings({"unchecked", "rawtypes"})
private void addAlreadyLeaderToResults(Slice slice, Replica replica) { private void addAlreadyLeaderToResults(Slice slice, Replica replica) {
SimpleOrderedMap alreadyLeaders = (SimpleOrderedMap) results.get(ALREADY_LEADERS); SimpleOrderedMap alreadyLeaders = (SimpleOrderedMap) results.get(ALREADY_LEADERS);
if (alreadyLeaders == null) { if (alreadyLeaders == null) {
@ -458,6 +462,7 @@ class RebalanceLeaders {
} }
// If we actually changed the leader, we should send that fact back in the response. // If we actually changed the leader, we should send that fact back in the response.
@SuppressWarnings({"unchecked", "rawtypes"})
private void addToSuccesses(Slice slice, Replica replica) { private void addToSuccesses(Slice slice, Replica replica) {
SimpleOrderedMap successes = (SimpleOrderedMap) results.get("successes"); SimpleOrderedMap successes = (SimpleOrderedMap) results.get("successes");
if (successes == null) { if (successes == null) {
@ -476,6 +481,7 @@ class RebalanceLeaders {
// If for any reason we were supposed to change leadership, that should be recorded in changingLeaders. Any // If for any reason we were supposed to change leadership, that should be recorded in changingLeaders. Any
// time we verified that the change actually occurred, that entry should have been removed. So report anything // time we verified that the change actually occurred, that entry should have been removed. So report anything
// left over as a failure. // left over as a failure.
@SuppressWarnings({"unchecked", "rawtypes"})
private void addAnyFailures() { private void addAnyFailures() {
if (pendingOps.size() == 0) { if (pendingOps.size() == 0) {
return; return;

View File

@ -86,6 +86,7 @@ public abstract class SecurityConfHandler extends RequestHandlerBase implements
} }
} }
@SuppressWarnings({"unchecked", "rawtypes"})
private void doEdit(SolrQueryRequest req, SolrQueryResponse rsp, String path, final String key, final Object plugin) private void doEdit(SolrQueryRequest req, SolrQueryResponse rsp, String path, final String key, final Object plugin)
throws IOException { throws IOException {
ConfigEditablePlugin configEditablePlugin = null; ConfigEditablePlugin configEditablePlugin = null;
@ -156,14 +157,16 @@ public abstract class SecurityConfHandler extends RequestHandlerBase implements
protected abstract void getConf(SolrQueryResponse rsp, String key); protected abstract void getConf(SolrQueryResponse rsp, String key);
public static Map<String, Object> getMapValue(Map<String, Object> lookupMap, String key) { public static Map<String, Object> getMapValue(Map<String, Object> lookupMap, String key) {
@SuppressWarnings({"unchecked"})
Map<String, Object> m = (Map<String, Object>) lookupMap.get(key); Map<String, Object> m = (Map<String, Object>) lookupMap.get(key);
if (m == null) lookupMap.put(key, m = new LinkedHashMap<>()); if (m == null) lookupMap.put(key, m = new LinkedHashMap<>());
return m; return m;
} }
@SuppressWarnings({"rawtypes"})
public static List getListValue(Map<String, Object> lookupMap, String key) { public static List getListValue(Map<String, Object> lookupMap, String key) {
List l = (List) lookupMap.get(key); List l = (List) lookupMap.get(key);
if (l == null) lookupMap.put(key, l= new ArrayList()); if (l == null) lookupMap.put(key, l= new ArrayList<>());
return l; return l;
} }
@ -193,6 +196,7 @@ public abstract class SecurityConfHandler extends RequestHandlerBase implements
* The data object defaults to EMPTY_MAP if not set * The data object defaults to EMPTY_MAP if not set
*/ */
public static class SecurityConfig { public static class SecurityConfig {
@SuppressWarnings({"unchecked"})
private Map<String, Object> data = Collections.EMPTY_MAP; private Map<String, Object> data = Collections.EMPTY_MAP;
private int version = -1; private int version = -1;
@ -213,6 +217,7 @@ public abstract class SecurityConfHandler extends RequestHandlerBase implements
* @param data an Object of type Map&lt;String,Object&gt; * @param data an Object of type Map&lt;String,Object&gt;
* @return SecurityConf object (builder pattern) * @return SecurityConf object (builder pattern)
*/ */
@SuppressWarnings({"unchecked"})
public SecurityConfig setData(Object data) { public SecurityConfig setData(Object data) {
if (data instanceof Map) { if (data instanceof Map) {
this.data = (Map<String, Object>) data; this.data = (Map<String, Object>) data;

View File

@ -103,7 +103,7 @@ public class ShowFileRequestHandler extends RequestHandlerBase
} }
@Override @Override
public void init(NamedList args) { public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
super.init( args ); super.init( args );
hiddenFiles = initHidden(invariants); hiddenFiles = initHidden(invariants);
} }

View File

@ -184,6 +184,7 @@ public class SolrInfoMBeanHandler extends RequestHandlerBase {
// System.out.println( "NOW: " + now_txt ); // System.out.println( "NOW: " + now_txt );
// Calculate the differences // Calculate the differences
@SuppressWarnings({"rawtypes"})
NamedList diff = diffNamedList(ref_bean,now_bean); NamedList diff = diffNamedList(ref_bean,now_bean);
diff.add( "_changed_", true ); // flag the changed thing diff.add( "_changed_", true ); // flag the changed thing
cat.add(name, diff); cat.add(name, diff);
@ -204,6 +205,7 @@ public class SolrInfoMBeanHandler extends RequestHandlerBase {
return changed; return changed;
} }
@SuppressWarnings({"rawtypes"})
public NamedList diffNamedList(NamedList ref, NamedList now) { public NamedList diffNamedList(NamedList ref, NamedList now) {
NamedList out = new SimpleOrderedMap(); NamedList out = new SimpleOrderedMap();
for(int i=0; i<ref.size(); i++) { for(int i=0; i<ref.size(); i++) {
@ -232,6 +234,7 @@ public class SolrInfoMBeanHandler extends RequestHandlerBase {
return out; return out;
} }
@SuppressWarnings({"rawtypes"})
public Object diffObject(Object ref, Object now) { public Object diffObject(Object ref, Object now) {
if (now instanceof Map) { if (now instanceof Map) {
now = new NamedList((Map)now); now = new NamedList((Map)now);
@ -272,6 +275,7 @@ public class SolrInfoMBeanHandler extends RequestHandlerBase {
/** /**
* The 'avgRequestsPerSecond' field will make everything look like it changed * The 'avgRequestsPerSecond' field will make everything look like it changed
*/ */
@SuppressWarnings({"rawtypes"})
public NamedList normalize(NamedList input) { public NamedList normalize(NamedList input) {
input.remove("avgRequestsPerSecond"); input.remove("avgRequestsPerSecond");
for(int i=0; i<input.size(); i++) { for(int i=0; i<input.size(); i++) {

View File

@ -129,6 +129,7 @@ class SplitOp implements CoreAdminHandler.CoreAdminOp {
} }
Object routerObj = collection.get(DOC_ROUTER); // for back-compat with Solr 4.4 Object routerObj = collection.get(DOC_ROUTER); // for back-compat with Solr 4.4
if (routerObj instanceof Map) { if (routerObj instanceof Map) {
@SuppressWarnings({"rawtypes"})
Map routerProps = (Map) routerObj; Map routerProps = (Map) routerObj;
routeFieldName = (String) routerProps.get("field"); routeFieldName = (String) routerProps.get("field");
} }
@ -221,6 +222,7 @@ class SplitOp implements CoreAdminHandler.CoreAdminOp {
Object routerObj = collection.get(DOC_ROUTER); // for back-compat with Solr 4.4 Object routerObj = collection.get(DOC_ROUTER); // for back-compat with Solr 4.4
if (routerObj instanceof Map) { if (routerObj instanceof Map) {
@SuppressWarnings({"rawtypes"})
Map routerProps = (Map) routerObj; Map routerProps = (Map) routerObj;
routeFieldName = (String) routerProps.get("field"); routeFieldName = (String) routerProps.get("field");
} }

View File

@ -339,6 +339,7 @@ public class SystemInfoHandler extends RequestHandlerBase
info.add("username", username); info.add("username", username);
// Mapped roles for this principal // Mapped roles for this principal
@SuppressWarnings("resource")
AuthorizationPlugin auth = cc==null? null: cc.getAuthorizationPlugin(); AuthorizationPlugin auth = cc==null? null: cc.getAuthorizationPlugin();
if (auth != null) { if (auth != null) {
RuleBasedAuthorizationPluginBase rbap = (RuleBasedAuthorizationPluginBase) auth; RuleBasedAuthorizationPluginBase rbap = (RuleBasedAuthorizationPluginBase) auth;

View File

@ -353,6 +353,7 @@ public final class ZookeeperInfoHandler extends RequestHandlerBase {
private PagedCollectionSupport pagingSupport; private PagedCollectionSupport pagingSupport;
@Override @Override
@SuppressWarnings({"unchecked"})
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
final SolrParams params = req.getParams(); final SolrParams params = req.getParams();
Map<String, String> map = new HashMap<>(1); Map<String, String> map = new HashMap<>(1);

View File

@ -73,8 +73,8 @@ public class ZookeeperStatusHandler extends RequestHandlerBase {
return Category.ADMIN; return Category.ADMIN;
} }
@SuppressWarnings("rawtypes")
@Override @Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
NamedList values = rsp.getValues(); NamedList values = rsp.getValues();
if (cores.isZooKeeperAware()) { if (cores.isZooKeeperAware()) {
@ -94,6 +94,7 @@ public class ZookeeperStatusHandler extends RequestHandlerBase {
* @param zkDynamicConfig list of zk dynamic config objects * @param zkDynamicConfig list of zk dynamic config objects
* @return map of zookeeper config and status per zk host * @return map of zookeeper config and status per zk host
*/ */
@SuppressWarnings({"unchecked"})
protected Map<String, Object> getZkStatus(String zkHost, ZkDynamicConfig zkDynamicConfig) { protected Map<String, Object> getZkStatus(String zkHost, ZkDynamicConfig zkDynamicConfig) {
final ZkDynamicConfig hostsFromConnectionString = ZkDynamicConfig.fromZkConnectString(zkHost); final ZkDynamicConfig hostsFromConnectionString = ZkDynamicConfig.fromZkConnectString(zkHost);
final ZkDynamicConfig zookeepers; final ZkDynamicConfig zookeepers;

View File

@ -408,6 +408,7 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements org.
protected ReplicaListTransformer getReplicaListTransformer(final SolrQueryRequest req) { protected ReplicaListTransformer getReplicaListTransformer(final SolrQueryRequest req) {
final SolrParams params = req.getParams(); final SolrParams params = req.getParams();
final SolrCore core = req.getCore(); // explicit check for null core (temporary?, for tests) final SolrCore core = req.getCore(); // explicit check for null core (temporary?, for tests)
@SuppressWarnings("resource")
ZkController zkController = core == null ? null : core.getCoreContainer().getZkController(); ZkController zkController = core == null ? null : core.getCoreContainer().getZkController();
if (zkController != null) { if (zkController != null) {
return requestReplicaListTransformerGenerator.getReplicaListTransformer( return requestReplicaListTransformerGenerator.getReplicaListTransformer(

View File

@ -1116,9 +1116,12 @@ public class RealTimeGetComponent extends SearchComponent
} }
public void processSyncWithLeader(ResponseBuilder rb, int nVersions, String syncWithLeader, List<Long> versions) { public void processSyncWithLeader(ResponseBuilder rb, int nVersions, String syncWithLeader, List<Long> versions) {
PeerSyncWithLeader peerSync = new PeerSyncWithLeader(rb.req.getCore(), syncWithLeader, nVersions); try (PeerSyncWithLeader peerSync = new PeerSyncWithLeader(rb.req.getCore(), syncWithLeader, nVersions)) {
boolean success = peerSync.sync(versions).isSuccess(); boolean success = peerSync.sync(versions).isSuccess();
rb.rsp.add("syncWithLeader", success); rb.rsp.add("syncWithLeader", success);
} catch (IOException e) {
log.error("Error while closing", e);
}
} }
@ -1137,12 +1140,13 @@ public class RealTimeGetComponent extends SearchComponent
List<String> replicas = StrUtils.splitSmart(sync, ",", true); List<String> replicas = StrUtils.splitSmart(sync, ",", true);
boolean cantReachIsSuccess = rb.req.getParams().getBool("cantReachIsSuccess", false); boolean cantReachIsSuccess = rb.req.getParams().getBool("cantReachIsSuccess", false);
try (PeerSync peerSync = new PeerSync(rb.req.getCore(), replicas, nVersions, cantReachIsSuccess)) {
PeerSync peerSync = new PeerSync(rb.req.getCore(), replicas, nVersions, cantReachIsSuccess);
boolean success = peerSync.sync().isSuccess(); boolean success = peerSync.sync().isSuccess();
// TODO: more complex response? // TODO: more complex response?
rb.rsp.add("sync", success); rb.rsp.add("sync", success);
} catch (IOException e) {
log.error("Error while closing", e);
}
} }

View File

@ -133,7 +133,7 @@ public class JavabinLoader extends ContentStreamLoader {
throws IOException { throws IOException {
FastInputStream in = FastInputStream.wrap(stream); FastInputStream in = FastInputStream.wrap(stream);
SolrParams old = req.getParams(); SolrParams old = req.getParams();
new JavaBinCodec() { try (JavaBinCodec jbc = new JavaBinCodec() {
SolrParams params; SolrParams params;
AddUpdateCommand addCmd = null; AddUpdateCommand addCmd = null;
@ -164,7 +164,9 @@ public class JavabinLoader extends ContentStreamLoader {
return Collections.emptyList(); return Collections.emptyList();
} }
}.unmarshal(in); }) {
jbc.unmarshal(in);
}
} }
private AddUpdateCommand getAddCommand(SolrQueryRequest req, SolrParams params) { private AddUpdateCommand getAddCommand(SolrQueryRequest req, SolrParams params) {

View File

@ -53,11 +53,9 @@ public class BinaryUpdateRequestHandlerTest extends SolrTestCaseJ4 {
BinaryRequestWriter brw = new BinaryRequestWriter(); BinaryRequestWriter brw = new BinaryRequestWriter();
BufferingRequestProcessor p = new BufferingRequestProcessor(null); BufferingRequestProcessor p = new BufferingRequestProcessor(null);
SolrQueryResponse rsp = new SolrQueryResponse(); SolrQueryResponse rsp = new SolrQueryResponse();
UpdateRequestHandler handler = new UpdateRequestHandler(); try (SolrQueryRequest req = req(); UpdateRequestHandler handler = new UpdateRequestHandler()) {
handler.init(new NamedList()); handler.init(new NamedList());
SolrQueryRequest req = req();
ContentStreamLoader csl = handler.newLoader(req, p); ContentStreamLoader csl = handler.newLoader(req, p);
RequestWriter.ContentWriter cw = brw.getContentWriter(ureq); RequestWriter.ContentWriter cw = brw.getContentWriter(ureq);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
cw.write(baos); cw.write(baos);
@ -67,7 +65,6 @@ public class BinaryUpdateRequestHandlerTest extends SolrTestCaseJ4 {
System.out.println(add.solrDoc); System.out.println(add.solrDoc);
assertEquals(false, add.overwrite); assertEquals(false, add.overwrite);
assertEquals(100, add.commitWithin); assertEquals(100, add.commitWithin);
}
req.close();
} }
} }

View File

@ -43,7 +43,6 @@ public class MoreLikeThisHandlerTest extends SolrTestCaseJ4 {
public void testInterface() throws Exception public void testInterface() throws Exception
{ {
SolrCore core = h.getCore(); SolrCore core = h.getCore();
MoreLikeThisHandler mlt = new MoreLikeThisHandler();
ModifiableSolrParams params = new ModifiableSolrParams(); ModifiableSolrParams params = new ModifiableSolrParams();
@ -63,7 +62,8 @@ public class MoreLikeThisHandlerTest extends SolrTestCaseJ4 {
// requires 'q' or a single content stream // requires 'q' or a single content stream
SolrException ex = expectThrows(SolrException.class, () -> { SolrException ex = expectThrows(SolrException.class, () -> {
try (SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) { try (MoreLikeThisHandler mlt = new MoreLikeThisHandler();
SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) {
mlt.handleRequestBody(req, new SolrQueryResponse()); mlt.handleRequestBody(req, new SolrQueryResponse());
} }
}); });
@ -72,7 +72,8 @@ public class MoreLikeThisHandlerTest extends SolrTestCaseJ4 {
// requires a single content stream (more than one is not supported). // requires a single content stream (more than one is not supported).
ex = expectThrows(SolrException.class, () -> { ex = expectThrows(SolrException.class, () -> {
try (SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) { try (MoreLikeThisHandler mlt = new MoreLikeThisHandler();
SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) {
ArrayList<ContentStream> streams = new ArrayList<>(2); ArrayList<ContentStream> streams = new ArrayList<>(2);
streams.add(new ContentStreamBase.StringStream("hello")); streams.add(new ContentStreamBase.StringStream("hello"));
streams.add(new ContentStreamBase.StringStream("there")); streams.add(new ContentStreamBase.StringStream("there"));
@ -153,8 +154,6 @@ public class MoreLikeThisHandlerTest extends SolrTestCaseJ4 {
public void testMultifieldSimilarity() throws Exception public void testMultifieldSimilarity() throws Exception
{ {
SolrCore core = h.getCore(); SolrCore core = h.getCore();
MoreLikeThisHandler mlt = new MoreLikeThisHandler();
ModifiableSolrParams params = new ModifiableSolrParams(); ModifiableSolrParams params = new ModifiableSolrParams();
assertU(adoc("id", "1", "name", "aaa bbb ccc", "subword", " zzz")); assertU(adoc("id", "1", "name", "aaa bbb ccc", "subword", " zzz"));

View File

@ -63,7 +63,7 @@ public class TestCoreBackup extends SolrTestCaseJ4 {
String snapshotName = TestUtil.randomSimpleString(random(), 1, 5); String snapshotName = TestUtil.randomSimpleString(random(), 1, 5);
final CoreContainer cores = h.getCoreContainer(); final CoreContainer cores = h.getCoreContainer();
final CoreAdminHandler admin = new CoreAdminHandler(cores); try (final CoreAdminHandler admin = new CoreAdminHandler(cores)) {
SolrQueryResponse resp = new SolrQueryResponse(); SolrQueryResponse resp = new SolrQueryResponse();
admin.handleRequestBody admin.handleRequestBody
(req(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.BACKUPCORE.toString(), (req(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.BACKUPCORE.toString(),
@ -72,6 +72,7 @@ public class TestCoreBackup extends SolrTestCaseJ4 {
assertNull("Backup should have succeeded", resp.getException()); assertNull("Backup should have succeeded", resp.getException());
simpleBackupCheck(new File(location, "snapshot." + snapshotName), 2); simpleBackupCheck(new File(location, "snapshot." + snapshotName), 2);
} }
}
public void testBackupBeforeFirstCommit() throws Exception { public void testBackupBeforeFirstCommit() throws Exception {
@ -169,6 +170,7 @@ public class TestCoreBackup extends SolrTestCaseJ4 {
0, initialEmptyIndexSegmentFileName); 0, initialEmptyIndexSegmentFileName);
} }
admin.close();
} }
/** /**
@ -291,7 +293,7 @@ public class TestCoreBackup extends SolrTestCaseJ4 {
1, oneDocSegmentFile); 1, oneDocSegmentFile);
} }
admin.close();
} }
/** /**

View File

@ -77,9 +77,10 @@ public class XsltUpdateRequestHandlerTest extends SolrTestCaseJ4 {
streams.add(new ContentStreamBase.StringStream(xml)); streams.add(new ContentStreamBase.StringStream(xml));
req.setContentStreams(streams); req.setContentStreams(streams);
SolrQueryResponse rsp = new SolrQueryResponse(); SolrQueryResponse rsp = new SolrQueryResponse();
UpdateRequestHandler handler = new UpdateRequestHandler(); try (UpdateRequestHandler handler = new UpdateRequestHandler()) {
handler.init(new NamedList<String>()); handler.init(new NamedList<String>());
handler.handleRequestBody(req, rsp); handler.handleRequestBody(req, rsp);
}
StringWriter sw = new StringWriter(32000); StringWriter sw = new StringWriter(32000);
QueryResponseWriter responseWriter = core.getQueryResponseWriter(req); QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
responseWriter.write(sw,req,rsp); responseWriter.write(sw,req,rsp);

View File

@ -117,6 +117,7 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
// Should have segments in the directory pointed to by the ${DATA_TEST}. // Should have segments in the directory pointed to by the ${DATA_TEST}.
File test = new File(dataDir, "index"); File test = new File(dataDir, "index");
assertTrue("Should have found index dir at " + test.getAbsolutePath(), test.exists()); assertTrue("Should have found index dir at " + test.getAbsolutePath(), test.exists());
admin.close();
} }
@Test @Test
@ -243,7 +244,7 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
assertNotNull("Core should have been renamed!", cd); assertNotNull("Core should have been renamed!", cd);
// :TODO: because of SOLR-3665 we can't ask for status from all cores // :TODO: because of SOLR-3665 we can't ask for status from all cores
admin.close();
} }
@Test @Test
@ -417,5 +418,6 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
, resp); , resp);
}); });
assertEquals("Expected error message for non-existent core.", "Missing required parameter: core", e.getMessage()); assertEquals("Expected error message for non-existent core.", "Missing required parameter: core", e.getMessage());
admin.close();
} }
} }

View File

@ -97,6 +97,7 @@ public class CoreAdminRequestStatusTest extends SolrTestCaseJ4{
"notfound", resp.getValues().get("STATUS")); "notfound", resp.getValues().get("STATUS"));
admin.shutdown(); admin.shutdown();
admin.close();
} }
} }

View File

@ -75,9 +75,8 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {
final CoreContainer cores = h.getCoreContainer(); final CoreContainer cores = h.getCoreContainer();
final CoreAdminHandler admin = new CoreAdminHandler(cores); try (final CoreAdminHandler admin = new CoreAdminHandler(cores);
SolrCore core = cores.getCore("collection1")) {
try (SolrCore core = cores.getCore("collection1")) {
DirectoryFactory df = core.getDirectoryFactory(); DirectoryFactory df = core.getDirectoryFactory();
FailingDirectoryFactory dirFactory = (FailingDirectoryFactory) df; FailingDirectoryFactory dirFactory = (FailingDirectoryFactory) df;

View File

@ -193,5 +193,6 @@ public class MBeansHandlerTest extends SolrTestCaseJ4 {
reader.start(); reader.start();
counter.await(30, TimeUnit.SECONDS); counter.await(30, TimeUnit.SECONDS);
runSnapshots = false; runSnapshots = false;
bean.close();
} }
} }

View File

@ -198,6 +198,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {
assertNotNull(values.get("metrics")); assertNotNull(values.get("metrics"));
SimpleOrderedMap map = (SimpleOrderedMap) values.get("metrics"); SimpleOrderedMap map = (SimpleOrderedMap) values.get("metrics");
assertEquals(0, map.size()); assertEquals(0, map.size());
handler.close();
} }
@Test @Test
@ -214,6 +215,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {
Object o = nl.get("SEARCHER.new.errors"); Object o = nl.get("SEARCHER.new.errors");
assertNotNull(o); // counter type assertNotNull(o); // counter type
assertTrue(o instanceof Number); assertTrue(o instanceof Number);
handler.close();
} }
@Test @Test
@ -253,6 +255,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {
assertNotNull(map.get("inserts")); assertNotNull(map.get("inserts"));
assertNotNull(map.get("size")); assertNotNull(map.get("size"));
}); });
handler.close();
} }
@Test @Test
@ -338,6 +341,8 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {
metrics = (NamedList) values.get("metrics"); metrics = (NamedList) values.get("metrics");
assertEquals(0, metrics.size()); assertEquals(0, metrics.size());
assertNotNull(values.findRecursive("errors", "solr.jetty:unknown:baz")); assertNotNull(values.findRecursive("errors", "solr.jetty:unknown:baz"));
handler.close();
} }
@Test @Test

View File

@ -175,6 +175,7 @@ public class SecurityConfHandlerTest extends SolrTestCaseJ4 {
handler.handleRequestBody(req, rsp); handler.handleRequestBody(req, rsp);
List l = (List) ((Map) ((List)rsp.getValues().get("errorMessages")).get(0)).get("errorMessages"); List l = (List) ((Map) ((List)rsp.getValues().get("errorMessages")).get(0)).get("errorMessages");
assertEquals(1, l.size()); assertEquals(1, l.size());
handler.close();
} }
@ -266,7 +267,9 @@ public class SecurityConfHandlerTest extends SolrTestCaseJ4 {
public static void main(String[] args) throws Exception{ public static void main(String[] args) throws Exception{
System.out.println(new MockSecurityHandler().getStandardJson()); try (MockSecurityHandler msh = new MockSecurityHandler()) {
System.out.println(msh.getStandardJson());
}
} }

View File

@ -79,10 +79,12 @@ public class TestCollectionAPIs extends SolrTestCaseJ4 {
} }
public void testCommands() throws Exception { public void testCommands() throws Exception {
MockCollectionsHandler collectionsHandler = new MockCollectionsHandler(); ApiBag apiBag;
ApiBag apiBag = new ApiBag(false); try (MockCollectionsHandler collectionsHandler = new MockCollectionsHandler()) {
apiBag = new ApiBag(false);
Collection<Api> apis = collectionsHandler.getApis(); Collection<Api> apis = collectionsHandler.getApis();
for (Api api : apis) apiBag.register(api, Collections.emptyMap()); for (Api api : apis) apiBag.register(api, Collections.emptyMap());
}
//test a simple create collection call //test a simple create collection call
compareOutput(apiBag, "/collections", POST, compareOutput(apiBag, "/collections", POST,
"{create:{name:'newcoll', config:'schemaless', numShards:2, replicationFactor:2 }}", null, "{create:{name:'newcoll', config:'schemaless', numShards:2, replicationFactor:2 }}", null,

View File

@ -38,7 +38,7 @@ public class TestConfigsApi extends SolrTestCaseJ4 {
public void testCommands() throws Exception { public void testCommands() throws Exception {
ConfigSetsHandler handler = new ConfigSetsHandler(null) { try (ConfigSetsHandler handler = new ConfigSetsHandler(null) {
@Override @Override
protected void sendToZk(SolrQueryResponse rsp, protected void sendToZk(SolrQueryResponse rsp,
ConfigSetOperation operation, ConfigSetOperation operation,
@ -47,7 +47,7 @@ public class TestConfigsApi extends SolrTestCaseJ4 {
result.put(QUEUE_OPERATION, operation.action.toLower()); result.put(QUEUE_OPERATION, operation.action.toLower());
rsp.add(ZkNodeProps.class.getName(), new ZkNodeProps(result)); rsp.add(ZkNodeProps.class.getName(), new ZkNodeProps(result));
} }
}; }) {
ApiBag apiBag = new ApiBag(false); ApiBag apiBag = new ApiBag(false);
for (Api api : handler.getApis()) apiBag.register(api, EMPTY_MAP); for (Api api : handler.getApis()) apiBag.register(api, EMPTY_MAP);
compareOutput(apiBag, "/cluster/configs/sample", DELETE, null, null, compareOutput(apiBag, "/cluster/configs/sample", DELETE, null, null,
@ -57,3 +57,4 @@ public class TestConfigsApi extends SolrTestCaseJ4 {
"{operation:create, name :newconf, baseConfigSet: sample, immutable: false }"); "{operation:create, name :newconf, baseConfigSet: sample, immutable: false }");
} }
} }
}

View File

@ -39,11 +39,13 @@ public class TestCoreAdminApis extends SolrTestCaseJ4 {
Map<String, Object[]> calls = new HashMap<>(); Map<String, Object[]> calls = new HashMap<>();
CoreContainer mockCC = getCoreContainerMock(calls, new HashMap<>()); CoreContainer mockCC = getCoreContainerMock(calls, new HashMap<>());
CoreAdminHandler coreAdminHandler = new CoreAdminHandler(mockCC); ApiBag apiBag;
ApiBag apiBag = new ApiBag(false); try (CoreAdminHandler coreAdminHandler = new CoreAdminHandler(mockCC)) {
apiBag = new ApiBag(false);
for (Api api : coreAdminHandler.getApis()) { for (Api api : coreAdminHandler.getApis()) {
apiBag.register(api, Collections.EMPTY_MAP); apiBag.register(api, Collections.EMPTY_MAP);
} }
}
TestCollectionAPIs.makeCall(apiBag, "/cores", SolrRequest.METHOD.POST, TestCollectionAPIs.makeCall(apiBag, "/cores", SolrRequest.METHOD.POST,
"{create:{name: hello, instanceDir : someDir, schema: 'schema.xml'}}", mockCC); "{create:{name: hello, instanceDir : someDir, schema: 'schema.xml'}}", mockCC);
Object[] params = calls.get("create"); Object[] params = calls.get("create");

View File

@ -157,13 +157,21 @@ public class ZookeeperStatusHandlerTest extends SolrCloudTestCase {
@Test(expected = SolrException.class) @Test(expected = SolrException.class)
public void validateNotWhitelisted() { public void validateNotWhitelisted() {
new ZookeeperStatusHandler(null).validateZkRawResponse(Collections.singletonList("mntr is not executed because it is not in the whitelist."), try (ZookeeperStatusHandler zsh = new ZookeeperStatusHandler(null)) {
zsh.validateZkRawResponse(Collections.singletonList("mntr is not executed because it is not in the whitelist."),
"zoo1:2181", "mntr"); "zoo1:2181", "mntr");
} catch (IOException e) {
fail("Error closing ZookeeperStatusHandler");
}
} }
@Test(expected = SolrException.class) @Test(expected = SolrException.class)
public void validateEmptyResponse() { public void validateEmptyResponse() {
new ZookeeperStatusHandler(null).validateZkRawResponse(Collections.emptyList(), "zoo1:2181", "mntr"); try (ZookeeperStatusHandler zsh = new ZookeeperStatusHandler(null)) {
zsh.validateZkRawResponse(Collections.emptyList(), "zoo1:2181", "mntr");
} catch (IOException e) {
fail("Error closing ZookeeperStatusHandler");
}
} }
@Test @Test

View File

@ -384,14 +384,16 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {
args.add(QueryElevationComponent.FIELD_TYPE, "string"); args.add(QueryElevationComponent.FIELD_TYPE, "string");
args.add(QueryElevationComponent.CONFIG_FILE, "elevate.xml"); args.add(QueryElevationComponent.CONFIG_FILE, "elevate.xml");
QueryElevationComponent comp = new QueryElevationComponent(); IndexReader reader;
try (SolrQueryRequest req = req()) {
reader = req.getSearcher().getIndexReader();
}
try (QueryElevationComponent comp = new QueryElevationComponent()) {
comp.init(args); comp.init(args);
comp.inform(core); comp.inform(core);
SolrQueryRequest req = req();
IndexReader reader = req.getSearcher().getIndexReader();
QueryElevationComponent.ElevationProvider elevationProvider = comp.getElevationProvider(reader, core); QueryElevationComponent.ElevationProvider elevationProvider = comp.getElevationProvider(reader, core);
req.close();
// Make sure the boosts loaded properly // Make sure the boosts loaded properly
assertEquals(11, elevationProvider.size()); assertEquals(11, elevationProvider.size());
@ -401,16 +403,17 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {
assertNull(elevationProvider.getElevationForQuery("xxxx")); assertNull(elevationProvider.getElevationForQuery("xxxx"));
assertNull(elevationProvider.getElevationForQuery("yyyy")); assertNull(elevationProvider.getElevationForQuery("yyyy"));
assertNull(elevationProvider.getElevationForQuery("zzzz")); assertNull(elevationProvider.getElevationForQuery("zzzz"));
}
// Now test the same thing with a lowercase filter: 'lowerfilt' // Now test the same thing with a lowercase filter: 'lowerfilt'
args = new NamedList<>(); args = new NamedList<>();
args.add(QueryElevationComponent.FIELD_TYPE, "lowerfilt"); args.add(QueryElevationComponent.FIELD_TYPE, "lowerfilt");
args.add(QueryElevationComponent.CONFIG_FILE, "elevate.xml"); args.add(QueryElevationComponent.CONFIG_FILE, "elevate.xml");
comp = new QueryElevationComponent(); try (QueryElevationComponent comp = new QueryElevationComponent()) {
comp.init(args); comp.init(args);
comp.inform(core); comp.inform(core);
elevationProvider = comp.getElevationProvider(reader, core); QueryElevationComponent.ElevationProvider elevationProvider = comp.getElevationProvider(reader, core);
assertEquals(11, elevationProvider.size()); assertEquals(11, elevationProvider.size());
assertEquals(1, elevationProvider.getElevationForQuery("XXXX").elevatedIds.size()); assertEquals(1, elevationProvider.getElevationForQuery("XXXX").elevatedIds.size());
assertEquals(2, elevationProvider.getElevationForQuery("YYYY").elevatedIds.size()); assertEquals(2, elevationProvider.getElevationForQuery("YYYY").elevatedIds.size());
@ -424,6 +427,7 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {
assertQ("Make sure QEC handles null queries", req("qt", "/elevate", "q.alt", "*:*", "defType", "dismax"), assertQ("Make sure QEC handles null queries", req("qt", "/elevate", "q.alt", "*:*", "defType", "dismax"),
"//*[@numFound='0']"); "//*[@numFound='0']");
}
} finally { } finally {
delete(); delete();
} }
@ -903,7 +907,7 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {
@Test @Test
public void testElevatedIds() throws Exception { public void testElevatedIds() throws Exception {
try { try (QueryElevationComponent comp = new QueryElevationComponent()) {
init("schema12.xml"); init("schema12.xml");
SolrCore core = h.getCore(); SolrCore core = h.getCore();
@ -911,7 +915,6 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {
args.add(QueryElevationComponent.FIELD_TYPE, "text"); args.add(QueryElevationComponent.FIELD_TYPE, "text");
args.add(QueryElevationComponent.CONFIG_FILE, "elevate.xml"); args.add(QueryElevationComponent.CONFIG_FILE, "elevate.xml");
QueryElevationComponent comp = new QueryElevationComponent();
comp.init(args); comp.init(args);
comp.inform(core); comp.inform(core);

View File

@ -16,6 +16,7 @@
*/ */
package org.apache.solr.handler.component; package org.apache.solr.handler.component;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
@ -45,8 +46,6 @@ public class SearchHandlerTest extends SolrTestCaseJ4
initCore("solrconfig.xml","schema.xml"); initCore("solrconfig.xml","schema.xml");
} }
@SuppressWarnings("unchecked")
@Test @Test
public void testInitialization() public void testInitialization()
{ {
@ -57,15 +56,18 @@ public class SearchHandlerTest extends SolrTestCaseJ4
List<String> names0 = new ArrayList<>(); List<String> names0 = new ArrayList<>();
names0.add( MoreLikeThisComponent.COMPONENT_NAME ); names0.add( MoreLikeThisComponent.COMPONENT_NAME );
NamedList args = new NamedList(); NamedList<List<String>> args = new NamedList<>();
args.add( SearchHandler.INIT_COMPONENTS, names0 ); args.add( SearchHandler.INIT_COMPONENTS, names0 );
SearchHandler handler = new SearchHandler(); try (SearchHandler handler = new SearchHandler()) {
handler.init(args); handler.init(args);
handler.inform(core); handler.inform(core);
assertEquals(1, handler.getComponents().size()); assertEquals(1, handler.getComponents().size());
assertEquals(core.getSearchComponent(MoreLikeThisComponent.COMPONENT_NAME), assertEquals(core.getSearchComponent(MoreLikeThisComponent.COMPONENT_NAME),
handler.getComponents().get(0)); handler.getComponents().get(0));
} catch (IOException e) {
fail("IOExcepiton closing SearchHandler");
}
// Build an explicit list that includes the debug comp. // Build an explicit list that includes the debug comp.
//----------------------------------------------- //-----------------------------------------------
@ -74,9 +76,9 @@ public class SearchHandlerTest extends SolrTestCaseJ4
names0.add( DebugComponent.COMPONENT_NAME ); names0.add( DebugComponent.COMPONENT_NAME );
names0.add( MoreLikeThisComponent.COMPONENT_NAME ); names0.add( MoreLikeThisComponent.COMPONENT_NAME );
args = new NamedList(); args = new NamedList<>();
args.add( SearchHandler.INIT_COMPONENTS, names0 ); args.add( SearchHandler.INIT_COMPONENTS, names0 );
handler = new SearchHandler(); try (SearchHandler handler = new SearchHandler()) {
handler.init(args); handler.init(args);
handler.inform(core); handler.inform(core);
@ -87,6 +89,9 @@ public class SearchHandlerTest extends SolrTestCaseJ4
handler.getComponents().get(1)); handler.getComponents().get(1));
assertEquals(core.getSearchComponent(MoreLikeThisComponent.COMPONENT_NAME), assertEquals(core.getSearchComponent(MoreLikeThisComponent.COMPONENT_NAME),
handler.getComponents().get(2)); handler.getComponents().get(2));
} catch (IOException e) {
fail("Exception when closing SearchHandler");
}
// First/Last list // First/Last list
@ -97,10 +102,10 @@ public class SearchHandlerTest extends SolrTestCaseJ4
List<String> names1 = new ArrayList<>(); List<String> names1 = new ArrayList<>();
names1.add( FacetComponent.COMPONENT_NAME ); names1.add( FacetComponent.COMPONENT_NAME );
args = new NamedList(); args = new NamedList<>();
args.add( SearchHandler.INIT_FIRST_COMPONENTS, names0 ); args.add( SearchHandler.INIT_FIRST_COMPONENTS, names0 );
args.add( SearchHandler.INIT_LAST_COMPONENTS, names1 ); args.add( SearchHandler.INIT_LAST_COMPONENTS, names1 );
handler = new SearchHandler(); try (SearchHandler handler = new SearchHandler()) {
handler.init(args); handler.init(args);
handler.inform(core); handler.inform(core);
@ -110,6 +115,9 @@ public class SearchHandlerTest extends SolrTestCaseJ4
assertEquals(core.getSearchComponent(FacetComponent.COMPONENT_NAME), comps.get(comps.size() - 2)); assertEquals(core.getSearchComponent(FacetComponent.COMPONENT_NAME), comps.get(comps.size() - 2));
//Debug component is always last in this case //Debug component is always last in this case
assertEquals(core.getSearchComponent(DebugComponent.COMPONENT_NAME), comps.get(comps.size() - 1)); assertEquals(core.getSearchComponent(DebugComponent.COMPONENT_NAME), comps.get(comps.size() - 1));
} catch (IOException e) {
fail("Exception when closing SearchHandler");
}
} }
@Test @Test

View File

@ -282,6 +282,7 @@ public class SpellCheckComponentTest extends SolrTestCaseJ4 {
} }
rb.req.close(); rb.req.close();
checker.close();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -405,8 +405,6 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
args.put(StatsParams.STATS_FIELD, f); args.put(StatsParams.STATS_FIELD, f);
args.put("f." + f +".stats.calcdistinct","true"); args.put("f." + f +".stats.calcdistinct","true");
args.put("indent", "true"); args.put("indent", "true");
SolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args));
for (SolrParams baseParams : new SolrParams[] { for (SolrParams baseParams : new SolrParams[] {
params("stats.field", f, "stats", "true", "f." + f +".stats.calcdistinct","true"), params("stats.field", f, "stats", "true", "f." + f +".stats.calcdistinct","true"),

View File

@ -16,6 +16,7 @@
*/ */
package org.apache.solr.handler.component; package org.apache.solr.handler.component;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -154,10 +155,14 @@ public class TermsComponentTest extends SolrTestCaseJ4 {
ModifiableSolrParams params = new ModifiableSolrParams(); ModifiableSolrParams params = new ModifiableSolrParams();
params.add(TermsParams.TERMS_REGEXP_FLAG, "case_insensitive", "literal", "comments", "multiline", "unix_lines", params.add(TermsParams.TERMS_REGEXP_FLAG, "case_insensitive", "literal", "comments", "multiline", "unix_lines",
"unicode_case", "dotall", "canon_eq"); "unicode_case", "dotall", "canon_eq");
int flags = new TermsComponent().resolveRegexpFlags(params); try (TermsComponent termsComponent = new TermsComponent()) {
int flags = termsComponent.resolveRegexpFlags(params);
int expected = Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.COMMENTS | Pattern.MULTILINE | Pattern.UNIX_LINES int expected = Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.COMMENTS | Pattern.MULTILINE | Pattern.UNIX_LINES
| Pattern.UNICODE_CASE | Pattern.DOTALL | Pattern.CANON_EQ; | Pattern.UNICODE_CASE | Pattern.DOTALL | Pattern.CANON_EQ;
assertEquals(expected, flags); assertEquals(expected, flags);
} catch (IOException e) {
fail("Error closing TermsComponent");
}
} }
@Test @Test

View File

@ -79,6 +79,7 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {
// test that factory is HttpShardHandlerFactory with expected url reserve fraction // test that factory is HttpShardHandlerFactory with expected url reserve fraction
assertTrue(factory instanceof HttpShardHandlerFactory); assertTrue(factory instanceof HttpShardHandlerFactory);
@SuppressWarnings("resource")
final HttpShardHandlerFactory httpShardHandlerFactory = ((HttpShardHandlerFactory)factory); final HttpShardHandlerFactory httpShardHandlerFactory = ((HttpShardHandlerFactory)factory);
assertEquals(expectedLoadBalancerRequestsMinimumAbsolute, httpShardHandlerFactory.permittedLoadBalancerRequestsMinimumAbsolute, 0.0); assertEquals(expectedLoadBalancerRequestsMinimumAbsolute, httpShardHandlerFactory.permittedLoadBalancerRequestsMinimumAbsolute, 0.0);
assertEquals(expectedLoadBalancerRequestsMaximumFraction, httpShardHandlerFactory.permittedLoadBalancerRequestsMaximumFraction, 0.0); assertEquals(expectedLoadBalancerRequestsMaximumFraction, httpShardHandlerFactory.permittedLoadBalancerRequestsMaximumFraction, 0.0);
@ -122,6 +123,7 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {
cc = CoreContainer.createAndLoad(home, home.resolve("solr.xml")); cc = CoreContainer.createAndLoad(home, home.resolve("solr.xml"));
factory = cc.getShardHandlerFactory(); factory = cc.getShardHandlerFactory();
assertTrue(factory instanceof HttpShardHandlerFactory); assertTrue(factory instanceof HttpShardHandlerFactory);
@SuppressWarnings("resource")
final HttpShardHandlerFactory httpShardHandlerFactory = ((HttpShardHandlerFactory)factory); final HttpShardHandlerFactory httpShardHandlerFactory = ((HttpShardHandlerFactory)factory);
assertThat(httpShardHandlerFactory.getWhitelistHostChecker().getWhitelistHosts().size(), is(2)); assertThat(httpShardHandlerFactory.getWhitelistHostChecker().getWhitelistHosts().size(), is(2));
assertThat(httpShardHandlerFactory.getWhitelistHostChecker().getWhitelistHosts(), hasItem("abc:8983")); assertThat(httpShardHandlerFactory.getWhitelistHostChecker().getWhitelistHosts(), hasItem("abc:8983"));

View File

@ -61,6 +61,7 @@ public class TestTrackingShardHandlerFactory extends AbstractFullDistribZkTestBa
CoreContainer container = runner.getCoreContainer(); CoreContainer container = runner.getCoreContainer();
ShardHandlerFactory factory = container.getShardHandlerFactory(); ShardHandlerFactory factory = container.getShardHandlerFactory();
assert factory instanceof TrackingShardHandlerFactory; assert factory instanceof TrackingShardHandlerFactory;
@SuppressWarnings("resource")
TrackingShardHandlerFactory trackingShardHandlerFactory = (TrackingShardHandlerFactory) factory; TrackingShardHandlerFactory trackingShardHandlerFactory = (TrackingShardHandlerFactory) factory;
assertSame(trackingQueue, trackingShardHandlerFactory.getTrackingQueue()); assertSame(trackingQueue, trackingShardHandlerFactory.getTrackingQueue());
} }
@ -116,6 +117,7 @@ public class TestTrackingShardHandlerFactory extends AbstractFullDistribZkTestBa
CoreContainer container = runner.getCoreContainer(); CoreContainer container = runner.getCoreContainer();
ShardHandlerFactory factory = container.getShardHandlerFactory(); ShardHandlerFactory factory = container.getShardHandlerFactory();
assert factory instanceof TrackingShardHandlerFactory; assert factory instanceof TrackingShardHandlerFactory;
@SuppressWarnings("resource")
TrackingShardHandlerFactory trackingShardHandlerFactory = (TrackingShardHandlerFactory) factory; TrackingShardHandlerFactory trackingShardHandlerFactory = (TrackingShardHandlerFactory) factory;
assertFalse(trackingShardHandlerFactory.isTracking()); assertFalse(trackingShardHandlerFactory.isTracking());
} }

View File

@ -218,6 +218,7 @@ public class TrackingShardHandlerFactory extends HttpShardHandlerFactory {
ShardHandlerFactory factory = container.getShardHandlerFactory(); ShardHandlerFactory factory = container.getShardHandlerFactory();
assert factory instanceof TrackingShardHandlerFactory : "not a TrackingShardHandlerFactory: " assert factory instanceof TrackingShardHandlerFactory : "not a TrackingShardHandlerFactory: "
+ factory.getClass(); + factory.getClass();
@SuppressWarnings("resource")
TrackingShardHandlerFactory trackingShardHandlerFactory = (TrackingShardHandlerFactory) factory; TrackingShardHandlerFactory trackingShardHandlerFactory = (TrackingShardHandlerFactory) factory;
trackingShardHandlerFactory.setTrackingQueue(queue); trackingShardHandlerFactory.setTrackingQueue(queue);
} }