Skip to content

Commit

Permalink
Enable compiler warnings for watcher (#75516)
Browse files Browse the repository at this point in the history
Part of #40366.
  • Loading branch information
pugnascotia committed Jul 20, 2021
1 parent c412076 commit b374c68
Show file tree
Hide file tree
Showing 56 changed files with 233 additions and 149 deletions.
4 changes: 0 additions & 4 deletions x-pack/plugin/watcher/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ archivesBaseName = 'x-pack-watcher'

ext.compactProfile = 'full'

tasks.withType(JavaCompile).configureEach {
options.compilerArgs << "-Xlint:-rawtypes,-unchecked"
}

tasks.named("dependencyLicenses").configure {
mapping from: /owasp-java-html-sanitizer.*/, to: 'owasp-java-html-sanitizer'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ public class Watcher extends Plugin implements SystemIndexPlugin, ScriptPlugin,
protected final Settings settings;
protected final boolean transportClient;
protected final boolean enabled;
protected List<NotificationService> reloadableServices = new ArrayList<>();
protected List<NotificationService<?>> reloadableServices = new ArrayList<>();

public Watcher(final Settings settings) {
this.settings = settings;
Expand Down Expand Up @@ -298,7 +298,7 @@ public Collection<Object> createComponents(Client client, ClusterService cluster
reloadableServices.add(pagerDutyService);

TextTemplateEngine templateEngine = new TextTemplateEngine(scriptService);
Map<String, EmailAttachmentParser> emailAttachmentParsers = new HashMap<>();
Map<String, EmailAttachmentParser<?>> emailAttachmentParsers = new HashMap<>();
emailAttachmentParsers.put(HttpEmailAttachementParser.TYPE, new HttpEmailAttachementParser(httpClient, templateEngine));
emailAttachmentParsers.put(DataAttachmentParser.TYPE, new DataAttachmentParser());
emailAttachmentParsers.put(ReportingAttachmentParser.TYPE,
Expand Down Expand Up @@ -333,7 +333,7 @@ public Collection<Object> createComponents(Client client, ClusterService cluster
getLicenseState());

// inputs
final Map<String, InputFactory> inputFactories = new HashMap<>();
final Map<String, InputFactory<?, ?, ?>> inputFactories = new HashMap<>();
inputFactories.put(SearchInput.TYPE, new SearchInputFactory(settings, client, xContentRegistry, scriptService));
inputFactories.put(SimpleInput.TYPE, new SimpleInputFactory());
inputFactories.put(HttpInput.TYPE, new HttpInputFactory(settings, httpClient, templateEngine));
Expand Down Expand Up @@ -396,7 +396,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure)
HistoryStore historyStore = new HistoryStore(bulkProcessor, clusterService::state);

// schedulers
final Set<Schedule.Parser> scheduleParsers = new HashSet<>();
final Set<Schedule.Parser<?>> scheduleParsers = new HashSet<>();
scheduleParsers.add(new CronSchedule.Parser());
scheduleParsers.add(new DailySchedule.Parser());
scheduleParsers.add(new HourlySchedule.Parser());
Expand All @@ -406,10 +406,10 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure)
scheduleParsers.add(new YearlySchedule.Parser());
final ScheduleRegistry scheduleRegistry = new ScheduleRegistry(scheduleParsers);

TriggerEngine manualTriggerEngine = new ManualTriggerEngine();
final TriggerEngine configuredTriggerEngine = getTriggerEngine(getClock(), scheduleRegistry);
TriggerEngine<?, ?> manualTriggerEngine = new ManualTriggerEngine();
final TriggerEngine<?, ?> configuredTriggerEngine = getTriggerEngine(getClock(), scheduleRegistry);

final Set<TriggerEngine> triggerEngines = new HashSet<>();
final Set<TriggerEngine<?, ?>> triggerEngines = new HashSet<>();
triggerEngines.add(manualTriggerEngine);
triggerEngines.add(configuredTriggerEngine);
final TriggerService triggerService = new TriggerService(triggerEngines);
Expand Down Expand Up @@ -442,7 +442,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure)
configuredTriggerEngine, triggeredWatchStore, watcherSearchTemplateService, slackService, pagerDutyService);
}

