Remove ImmutableMap$Builder

Original commit: elastic/x-pack-elasticsearch@f0d3f71887
This commit is contained in:
Nik Everett 2015-10-05 17:11:33 -04:00
parent 1d61278b2d
commit dab504f6ba
20 changed files with 258 additions and 177 deletions

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.shield.authc.esusers;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.inject.internal.Nullable;
import org.elasticsearch.common.logging.ESLogger;
@ -28,12 +26,14 @@ import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.shield.support.ShieldFiles.openAtomicMoveWriter;
/**
@ -137,7 +137,7 @@ public class FileUserPasswdStore {
throw new IllegalStateException("could not read users file [" + path.toAbsolutePath() + "]", ioe);
}
ImmutableMap.Builder<String, char[]> users = ImmutableMap.builder();
Map<String, char[]> users = new HashMap<>();
int lineNr = 0;
for (String line : lines) {
@ -164,11 +164,10 @@ public class FileUserPasswdStore {
users.put(username, hash.toCharArray());
}
ImmutableMap<String, char[]> usersMap = users.build();
if (usersMap.isEmpty()){
if (users.isEmpty()){
logger.warn("no users found in users file [{}]. use bin/shield/esusers to add users and role mappings", path.toAbsolutePath());
}
return usersMap;
return unmodifiableMap(users);
}
public static void writeFile(Map<String, char[]> esUsers, Path path) {

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.shield.authc.esusers;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.internal.Nullable;
@ -36,6 +34,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Pattern;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.shield.support.ShieldFiles.openAtomicMoveWriter;
/**
@ -173,17 +172,16 @@ public class FileUserRolesStore {
}
}
ImmutableMap.Builder<String, String[]> builder = ImmutableMap.builder();
Map<String, String[]> usersRoles = new HashMap<>();
for (Map.Entry<String, List<String>> entry : userToRoles.entrySet()) {
builder.put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
usersRoles.put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
}
ImmutableMap<String, String[]> usersRoles = builder.build();
if (usersRoles.isEmpty()){
logger.warn("no entries found in users_roles file [{}]. use bin/shield/esusers to add users and role mappings", path.toAbsolutePath());
}
return usersRoles;
return unmodifiableMap(usersRoles);
}
/**

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.shield.authz;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.cluster.metadata.AliasOrIndex;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
@ -346,7 +344,7 @@ public interface Permission {
}
@Override
public ImmutableMap<String, IndicesAccessControl.IndexAccessControl> authorize(String action, Set<String> requestedIndicesOrAliases, MetaData metaData) {
public Map<String, IndicesAccessControl.IndexAccessControl> authorize(String action, Set<String> requestedIndicesOrAliases, MetaData metaData) {
// now... every index that is associated with the request, must be granted
// by at least one indices permission group
@ -398,7 +396,7 @@ public interface Permission {
}
}
ImmutableMap.Builder<String, IndicesAccessControl.IndexAccessControl> indexPermissions = ImmutableMap.builder();
Map<String, IndicesAccessControl.IndexAccessControl> indexPermissions = new HashMap<>();
for (Map.Entry<String, Boolean> entry : grantedBuilder.entrySet()) {
String index = entry.getKey();
Set<BytesReference> roleQueries = roleQueriesByIndex.get(index);
@ -411,7 +409,7 @@ public interface Permission {
}
indexPermissions.put(index, new IndicesAccessControl.IndexAccessControl(entry.getValue(), roleFields, roleQueries));
}
return indexPermissions.build();
return unmodifiableMap(indexPermissions);
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.actions.email.service;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
@ -16,14 +15,23 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static java.util.Collections.unmodifiableMap;
/**
*
@ -41,12 +49,12 @@ public class Email implements ToXContent {
final String subject;
final String textBody;
final String htmlBody;
final ImmutableMap<String, Attachment> attachments;
final ImmutableMap<String, Inline> inlines;
final Map<String, Attachment> attachments;
final Map<String, Inline> inlines;
public Email(String id, Address from, AddressList replyTo, Priority priority, DateTime sentDate,
AddressList to, AddressList cc, AddressList bcc, String subject, String textBody, String htmlBody,
ImmutableMap<String, Attachment> attachments, ImmutableMap<String, Inline> inlines) {
Map<String, Attachment> attachments, Map<String, Inline> inlines) {
this.id = id;
this.from = from;
@ -107,11 +115,11 @@ public class Email implements ToXContent {
return htmlBody;
}
public ImmutableMap<String, Attachment> attachments() {
public Map<String, Attachment> attachments() {
return attachments;
}
public ImmutableMap<String, Inline> inlines() {
public Map<String, Inline> inlines() {
return inlines;
}
@ -239,8 +247,8 @@ public class Email implements ToXContent {
private String subject;
private String textBody;
private String htmlBody;
private ImmutableMap.Builder<String, Attachment> attachments = ImmutableMap.builder();
private ImmutableMap.Builder<String, Inline> inlines = ImmutableMap.builder();
private Map<String, Attachment> attachments = new HashMap<>();
private Map<String, Inline> inlines = new HashMap<>();
private Builder() {
}
@ -342,19 +350,32 @@ public class Email implements ToXContent {
}
public Builder attach(Attachment attachment) {
if (attachments == null) {
throw new IllegalStateException("Email has already been built!");
}
attachments.put(attachment.id(), attachment);
return this;
}
public Builder inline(Inline inline) {
if (inlines == null) {
throw new IllegalStateException("Email has already been built!");
}
inlines.put(inline.id(), inline);
return this;
}
/**
* Build the email. Note that adding items to attachments or inlines
* after this is called is incorrect.
*/
public Email build() {
assert id != null : "email id should not be null (should be set to the watch id";
ImmutableMap<String, Attachment> attachmentsMap = attachments.build();
return new Email(id, from, replyTo, priority, sentDate, to, cc, bcc, subject, textBody, htmlBody, attachmentsMap, inlines.build());
Email email = new Email(id, from, replyTo, priority, sentDate, to, cc, bcc, subject, textBody, htmlBody,
unmodifiableMap(attachments), unmodifiableMap(inlines));
attachments = null;
inlines = null;
return email;
}
}

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.watcher.execution;
import com.google.common.collect.ImmutableMap;
import org.joda.time.DateTime;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.watcher.actions.Action;
import org.elasticsearch.watcher.actions.ActionWrapper;
@ -14,10 +12,14 @@ import org.elasticsearch.watcher.condition.Condition;
import org.elasticsearch.watcher.input.Input;
import org.elasticsearch.watcher.trigger.manual.ManualTriggerEvent;
import org.elasticsearch.watcher.watch.Watch;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/**
*/
public class ManualExecutionContext extends WatchExecutionContext {
@ -100,7 +102,7 @@ public class ManualExecutionContext extends WatchExecutionContext {
private final TimeValue defaultThrottlePeriod;
protected DateTime executionTime;
private boolean recordExecution = false;
private ImmutableMap.Builder<String, ActionExecutionMode> actionModes = ImmutableMap.builder();
private Map<String, ActionExecutionMode> actionModes = new HashMap<>();
private Input.Result inputResult;
private Condition.Result conditionResult;
@ -127,8 +129,11 @@ public class ManualExecutionContext extends WatchExecutionContext {
}
public Builder actionMode(String id, ActionExecutionMode mode) {
if (actionModes == null) {
throw new IllegalStateException("ManualExecutionContext has already been built!");
}
if (ALL.equals(id)) {
actionModes = ImmutableMap.builder();
actionModes = new HashMap<>();
}
actionModes.put(id, mode);
return this;
@ -148,7 +153,9 @@ public class ManualExecutionContext extends WatchExecutionContext {
if (executionTime == null) {
executionTime = DateTime.now(DateTimeZone.UTC);
}
return new ManualExecutionContext(watch, knownWatch, executionTime, triggerEvent, defaultThrottlePeriod, inputResult, conditionResult, actionModes.build(), recordExecution);
ManualExecutionContext context = new ManualExecutionContext(watch, knownWatch, executionTime, triggerEvent, defaultThrottlePeriod, inputResult, conditionResult, unmodifiableMap(actionModes), recordExecution);
actionModes = null;
return context;
}
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.input;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.common.collect.MapBuilder;
@ -47,10 +46,6 @@ public final class InputBuilders {
return simpleInput(MapBuilder.<String, Object>newMapBuilder().put(key, value));
}
public static SimpleInput.Builder simpleInput(ImmutableMap.Builder<String, Object> data) {
return simpleInput(data.build());
}
public static SimpleInput.Builder simpleInput(MapBuilder<String, Object> data) {
return simpleInput(data.map());
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.support.http;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.ExceptionsHelper;
@ -13,24 +12,38 @@ import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.watcher.support.http.auth.ApplicableHttpAuth;
import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry;
import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import static java.util.Collections.unmodifiableMap;
/**
* Client class to wrap http connections
*/
@ -160,7 +173,7 @@ public class HttpClient extends AbstractLifecycleComponent<HttpClient> {
urlConnection.connect();
final int statusCode = urlConnection.getResponseCode();
ImmutableMap.Builder<String, String[]> responseHeaders = ImmutableMap.builder();
Map<String, String[]> responseHeaders = new HashMap<>();
for (Map.Entry<String, List<String>> header : urlConnection.getHeaderFields().entrySet()) {
// HttpURLConnection#getHeaderFields returns the first status line as a header
// with a `null` key (facepalm)... so we have to skip that one.
@ -168,6 +181,7 @@ public class HttpClient extends AbstractLifecycleComponent<HttpClient> {
responseHeaders.put(header.getKey(), header.getValue().toArray(new String[header.getValue().size()]));
}
}
responseHeaders = unmodifiableMap(responseHeaders);
logger.debug("http status code [{}]", statusCode);
if (statusCode < 400) {
final byte[] body;
@ -175,9 +189,9 @@ public class HttpClient extends AbstractLifecycleComponent<HttpClient> {
Streams.copy(inputStream, outputStream);
body = outputStream.toByteArray();
}
return new HttpResponse(statusCode, body, responseHeaders.build());
return new HttpResponse(statusCode, body, responseHeaders);
}
return new HttpResponse(statusCode, responseHeaders.build());
return new HttpResponse(statusCode, responseHeaders);
}
/** SSL Initialization **/

View File

@ -5,14 +5,17 @@
*/
package org.elasticsearch.watcher.support.http;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.watcher.support.WatcherDateTimeUtils;
import org.elasticsearch.watcher.support.WatcherUtils;
import org.elasticsearch.watcher.support.http.auth.HttpAuth;
@ -22,9 +25,11 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
public class HttpRequest implements ToXContent {
@ -41,7 +46,7 @@ public class HttpRequest implements ToXContent {
final @Nullable TimeValue readTimeout;
public HttpRequest(String host, int port, @Nullable Scheme scheme, @Nullable HttpMethod method, @Nullable String path,
@Nullable ImmutableMap<String, String> params, @Nullable ImmutableMap<String, String> headers,
@Nullable Map<String, String> params, @Nullable Map<String, String> headers,
@Nullable HttpAuth auth, @Nullable String body, @Nullable TimeValue connectionTimeout, @Nullable TimeValue readTimeout) {
this.host = host;
this.port = port;
@ -302,8 +307,8 @@ public class HttpRequest implements ToXContent {
private Scheme scheme;
private HttpMethod method;
private String path;
private ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
private ImmutableMap.Builder<String, String> headers = ImmutableMap.builder();
private Map<String, String> params = new HashMap<>();
private Map<String, String> headers = new HashMap<>();
private HttpAuth auth;
private String body;
private TimeValue connectionTimeout;
@ -333,21 +338,33 @@ public class HttpRequest implements ToXContent {
}
public Builder setParams(Map<String, String> params) {
if (this.params == null) {
throw new IllegalStateException("Request has already been built!");
}
this.params.putAll(params);
return this;
}
public Builder setParam(String key, String value) {
if (params == null) {
throw new IllegalStateException("Request has already been built!");
}
this.params.put(key, value);
return this;
}
public Builder setHeaders(Map<String, String> headers) {
if (this.headers == null) {
throw new IllegalStateException("Request has already been built!");
}
this.headers.putAll(headers);
return this;
}
public Builder setHeader(String key, String value) {
if (headers == null) {
throw new IllegalStateException("Request has already been built!");
}
this.headers.put(key, value);
return this;
}
@ -378,7 +395,10 @@ public class HttpRequest implements ToXContent {
}
public HttpRequest build() {
return new HttpRequest(host, port, scheme, method, path, params.build(), headers.build(), auth, body, connectionTimeout, readTimeout);
HttpRequest request = new HttpRequest(host, port, scheme, method, path, unmodifiableMap(params), unmodifiableMap(headers), auth, body, connectionTimeout, readTimeout);
params = null;
headers = null;
return request;
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.trigger;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractComponent;
@ -16,11 +15,13 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.watcher.support.Exceptions.illegalArgument;
/**
@ -29,18 +30,18 @@ import static org.elasticsearch.watcher.support.Exceptions.illegalArgument;
public class TriggerService extends AbstractComponent {
private final Listeners listeners;
private final ImmutableMap<String, TriggerEngine> engines;
private final Map<String, TriggerEngine> engines;
@Inject
public TriggerService(Settings settings, Set<TriggerEngine> engines) {
super(settings);
listeners = new Listeners();
ImmutableMap.Builder<String, TriggerEngine> builder = ImmutableMap.builder();
Map<String, TriggerEngine> builder = new HashMap<>();
for (TriggerEngine engine : engines) {
builder.put(engine.type(), engine);
engine.register(listeners);
}
this.engines = builder.build();
this.engines = unmodifiableMap(builder);
}
public synchronized void start(Collection<? extends TriggerEngine.Job> jobs) throws Exception {

View File

@ -5,26 +5,33 @@
*/
package org.elasticsearch.watcher.trigger.schedule.engine;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.FutureUtils;
import org.elasticsearch.watcher.support.clock.Clock;
import org.elasticsearch.watcher.trigger.TriggerEvent;
import org.elasticsearch.watcher.trigger.schedule.*;
import org.elasticsearch.watcher.trigger.schedule.Schedule;
import org.elasticsearch.watcher.trigger.schedule.ScheduleRegistry;
import org.elasticsearch.watcher.trigger.schedule.ScheduleTrigger;
import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEngine;
import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.unmodifiableMap;
/**
*
*/
@ -131,20 +138,20 @@ public class SchedulerScheduleTriggerEngine extends ScheduleTriggerEngine {
static class Schedules {
private final ActiveSchedule[] schedules;
private final ImmutableMap<String, ActiveSchedule> scheduleByName;
private final Map<String, ActiveSchedule> scheduleByName;
Schedules(Collection<ActiveSchedule> schedules) {
ImmutableMap.Builder<String, ActiveSchedule> builder = ImmutableMap.builder();
Map<String, ActiveSchedule> builder = new HashMap<>();
this.schedules = new ActiveSchedule[schedules.size()];
int i = 0;
for (ActiveSchedule schedule : schedules) {
builder.put(schedule.name, schedule);
this.schedules[i++] = schedule;
}
this.scheduleByName = builder.build();
this.scheduleByName = unmodifiableMap(builder);
}
public Schedules(ActiveSchedule[] schedules, ImmutableMap<String, ActiveSchedule> scheduleByName) {
public Schedules(ActiveSchedule[] schedules, Map<String, ActiveSchedule> scheduleByName) {
this.schedules = schedules;
this.scheduleByName = scheduleByName;
}
@ -155,14 +162,12 @@ public class SchedulerScheduleTriggerEngine extends ScheduleTriggerEngine {
ActiveSchedule[] newSchedules = new ActiveSchedule[schedules.length + 1];
System.arraycopy(schedules, 0, newSchedules, 0, schedules.length);
newSchedules[schedules.length] = schedule;
ImmutableMap<String, ActiveSchedule> newScheduleByName = ImmutableMap.<String, ActiveSchedule>builder()
.putAll(scheduleByName)
.put(schedule.name, schedule)
.build();
return new Schedules(newSchedules, newScheduleByName);
Map<String, ActiveSchedule> newScheduleByName = new HashMap<>(scheduleByName);
newScheduleByName.put(schedule.name, schedule);
return new Schedules(newSchedules, unmodifiableMap(newScheduleByName));
}
ActiveSchedule[] newSchedules = new ActiveSchedule[schedules.length];
ImmutableMap.Builder<String, ActiveSchedule> builder = ImmutableMap.builder();
Map<String, ActiveSchedule> builder = new HashMap<>();
for (int i = 0; i < schedules.length; i++) {
final ActiveSchedule sched;
if (schedules[i].name.equals(schedule.name)) {
@ -174,14 +179,14 @@ public class SchedulerScheduleTriggerEngine extends ScheduleTriggerEngine {
newSchedules[i] = sched;
builder.put(sched.name, sched);
}
return new Schedules(newSchedules, builder.build());
return new Schedules(newSchedules, unmodifiableMap(builder));
}
public Schedules remove(String name) {
if (!scheduleByName.containsKey(name)) {
return null;
}
ImmutableMap.Builder<String, ActiveSchedule> builder = ImmutableMap.builder();
Map<String, ActiveSchedule> builder = new HashMap<>();
ActiveSchedule[] newSchedules = new ActiveSchedule[schedules.length - 1];
int i = 0;
for (ActiveSchedule schedule : schedules) {
@ -192,7 +197,7 @@ public class SchedulerScheduleTriggerEngine extends ScheduleTriggerEngine {
schedule.cancel();
}
}
return new Schedules(newSchedules, builder.build());
return new Schedules(newSchedules, unmodifiableMap(builder));
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.watch;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
@ -42,14 +41,15 @@ import org.elasticsearch.watcher.trigger.Trigger;
import org.elasticsearch.watcher.trigger.TriggerEngine;
import org.elasticsearch.watcher.trigger.TriggerService;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.PeriodType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.watcher.support.Exceptions.ioException;
@ -85,10 +85,12 @@ public class Watch implements TriggerEngine.Job, ToXContent {
this.status = status;
}
@Override
public String id() {
return id;
}
@Override
public Trigger trigger() {
return trigger;
}
@ -343,12 +345,12 @@ public class Watch implements TriggerEngine.Job, ToXContent {
}
} else {
// we need to create the initial statuses for the actions
ImmutableMap.Builder<String, ActionStatus> actionsStatuses = ImmutableMap.builder();
Map<String, ActionStatus> actionsStatuses = new HashMap<>();
DateTime now = WatcherXContentParser.clock(parser).nowUTC();
for (ActionWrapper action : actions) {
actionsStatuses.put(action.id(), new ActionStatus(now));
}
status = new WatchStatus(WatcherXContentParser.clock(parser).nowUTC(), actionsStatuses.build());
status = new WatchStatus(WatcherXContentParser.clock(parser).nowUTC(), unmodifiableMap(actionsStatuses));
}
return new Watch(id, trigger, input, condition, transform, throttlePeriod, actions, metatdata, status);

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.watch;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.common.Nullable;
@ -26,9 +25,15 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.*;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.parseDate;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.readDate;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.readOptionalDate;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.writeDate;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.writeOptionalDate;
/**
*
@ -226,12 +231,12 @@ public class WatchStatus implements ToXContent, Streamable {
version = in.readLong();
lastChecked = readOptionalDate(in, DateTimeZone.UTC);
lastMetCondition = readOptionalDate(in, DateTimeZone.UTC);
ImmutableMap.Builder<String, ActionStatus> builder = ImmutableMap.builder();
int count = in.readInt();
Map<String, ActionStatus> actions = new HashMap<>(count);
for (int i = 0; i < count; i++) {
builder.put(in.readString(), ActionStatus.readFrom(in));
actions.put(in.readString(), ActionStatus.readFrom(in));
}
actions = builder.build();
this.actions = unmodifiableMap(actions);
if (in.getVersion().onOrAfter(Version.V_2_0_0)) {
state = new State(in.readBoolean(), readDate(in, DateTimeZone.UTC));
} else {
@ -273,7 +278,7 @@ public class WatchStatus implements ToXContent, Streamable {
State state = null;
DateTime lastChecked = null;
DateTime lastMetCondition = null;
ImmutableMap.Builder<String, ActionStatus> actions = null;
Map<String, ActionStatus> actions = null;
String currentFieldName = null;
XContentParser.Token token;
@ -299,7 +304,7 @@ public class WatchStatus implements ToXContent, Streamable {
throw new ElasticsearchParseException("could not parse watch status for [{}]. expecting field [{}] to hold a date value, found [{}] instead", watchId, currentFieldName, token);
}
} else if (ParseFieldMatcher.STRICT.match(currentFieldName, Field.ACTIONS)) {
actions = ImmutableMap.builder();
actions = new HashMap<>();
if (token == XContentParser.Token.START_OBJECT) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
@ -322,7 +327,7 @@ public class WatchStatus implements ToXContent, Streamable {
state = new State(true, WatcherXContentParser.clock(parser).nowUTC());
}
return new WatchStatus(-1, state, lastChecked, lastMetCondition, actions.build());
return new WatchStatus(-1, state, lastChecked, lastMetCondition, unmodifiableMap(actions));
}
public static class State implements ToXContent {

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.actions.email;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.MapBuilder;
@ -16,7 +15,12 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.watcher.actions.Action;
import org.elasticsearch.watcher.actions.email.service.*;
import org.elasticsearch.watcher.actions.email.service.Authentication;
import org.elasticsearch.watcher.actions.email.service.Email;
import org.elasticsearch.watcher.actions.email.service.EmailService;
import org.elasticsearch.watcher.actions.email.service.EmailTemplate;
import org.elasticsearch.watcher.actions.email.service.HtmlSanitizer;
import org.elasticsearch.watcher.actions.email.service.Profile;
import org.elasticsearch.watcher.execution.WatchExecutionContext;
import org.elasticsearch.watcher.execution.Wid;
import org.elasticsearch.watcher.support.secret.Secret;
@ -28,13 +32,20 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContextBuilder;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ -101,20 +112,18 @@ public class EmailActionTests extends ESTestCase {
.metadata(metadata)
.buildMock();
Map<String, Object> expectedModel = ImmutableMap.<String, Object>builder()
.put("ctx", ImmutableMap.<String, Object>builder()
.put("id", ctx.id().value())
.put("watch_id", "watch1")
.put("payload", data)
.put("metadata", metadata)
.put("execution_time", now)
.put("trigger", ImmutableMap.<String, Object>builder()
.put("triggered_time", now)
.put("scheduled_time", now)
.build())
.put("vars", Collections.emptyMap())
.build())
.build();
Map<String, Object> triggerModel = new HashMap<>();
triggerModel.put("triggered_time", now);
triggerModel.put("scheduled_time", now);
Map<String, Object> ctxModel = new HashMap<>();
ctxModel.put("id", ctx.id().value());
ctxModel.put("watch_id", "watch1");
ctxModel.put("payload", data);
ctxModel.put("metadata", metadata);
ctxModel.put("execution_time", now);
ctxModel.put("trigger", triggerModel);
ctxModel.put("vars", emptyMap());
Map<String, Object> expectedModel = singletonMap("ctx", ctxModel);
if (subject != null) {
when(engine.render(subject, expectedModel)).thenReturn(subject.getTemplate());

View File

@ -5,19 +5,19 @@
*/
package org.elasticsearch.watcher.actions.email.service;
import com.google.common.collect.ImmutableMap;
import org.joda.time.DateTime;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.test.ESTestCase;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
@ -43,8 +43,8 @@ public class EmailTests extends ESTestCase {
String subject = randomFrom("Random Subject", "", null);
String textBody = randomFrom("Random Body", "", null);
String htmlBody = randomFrom("<hr /><b>BODY</b><hr />", "", null);
ImmutableMap<String, Attachment> attachments = null;
ImmutableMap<String, Inline> inlines = null;
Map<String, Attachment> attachments = null;
Map<String, Inline> inlines = null;
Email email = new Email(id, from, replyTo, priority, sentDate, to, cc, bcc, subject, textBody, htmlBody, attachments, inlines);

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.actions.hipchat;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.MapBuilder;
@ -36,9 +35,14 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContextBuilder;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ -83,20 +87,18 @@ public class HipChatActionTests extends ESTestCase {
.metadata(metadata)
.buildMock();
Map<String, Object> expectedModel = ImmutableMap.<String, Object>builder()
.put("ctx", ImmutableMap.<String, Object>builder()
.put("id", ctx.id().value())
.put("watch_id", wid.watchId())
.put("payload", data)
.put("metadata", metadata)
.put("execution_time", now)
.put("trigger", ImmutableMap.<String, Object>builder()
.put("triggered_time", now)
.put("scheduled_time", now)
.build())
.put("vars", Collections.emptyMap())
.build())
.build();
Map<String, Object> triggerModel = new HashMap<>();
triggerModel.put("triggered_time", now);
triggerModel.put("scheduled_time", now);
Map<String, Object> ctxModel = new HashMap<>();
ctxModel.put("id", ctx.id().value());
ctxModel.put("watch_id", wid.watchId());
ctxModel.put("payload", data);
ctxModel.put("metadata", metadata);
ctxModel.put("execution_time", now);
ctxModel.put("trigger", triggerModel);
ctxModel.put("vars", Collections.emptyMap());
Map<String, Object> expectedModel = singletonMap("ctx", ctxModel);
if (body != null) {
when(templateEngine.render(body, expectedModel)).thenReturn(body.getTemplate());

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.watcher.actions.slack;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.MapBuilder;
@ -32,12 +31,21 @@ import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.watcher.actions.ActionBuilders.slackAction;
import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContextBuilder;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
@ -82,20 +90,18 @@ public class SlackActionTests extends ESTestCase {
.metadata(metadata)
.buildMock();
Map<String, Object> expectedModel = ImmutableMap.<String, Object>builder()
.put("ctx", ImmutableMap.<String, Object>builder()
.put("id", ctx.id().value())
.put("watch_id", wid.watchId())
.put("payload", data)
.put("metadata", metadata)
.put("execution_time", now)
.put("trigger", ImmutableMap.<String, Object>builder()
.put("triggered_time", now)
.put("scheduled_time", now)
.build())
.put("vars", Collections.emptyMap())
.build())
.build();
Map<String, Object> triggerModel = new HashMap<>();
triggerModel.put("triggered_time", now);
triggerModel.put("scheduled_time", now);
Map<String, Object> ctxModel = new HashMap<>();
ctxModel.put("id", ctx.id().value());
ctxModel.put("watch_id", wid.watchId());
ctxModel.put("payload", data);
ctxModel.put("metadata", metadata);
ctxModel.put("execution_time", now);
ctxModel.put("trigger", triggerModel);
ctxModel.put("vars", emptyMap());
Map<String, Object> expectedModel = singletonMap("ctx", ctxModel);
when(messageTemplate.render(eq(wid.watchId()), eq("_action"), eq(templateEngine), eq(expectedModel), any(SlackMessageDefaults.class))).thenReturn(message);
SlackAccount account = mock(SlackAccount.class);

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.watcher.support;
import com.google.common.collect.ImmutableMap;
import org.joda.time.DateTime;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.watcher.execution.WatchExecutionContext;
import org.elasticsearch.watcher.execution.Wid;
@ -14,13 +12,17 @@ import org.elasticsearch.watcher.test.WatcherTestUtils;
import org.elasticsearch.watcher.trigger.TriggerEvent;
import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent;
import org.elasticsearch.watcher.watch.Payload;
import org.joda.time.DateTime;
import org.junit.Test;
import java.util.Map;
import static org.joda.time.DateTimeZone.UTC;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.watcher.test.WatcherTestUtils.assertValue;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.joda.time.DateTimeZone.UTC;
/**
*
@ -32,8 +34,8 @@ public class VariablesTests extends ESTestCase {
DateTime scheduledTime = DateTime.now(UTC);
DateTime triggeredTime = scheduledTime.plusMillis(50);
DateTime executionTime = triggeredTime.plusMillis(50);
Payload payload = new Payload.Simple(ImmutableMap.<String, Object>builder().put("payload_key", "payload_value").build());
Map<String, Object> metatdata = ImmutableMap.<String, Object>builder().put("metadata_key", "metadata_value").build();
Payload payload = new Payload.Simple(singletonMap("payload_key", "payload_value"));
Map<String, Object> metatdata = singletonMap("metadata_key", "metadata_value");
TriggerEvent event = new ScheduleTriggerEvent("_watch_id", triggeredTime, scheduledTime);
Wid wid = new Wid("_watch_id", 0, executionTime);
WatchExecutionContext ctx = WatcherTestUtils.mockExecutionContextBuilder("_watch_id")

View File

@ -6,14 +6,17 @@
package org.elasticsearch.watcher.support;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESTestCase;
@ -21,7 +24,6 @@ import org.elasticsearch.watcher.input.search.ExecutableSearchInput;
import org.elasticsearch.watcher.support.clock.SystemClock;
import org.elasticsearch.watcher.support.text.TextTemplate;
import org.joda.time.DateTime;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
@ -29,30 +31,30 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.formatDate;
import static org.elasticsearch.watcher.support.WatcherUtils.DEFAULT_INDICES_OPTIONS;
import static org.elasticsearch.watcher.support.WatcherUtils.flattenModel;
import static org.elasticsearch.watcher.test.WatcherTestUtils.getRandomSupportedSearchType;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
/**
*
*/
public class WatcherUtilsTests extends ESTestCase {
@Test
public void testFlattenModel() throws Exception {
DateTime now = SystemClock.INSTANCE.nowUTC();
Map<String, Object> map = ImmutableMap.<String, Object>builder()
.put("a", ImmutableMap.builder().put("a1", new int[] { 0, 1, 2 }).build())
.put("b", new String[] { "b0", "b1", "b2" })
.put("c", Arrays.asList(TimeValue.timeValueSeconds(0), TimeValue.timeValueSeconds(1)))
.put("d", now)
.build();
Map<String, Object> map = new HashMap<>();
map.put("a", singletonMap("a1", new int[] { 0, 1, 2 }));
map.put("b", new String[] { "b0", "b1", "b2" });
map.put("c", Arrays.asList(TimeValue.timeValueSeconds(0), TimeValue.timeValueSeconds(1)));
map.put("d", now);
@SuppressWarnings("unchecked")
Map<String, String> result = (Map) flattenModel(map);
Map<String, Object> result = flattenModel(map);
assertThat(result.size(), is(9));
assertThat(result, hasEntry("a.a1.0", "0"));
assertThat(result, hasEntry("a.a1.1", "1"));
@ -65,7 +67,6 @@ public class WatcherUtilsTests extends ESTestCase {
assertThat(result, hasEntry("d", formatDate(now)));
}
@Test
public void testResponseToData() throws Exception {
final Map<String, Object> expected = new HashMap<>();
expected.put("key1", "val");
@ -89,7 +90,6 @@ public class WatcherUtilsTests extends ESTestCase {
assertThat(result, equalTo(expected));
}
@Test
public void testSerializeSearchRequest() throws Exception {
String[] randomIndices = generateRandomStringArray(5, 5, false);
SearchRequest expectedRequest = new SearchRequest(randomIndices);
@ -139,7 +139,6 @@ public class WatcherUtilsTests extends ESTestCase {
assertThat(result.templateSource(), equalTo(expectedRequest.templateSource()));
}
@Test
public void testDeserializeSearchRequest() throws Exception {
XContentBuilder builder = jsonBuilder().startObject();

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.watcher.transform.script;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
@ -33,6 +31,7 @@ import java.util.Collections;
import java.util.Map;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.watcher.support.Exceptions.illegalArgument;
import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD;
@ -81,9 +80,7 @@ public class ScriptTransformTests extends ESTestCase {
Map<String, Object> model = Variables.createCtxModel(ctx, payload);
Map<String, Object> transformed = ImmutableMap.<String, Object>builder()
.put("key", "value")
.build();
Map<String, Object> transformed = singletonMap("key", "value");
ExecutableScript executable = mock(ExecutableScript.class);
when(executable.run()).thenReturn(transformed);
@ -165,7 +162,7 @@ public class ScriptTransformTests extends ESTestCase {
XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes());
parser.nextToken();
ExecutableScriptTransform transform = new ScriptTransformFactory(Settings.EMPTY, service).parseExecutable("_id", parser);
Script script = scriptBuilder(type, "_script").lang("_lang").params(ImmutableMap.<String, Object>builder().put("key", "value").build()).build();
Script script = scriptBuilder(type, "_script").lang("_lang").params(singletonMap("key", "value")).build();
assertThat(transform.transform().getScript(), equalTo(script));
}

View File

@ -5,8 +5,6 @@
*/
package org.elasticsearch.watcher.transport.action.execute;
import com.google.common.collect.ImmutableMap;
import org.joda.time.DateTime;
import org.elasticsearch.watcher.client.WatcherClient;
import org.elasticsearch.watcher.execution.Wid;
import org.elasticsearch.watcher.support.WatcherDateTimeUtils;
@ -14,8 +12,12 @@ import org.elasticsearch.watcher.support.xcontent.XContentSource;
import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.watcher.transport.actions.execute.ExecuteWatchResponse;
import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse;
import org.joda.time.DateTime;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.watcher.actions.ActionBuilders.loggingAction;
import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder;
import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondition;
@ -53,12 +55,11 @@ public class ExecuteWatchWithDateMathTests extends AbstractWatcherIntegrationTes
DateTime triggeredTime = timeWarp().clock().nowUTC();
DateTime scheduledTime = triggeredTime.plusMinutes(1);
ExecuteWatchResponse response = watcherClient.prepareExecuteWatch("_id")
.setTriggerData(ImmutableMap.<String, Object>builder()
.put("triggered_time", "now")
.put("scheduled_time", "now+1m")
.build())
.get();
Map<String, Object> triggerData = new HashMap<>();
triggerData.put("triggered_time", "now");
triggerData.put("scheduled_time", "now+1m");
ExecuteWatchResponse response = watcherClient.prepareExecuteWatch("_id").setTriggerData(triggerData).get();
assertThat(response, notNullValue());
assertThat(response.getRecordId(), notNullValue());