Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix compiler warnings in :server - part 3 #76024

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public SearchAfterSortedDocQuery(Sort sort, FieldDoc after) {
this.sort = Objects.requireNonNull(sort);
this.after = after;
int numFields = sort.getSort().length;
this.fieldComparators = new FieldComparator[numFields];
this.fieldComparators = new FieldComparator<?>[numFields];
this.reverseMuls = new int[numFields];
for (int i = 0; i < numFields; i++) {
SortField sortField = sort.getSort()[i];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,23 @@
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.SearchSortValuesAndFormats;

import static org.elasticsearch.core.Types.forciblyCast;

/**
* Utility class to keep track of the bottom doc's sort values in a distributed search.
*/
class BottomSortValuesCollector {
private final int topNSize;
private final SortField[] sortFields;
private final FieldComparator[] comparators;
private final FieldComparator<?>[] comparators;
private final int[] reverseMuls;

private volatile long totalHits;
private volatile SearchSortValuesAndFormats bottomSortValues;

BottomSortValuesCollector(int topNSize, SortField[] sortFields) {
this.topNSize = topNSize;
this.comparators = new FieldComparator[sortFields.length];
this.comparators = new FieldComparator<?>[sortFields.length];
this.reverseMuls = new int[sortFields.length];
this.sortFields = sortFields;
for (int i = 0; i < sortFields.length; i++) {
Expand Down Expand Up @@ -90,7 +92,7 @@ private FieldDoc extractBottom(TopFieldDocs topDocs) {

private int compareValues(Object[] v1, Object[] v2) {
for (int i = 0; i < v1.length; i++) {
int cmp = reverseMuls[i] * comparators[i].compareValues(v1[i], v2[i]);
int cmp = reverseMuls[i] * comparators[i].compareValues(forciblyCast(v1[i]), forciblyCast(v2[i]));
if (cmp != 0) {
return cmp;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static org.elasticsearch.core.Types.forciblyCast;

/**
* This search phase can be used as an initial search phase to pre-filter search shards based on query rewriting.
* The queries are rewritten against the shards and based on the rewrite result shards might be able to be excluded
Expand Down Expand Up @@ -185,7 +187,11 @@ private static boolean shouldSortShards(MinAndMax<?>[] minAndMaxes) {
private static Comparator<Integer> shardComparator(GroupShardsIterator<SearchShardIterator> shardsIts,
MinAndMax<?>[] minAndMaxes,
SortOrder order) {
final Comparator<Integer> comparator = Comparator.comparing(index -> minAndMaxes[index], MinAndMax.getComparator(order));
final Comparator<Integer> comparator = Comparator.comparing(
index -> minAndMaxes[index],
forciblyCast(MinAndMax.getComparator(order))
);

return comparator.thenComparing(index -> shardsIts.get(index));
}

Expand All @@ -197,7 +203,7 @@ private static final class CanMatchSearchPhaseResults extends SearchPhaseResults
CanMatchSearchPhaseResults(int size) {
super(size);
possibleMatches = new FixedBitSet(size);
minAndMaxes = new MinAndMax[size];
minAndMaxes = new MinAndMax<?>[size];
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public TransportBroadcastByNodeAction(

private Response newResponse(
Request request,
AtomicReferenceArray responses,
AtomicReferenceArray<?> responses,
List<NoShardAvailableActionException> unavailableShardExceptions,
Map<String, List<ShardRouting>> nodes,
ClusterState clusterState) {
Expand All @@ -126,6 +126,7 @@ private Response newResponse(
exceptions.add(new DefaultShardOperationFailedException(shard.getIndexName(), shard.getId(), exception));
}
} else {
@SuppressWarnings("unchecked")
NodeResponse response = (NodeResponse) responses.get(i);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does forciblyCast not work here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well it would, but I don't really like using it - I feel like the annotation draws attention more than a function call, even with its name, and I'd prefer the engineers to want to make such cast unnecessary wherever possible.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should have some clear guidance here then on when one is preferable over the other. As it is, it doesn't seem obvious to me. My intention behind adding that method was to eliminate the need for this suppressions all over the case when there's no alternative to casting.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added something to CONTRIBUTING.md, see what you think.

broadcastByNodeResponses.addAll(response.results);
totalShards += response.getTotalShards();
Expand Down Expand Up @@ -401,7 +402,7 @@ public void messageReceived(final NodeRequest request, TransportChannel channel,
if (logger.isTraceEnabled()) {
logger.trace("[{}] executing operation on [{}] shards", actionName, totalShards);
}
final AtomicArray<Object> shardResultOrExceptions = new AtomicArray(totalShards);
final AtomicArray<Object> shardResultOrExceptions = new AtomicArray<>(totalShards);

final AtomicInteger counter = new AtomicInteger(shards.size());
int shardIndex = -1;
Expand Down Expand Up @@ -430,6 +431,7 @@ public void onFailure(Exception e) {
}
}

@SuppressWarnings("unchecked")
private void finishHim(NodeRequest request, TransportChannel channel, Task task,
AtomicArray<Object> shardResultOrExceptions) {
if (task instanceof CancellableTask) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ protected List<ShardId> shards(Request request, ClusterState clusterState) {

protected abstract ShardRequest newShardRequest(Request request, ShardId shardId);

private void finishAndNotifyListener(ActionListener listener, CopyOnWriteArrayList<ShardResponse> shardsResponses) {
private void finishAndNotifyListener(ActionListener<Response> listener, CopyOnWriteArrayList<ShardResponse> shardsResponses) {
logger.trace("{}: got all shard responses", actionName);
int successfulShards = 0;
int failedShards = 0;
Expand All @@ -159,6 +159,6 @@ private void finishAndNotifyListener(ActionListener listener, CopyOnWriteArrayLi
listener.onResponse(newResponse(successfulShards, failedShards, totalNumCopies, shardFailures));
}

protected abstract BroadcastResponse newResponse(int successfulShards, int failedShards, int totalNumCopies,
protected abstract Response newResponse(int successfulShards, int failedShards, int totalNumCopies,
List<DefaultShardOperationFailedException> shardFailures);
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public SortedSetDocValues ordinals(ValuesHolder values) {
if (multiValued) {
return new MultiDocs(this, values);
} else {
return (SortedSetDocValues) DocValues.singleton(new SingleDocs(this, values));
return DocValues.singleton(new SingleDocs(this, values));
mark-vieira marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public Collection<Accountable> getChildResources() {

@Override
public SortedSetDocValues ordinals(ValuesHolder values) {
return (SortedSetDocValues) DocValues.singleton(new Docs(this, values));
return DocValues.singleton(new Docs(this, values));
}

private static class Docs extends AbstractSortedDocValues {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ protected AbstractGeometryQueryBuilder(String fieldName, Supplier<Geometry> supp
this.fieldName = fieldName;
this.shape = null;
this.supplier = supplier;
this.indexedShapeId = indexedShapeId;;
this.indexedShapeId = indexedShapeId;
}

/**
Expand Down Expand Up @@ -190,6 +190,7 @@ public String fieldName() {
* @param geometry the geometry
* @return this
*/
@SuppressWarnings("unchecked")
public QB shape(Geometry geometry) {
if (geometry == null) {
throw new IllegalArgumentException("No geometry defined");
Expand Down Expand Up @@ -218,6 +219,7 @@ public String indexedShapeId() {
* @param indexedShapeIndex Name of the index where the indexed Shape is
* @return this
*/
@SuppressWarnings("unchecked")
public QB indexedShapeIndex(String indexedShapeIndex) {
this.indexedShapeIndex = indexedShapeIndex;
return (QB)this;
Expand All @@ -237,6 +239,7 @@ public String indexedShapeIndex() {
* @param indexedShapePath Path of the field where the Shape itself is defined
* @return this
*/
@SuppressWarnings("unchecked")
public QB indexedShapePath(String indexedShapePath) {
this.indexedShapePath = indexedShapePath;
return (QB)this;
Expand All @@ -255,6 +258,7 @@ public String indexedShapePath() {
* @param indexedShapeRouting indexed shape routing
* @return this
*/
@SuppressWarnings("unchecked")
public QB indexedShapeRouting(String indexedShapeRouting) {
this.indexedShapeRouting = indexedShapeRouting;
return (QB)this;
Expand All @@ -275,6 +279,7 @@ public String indexedShapeRouting() {
* @param relation relation of the shapes
* @return this
*/
@SuppressWarnings("unchecked")
public QB relation(ShapeRelation relation) {
if (relation == null) {
throw new IllegalArgumentException("No Shape Relation defined");
Expand Down Expand Up @@ -427,6 +432,7 @@ protected void doXContent(XContentBuilder builder, Params params) throws IOExcep
}

@Override
@SuppressWarnings("rawtypes")
protected boolean doEquals(AbstractGeometryQueryBuilder other) {
return Objects.equals(fieldName, other.fieldName)
&& Objects.equals(indexedShapeId, other.indexedShapeId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ public Item(@Nullable String index, XContentBuilder doc) {
/**
* Read from a stream.
*/
@SuppressWarnings("unchecked")
Item(StreamInput in) throws IOException {
index = in.readOptionalString();
if (in.getVersion().before(Version.V_8_0_0)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ public static GeoShapeQueryBuilder geoShapeQuery(String name, Geometry shape) th
* @deprecated use {@link #geoShapeQuery(String, Geometry)} instead
*/
@Deprecated
public static GeoShapeQueryBuilder geoShapeQuery(String name, ShapeBuilder shape) throws IOException {
public static GeoShapeQueryBuilder geoShapeQuery(String name, ShapeBuilder<?, ?, ?> shape) throws IOException {
return new GeoShapeQueryBuilder(name, shape.buildGeometry());
}

Expand All @@ -668,7 +668,7 @@ public static GeoShapeQueryBuilder geoIntersectionQuery(String name, Geometry sh
* @deprecated use {@link #geoIntersectionQuery(String, Geometry)} instead
*/
@Deprecated
public static GeoShapeQueryBuilder geoIntersectionQuery(String name, ShapeBuilder shape) throws IOException {
public static GeoShapeQueryBuilder geoIntersectionQuery(String name, ShapeBuilder<?, ?, ?> shape) throws IOException {
GeoShapeQueryBuilder builder = geoShapeQuery(name, shape);
builder.relation(ShapeRelation.INTERSECTS);
return builder;
Expand Down Expand Up @@ -696,7 +696,7 @@ public static GeoShapeQueryBuilder geoWithinQuery(String name, Geometry shape) t
* @deprecated use {@link #geoWithinQuery(String, Geometry)} instead
*/
@Deprecated
public static GeoShapeQueryBuilder geoWithinQuery(String name, ShapeBuilder shape) throws IOException {
public static GeoShapeQueryBuilder geoWithinQuery(String name, ShapeBuilder<?, ?, ?> shape) throws IOException {
GeoShapeQueryBuilder builder = geoShapeQuery(name, shape);
builder.relation(ShapeRelation.WITHIN);
return builder;
Expand Down Expand Up @@ -724,7 +724,7 @@ public static GeoShapeQueryBuilder geoDisjointQuery(String name, Geometry shape)
* @deprecated use {@link #geoDisjointQuery(String, Geometry)} instead
*/
@Deprecated
public static GeoShapeQueryBuilder geoDisjointQuery(String name, ShapeBuilder shape) throws IOException {
public static GeoShapeQueryBuilder geoDisjointQuery(String name, ShapeBuilder<?, ?, ?> shape) throws IOException {
GeoShapeQueryBuilder builder = geoShapeQuery(name, shape);
builder.relation(ShapeRelation.DISJOINT);
return builder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ protected QueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) {
return this;
}

@SuppressWarnings("rawtypes")
private abstract static class Values extends AbstractCollection implements Writeable {

private static Values readFrom(StreamInput in) throws IOException {
Expand Down Expand Up @@ -477,6 +478,7 @@ public final void clear() {
* When users send a query contain a lot of terms, A {@link BytesReference} can help
* gc and reduce the cost of {@link #doWriteTo}, which can be slow for lots of terms.
*/
@SuppressWarnings("rawtypes")
private static class BinaryValues extends Values {

private final BytesReference valueRef;
Expand Down Expand Up @@ -577,6 +579,7 @@ private int consumerHeadersAndGetListSize(StreamInput in) throws IOException {
*
* TODO: remove in 9.0.0
*/
@SuppressWarnings("rawtypes")
private static class ListValues extends Values {

private final List<?> values;
Expand Down Expand Up @@ -611,6 +614,7 @@ public Object[] toArray(Object[] a) {
}

@Override
@SuppressWarnings("unchecked")
public Object[] toArray(IntFunction generator) {
return values.toArray(generator);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public static RandomScoreFunctionBuilder randomFunction() {
}

public static WeightBuilder weightFactorFunction(float weight) {
return (WeightBuilder)(new WeightBuilder().setWeight(weight));
return new WeightBuilder().setWeight(weight);
}

public static FieldValueFactorFunctionBuilder fieldValueFactorFunction(String fieldName) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,11 +367,10 @@ public static class Status implements Task.Status, SuccessfullyProcessed {
FIELDS_SET.add(SLICES_FIELD);
}

@SuppressWarnings("unchecked")
static final ConstructingObjectParser<Tuple<Long, Long>, Void> RETRIES_PARSER = new ConstructingObjectParser<>(
"bulk_by_scroll_task_status_retries",
true,
a -> new Tuple(a[0], a[1])
a -> new Tuple<>(((Long) a[0]), (Long) a[1])
);
static {
RETRIES_PARSER.declareLong(constructorArg(), new ParseField(RETRIES_BULK_FIELD));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ public static void buildNodesHeader(final XContentBuilder builder, final Params
* @return Never {@code null}.
* @throws IOException if building the response causes an issue
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static <NodesResponse extends BaseNodesResponse & ToXContent> BytesRestResponse nodesResponse(final XContentBuilder builder,
final Params params,
final NodesResponse response)
Expand Down Expand Up @@ -214,7 +215,7 @@ public static QueryBuilder getQueryContent(String fieldName, XContentParser requ
* });
* </code>
*/
public static class NodesResponseRestListener<NodesResponse extends BaseNodesResponse & ToXContent>
public static class NodesResponseRestListener<NodesResponse extends BaseNodesResponse<?> & ToXContent>
extends RestBuilderListener<NodesResponse> {

public NodesResponseRestListener(RestChannel channel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public String getName() {
}

@Override
@SuppressWarnings("unchecked")
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = Requests.clusterUpdateSettingsRequest();
clusterUpdateSettingsRequest.timeout(request.paramAsTime("timeout", clusterUpdateSettingsRequest.timeout()));
Expand All @@ -50,10 +51,10 @@ public RestChannelConsumer prepareRequest(final RestRequest request, final NodeC
source = parser.map();
}
if (source.containsKey(TRANSIENT)) {
clusterUpdateSettingsRequest.transientSettings((Map) source.get(TRANSIENT));
clusterUpdateSettingsRequest.transientSettings((Map<String, ?>) source.get(TRANSIENT));
}
if (source.containsKey(PERSISTENT)) {
clusterUpdateSettingsRequest.persistentSettings((Map) source.get(PERSISTENT));
clusterUpdateSettingsRequest.persistentSettings((Map<String, ?>) source.get(PERSISTENT));
}

return channel -> client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new RestToXContentListener<>(channel));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ static class TableIndexComparator implements Comparator<Integer> {
this.ordering = ordering;
}

@SuppressWarnings("unchecked")
private int compareCell(Object o1, Object o2) {
if (o1 == null && o2 == null) {
return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ public T getMax() {
/**
* Return a {@link Comparator} for {@link MinAndMax} values according to the provided {@link SortOrder}.
*/
public static Comparator<MinAndMax<?>> getComparator(SortOrder order) {
Comparator<MinAndMax<?>> cmp = order == SortOrder.ASC ?
public static <T extends Comparable<? super T>> Comparator<MinAndMax<T>> getComparator(SortOrder order) {
Comparator<MinAndMax<T>> cmp = order == SortOrder.ASC ?
Comparator.comparing(MinAndMax::getMin) : Comparator.comparing(MinAndMax::getMax);
if (order == SortOrder.DESC) {
cmp = cmp.reversed();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
import java.util.stream.IntStream;

import static org.elasticsearch.action.search.SearchAsyncActionTests.getShardsIter;
import static org.elasticsearch.core.Types.forciblyCast;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;

Expand Down Expand Up @@ -353,7 +354,7 @@ public void run() {
latch.await();
ShardId[] expected = IntStream.range(0, shardIds.size())
.boxed()
.sorted(Comparator.comparing(minAndMaxes::get, MinAndMax.getComparator(order)).thenComparing(shardIds::get))
.sorted(Comparator.comparing(minAndMaxes::get, forciblyCast(MinAndMax.getComparator(order))).thenComparing(shardIds::get))
.map(shardIds::get)
.toArray(ShardId[]::new);
if (shardToSkip.size() == expected.length) {
Expand Down
Loading