protected TriggerEngine getTriggerEngine(Clock clock, ScheduleRegistry scheduleRegistry) {
protected TriggerEngine<?, ?> getTriggerEngine(Clock clock, ScheduleRegistry scheduleRegistry) {
return new TickerScheduleTriggerEngine(settings, scheduleRegistry, clock);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.elasticsearch.xpack.watcher.notification.email.EmailService;
import org.elasticsearch.xpack.watcher.notification.email.HtmlSanitizer;
import org.elasticsearch.xpack.watcher.notification.email.attachment.EmailAttachmentParser;
import org.elasticsearch.xpack.watcher.notification.email.attachment.EmailAttachmentParser.EmailAttachment;
import org.elasticsearch.xpack.watcher.support.Variables;

import java.io.IOException;
Expand All @@ -35,10 +36,16 @@ public class ExecutableEmailAction extends ExecutableAction<EmailAction> {
private final EmailService emailService;
private final TextTemplateEngine templateEngine;
private final HtmlSanitizer htmlSanitizer;
private final Map<String, EmailAttachmentParser> emailAttachmentParsers;
private final Map<String, EmailAttachmentParser<? extends EmailAttachment>> emailAttachmentParsers;

public ExecutableEmailAction(EmailAction action, Logger logger, EmailService emailService, TextTemplateEngine templateEngine,
HtmlSanitizer htmlSanitizer, Map<String, EmailAttachmentParser> emailAttachmentParsers) {
public ExecutableEmailAction(
EmailAction action,
Logger logger,
EmailService emailService,
TextTemplateEngine templateEngine,
HtmlSanitizer htmlSanitizer,
Map<String, EmailAttachmentParser<? extends EmailAttachment>> emailAttachmentParsers
) {
super(action, logger);
this.emailService = emailService;
this.templateEngine = templateEngine;
Expand All @@ -57,8 +64,10 @@ public Action.Result execute(String actionId, WatchExecutionContext ctx, Payload
}

if (action.getAttachments() != null && action.getAttachments().getAttachments().size() > 0) {
for (EmailAttachmentParser.EmailAttachment emailAttachment : action.getAttachments().getAttachments()) {
EmailAttachmentParser parser = emailAttachmentParsers.get(emailAttachment.type());
for (EmailAttachment emailAttachment : action.getAttachments().getAttachments()) {
@SuppressWarnings("unchecked")
EmailAttachmentParser<EmailAttachment> parser =
(EmailAttachmentParser<EmailAttachment>) emailAttachmentParsers.get(emailAttachment.type());
try {
Attachment attachment = parser.toAttachment(ctx, payload, emailAttachment);
attachments.put(attachment.id(), attachment);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,14 @@ public ExecutableIndexAction(IndexAction action, Logger logger, Client client,
this.bulkDefaultTimeout = action.timeout != null ? action.timeout : bulkDefaultTimeout;
}

@SuppressWarnings("unchecked")
@Override
public Action.Result execute(String actionId, WatchExecutionContext ctx, Payload payload) throws Exception {
Map<String, Object> data = payload.data();
if (data.containsKey("_doc")) {
Object doc = data.get("_doc");
if (doc instanceof Iterable) {
return indexBulk((Iterable) doc, actionId, ctx);
return indexBulk((Iterable<?>) doc, actionId, ctx);
}
if (doc.getClass().isArray()) {
return indexBulk(new ArrayObjectIterator.Iterable(doc), actionId, ctx);
Expand Down Expand Up @@ -110,7 +111,7 @@ public Action.Result execute(String actionId, WatchExecutionContext ctx, Payload
return new IndexAction.Result(Status.SUCCESS, new XContentSource(bytesReference, XContentType.JSON));
}

Action.Result indexBulk(Iterable list, String actionId, WatchExecutionContext ctx) throws Exception {
Action.Result indexBulk(Iterable<?> list, String actionId, WatchExecutionContext ctx) throws Exception {
if (action.docId != null) {
throw illegalState("could not execute action [{}] of watch [{}]. [doc_id] cannot be used with bulk [_doc] indexing");
}
Expand All @@ -126,6 +127,7 @@ Action.Result indexBulk(Iterable list, String actionId, WatchExecutionContext ct
"[_data] field must either hold a Map or an List/Array of Maps", actionId, ctx.watch().id());
}

@SuppressWarnings("unchecked")
Map<String, Object> doc = (Map<String, Object>) item;
if (doc.containsKey(INDEX_FIELD) || doc.containsKey(TYPE_FIELD) || doc.containsKey(ID_FIELD)) {
doc = mutableMap(doc);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public Action.Result execute(final String actionId, WatchExecutionContext ctx, P
* Merges the defaults provided as the second parameter into the content of the first
* while applying a {@link Function} on both map key and map value.
*/
@SuppressWarnings("unchecked")
static Map<String, Object> merge(final Map<String, Object> fields, final Map<String, ?> defaults, final Function<String, String> fn) {
if (defaults != null) {
for (Map.Entry<String, ?> defaultEntry : defaults.entrySet()) {
Expand All @@ -85,8 +86,8 @@ static Map<String, Object> merge(final Map<String, Object> fields, final Map<Str

} else if (value instanceof List) {
// Apply the transformation to a list of strings
List<Object> newValues = new ArrayList<>(((List) value).size());
for (Object v : (List) value) {
List<Object> newValues = new ArrayList<>(((List<?>) value).size());
for (Object v : (List<?>) value) {
if (v instanceof String) {
newValues.add(fn.apply((String) v));
} else if (v instanceof Map) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,12 @@ public static HttpRequest parse(XContentParser parser) throws IOException {
pe, currentFieldName);
}
} else if (token == XContentParser.Token.START_OBJECT) {
@SuppressWarnings({"unchecked", "rawtypes"})
final Map<String, String> headers = (Map) WatcherUtils.flattenModel(parser.map());
if (Field.HEADERS.match(currentFieldName, parser.getDeprecationHandler())) {
builder.setHeaders((Map) WatcherUtils.flattenModel(parser.map()));
builder.setHeaders(headers);
} else if (Field.PARAMS.match(currentFieldName, parser.getDeprecationHandler())) {
builder.setParams((Map) WatcherUtils.flattenModel(parser.map()));
builder.setParams(headers);
} else if (Field.BODY.match(currentFieldName, parser.getDeprecationHandler())) {
builder.body(parser.text());
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class LenientCompare {
// will fail and `false` will be returned.
//
// may return `null` indicating v1 simply doesn't equal v2 (without any order association)
@SuppressWarnings("unchecked")
public static Integer compare(Object v1, Object v2) {
if (Objects.equals(v1, v2)) {
return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@

public class InputRegistry {

private final Map<String, InputFactory> factories;
private final Map<String, InputFactory<?, ?, ?>> factories;

public InputRegistry(Map<String, InputFactory> factories) {
Map<String, InputFactory> map = new HashMap<>(factories);
public InputRegistry(Map<String, InputFactory<?, ?, ?>> factories) {
Map<String, InputFactory<?, ?, ?>> map = new HashMap<>(factories);
map.put(ChainInput.TYPE, new ChainInputFactory(this));
this.factories = Collections.unmodifiableMap(map);
}
Expand Down Expand Up @@ -69,7 +69,7 @@ public InputRegistry(Map<String, InputFactory> factories) {
return input;
}

public Map<String, InputFactory> factories() {
public Map<String, InputFactory<?, ?, ?>> factories() {
return factories;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private Builder() {
inputs = new ArrayList<>();
}

public Builder add(String name, Input.Builder input) {
public Builder add(String name, Input.Builder<?> input) {
inputs.add(new Tuple<>(name, input.build()));
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,11 @@ public ChainInput parseInput(String watchId, XContentParser parser) throws IOExc

@Override
public ExecutableChainInput createExecutable(ChainInput input) {
List<Tuple<String, ExecutableInput>> executableInputs = new ArrayList<>();
List<Tuple<String, ExecutableInput<?, ?>>> executableInputs = new ArrayList<>();
for (Tuple<String, Input> tuple : input.getInputs()) {
ExecutableInput executableInput = inputRegistry.factories().get(tuple.v2().type()).createExecutable(tuple.v2());
@SuppressWarnings("unchecked")
ExecutableInput<?, ?> executableInput =
((InputFactory<Input, ?, ?>) inputRegistry.factories().get(tuple.v2().type())).createExecutable(tuple.v2());
executableInputs.add(new Tuple<>(tuple.v1(), executableInput));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
public class ExecutableChainInput extends ExecutableInput<ChainInput,ChainInput.Result> {
private static final Logger logger = LogManager.getLogger(ExecutableChainInput.class);

private List<Tuple<String, ExecutableInput>> inputs;
private List<Tuple<String, ExecutableInput<?, ?>>> inputs;

public ExecutableChainInput(ChainInput input, List<Tuple<String, ExecutableInput>> inputs) {
public ExecutableChainInput(ChainInput input, List<Tuple<String, ExecutableInput<?, ?>>> inputs) {
super(input);
this.inputs = inputs;
}
Expand All @@ -37,7 +37,7 @@ public ChainInput.Result execute(WatchExecutionContext ctx, Payload payload) {
Map<String, Object> payloads = new HashMap<>();

try {
for (Tuple<String, ExecutableInput> tuple : inputs) {
for (Tuple<String, ExecutableInput<?, ?>> tuple : inputs) {
Input.Result result = tuple.v2().execute(ctx, new Payload.Simple(payloads));
results.add(new Tuple<>(tuple.v1(), result));
payloads.put(tuple.v1(), result.payload().data());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@

public final class ExecutableTransformInput extends ExecutableInput<TransformInput, TransformInput.Result> {

private final ExecutableTransform executableTransform;
private final ExecutableTransform<?, ?> executableTransform;

ExecutableTransformInput(TransformInput input, ExecutableTransform executableTransform) {
ExecutableTransformInput(TransformInput input, ExecutableTransform<?, ?> executableTransform) {
super(input);
this.executableTransform = executableTransform;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ public TransformInput parseInput(String watchId, XContentParser parser) throws I
@Override
public ExecutableTransformInput createExecutable(TransformInput input) {
Transform transform = input.getTransform();
TransformFactory factory = transformRegistry.factory(transform.type());
ExecutableTransform executableTransform = factory.createExecutable(transform);
@SuppressWarnings("unchecked")
TransformFactory<Transform, ?, ?> factory = (TransformFactory<Transform, ?, ?>) transformRegistry.factory(transform.type());
ExecutableTransform<?, ?> executableTransform = factory.createExecutable(transform);
return new ExecutableTransformInput(input, executableTransform);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public EmailAttachments(Collection<EmailAttachmentParser.EmailAttachment> attach
this.attachments = attachments;
}

public Collection<EmailAttachmentParser.EmailAttachment> getAttachments() {
public Collection<? extends EmailAttachmentParser.EmailAttachment> getAttachments() {
return attachments;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.watcher.notification.email.attachment.EmailAttachmentParser.EmailAttachment;

import java.io.IOException;
import java.util.ArrayList;
Expand All @@ -16,14 +17,14 @@
import java.util.Map;

public class EmailAttachmentsParser {
private final Map<String, EmailAttachmentParser> parsers;
private final Map<String, EmailAttachmentParser<? extends EmailAttachment>> parsers;

public EmailAttachmentsParser(Map<String, EmailAttachmentParser> parsers) {
public EmailAttachmentsParser(Map<String, EmailAttachmentParser<? extends EmailAttachment>> parsers) {
this.parsers = Collections.unmodifiableMap(parsers);
}

public EmailAttachments parse(XContentParser parser) throws IOException {
List<EmailAttachmentParser.EmailAttachment> attachments = new ArrayList<>();
List<EmailAttachment> attachments = new ArrayList<>();
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
Expand All @@ -37,11 +38,11 @@ public EmailAttachments parse(XContentParser parser) throws IOException {
}
parser.nextToken();

EmailAttachmentParser emailAttachmentParser = parsers.get(currentAttachmentType);
EmailAttachmentParser<?> emailAttachmentParser = parsers.get(currentAttachmentType);
if (emailAttachmentParser == null) {
throw new ElasticsearchParseException("Cannot parse attachment of type [{}]", currentAttachmentType);
}
EmailAttachmentParser.EmailAttachment emailAttachment = emailAttachmentParser.parse(currentFieldName, parser);
EmailAttachment emailAttachment = emailAttachmentParser.parse(currentFieldName, parser);
attachments.add(emailAttachment);
// one further to skip the end_object from the attachment
parser.nextToken();
Expand All @@ -52,7 +53,7 @@ public EmailAttachments parse(XContentParser parser) throws IOException {
return new EmailAttachments(attachments);
}

public Map<String, EmailAttachmentParser> getParsers() {
public Map<String, EmailAttachmentParser<? extends EmailAttachment>> getParsers() {
return parsers;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,15 @@ public DynamicAttachments(String listPath, Attachment.Template attachment) {
this.attachment = attachment;
}

@SuppressWarnings("unchecked")
public List<Attachment> render(TextTemplateEngine engine, Map<String, Object> model, SlackMessageDefaults.AttachmentDefaults defaults) {
Object value = ObjectPath.eval(listPath, model);
if ((value instanceof Iterable) == false) {
throw new IllegalArgumentException("dynamic attachment could not be resolved. expected context [" + listPath + "] to be a " +
"list, but found [" + value + "] instead");
}
List<Attachment> attachments = new ArrayList<>();
for (Object obj : (Iterable) value) {
for (Object obj : (Iterable<Object>) value) {
if ((obj instanceof Map) == false) {
throw new IllegalArgumentException("dynamic attachment could not be resolved. expected [" + listPath + "] list to contain" +
" key/value pairs, but found [" + obj + "] instead");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ ScriptTransform.Result doExecute(WatchExecutionContext ctx, Payload payload) thr
Object value = transformScript.execute();
// TODO: deprecate one of these styles (returning a map or returning an opaque value below)
if (value instanceof Map) {
return new ScriptTransform.Result(new Payload.Simple((Map<String, Object>) value));
@SuppressWarnings("unchecked")
final Payload.Simple simplePayload = new Payload.Simple((Map<String, Object>) value);
return new ScriptTransform.Result(simplePayload);
}
Map<String, Object> data = new HashMap<>();
data.put("_value", value);
Expand Down
Loading

0 comments on commit b374c68

Please sign in to comment.