From eb60d5925a515a641f0251a781488af7d0330e95 Mon Sep 17 00:00:00 2001 From: Nik Everett Date: Mon, 5 Oct 2015 09:11:02 -0400 Subject: [PATCH 1/4] Start banning ImmutableMap Original commit: elastic/x-pack-elasticsearch@b895e519441704d2bb3cf168994d2323e5682832 --- .../execution/TriggeredWatchStoreTests.java | 27 ++++++++++---- .../watcher/watch/WatchStoreTests.java | 37 ++++++++++++------- 2 files changed, 43 insertions(+), 21 deletions(-) diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java index 159fce115d8..f8932e2381b 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java @@ -15,7 +15,12 @@ import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; -import org.elasticsearch.cluster.routing.*; +import org.elasticsearch.cluster.routing.IndexRoutingTable; +import org.elasticsearch.cluster.routing.IndexShardRoutingTable; +import org.elasticsearch.cluster.routing.RoutingTable; +import org.elasticsearch.cluster.routing.ShardRoutingState; +import org.elasticsearch.cluster.routing.TestShardRouting; +import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; @@ -34,12 +39,18 @@ import org.junit.Test; import java.util.Collection; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.IsEqual.equalTo; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class TriggeredWatchStoreTests extends ESTestCase { @@ -100,7 +111,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); ClusterState cs = csBuilder.build(); assertThat(triggeredWatchStore.validate(cs), is(false)); @@ -133,7 +144,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); ClusterState cs = csBuilder.build(); assertThat(triggeredWatchStore.validate(cs), is(true)); @@ -168,7 +179,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); ClusterState cs = csBuilder.build(); RefreshResponse refreshResponse = mockRefreshResponse(1, 1); @@ -212,7 +223,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); ClusterState cs = csBuilder.build(); RefreshResponse refreshResponse = mockRefreshResponse(1, 1); @@ -255,7 +266,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); ClusterState cs = csBuilder.build(); RefreshResponse refreshResponse = mockRefreshResponse(1, 1); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java index d87cf0e7e95..7f1dba418b9 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java @@ -5,6 +5,19 @@ */ package org.elasticsearch.watcher.watch; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import java.util.Collections; + import org.elasticsearch.Version; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; @@ -15,7 +28,12 @@ import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; -import org.elasticsearch.cluster.routing.*; +import org.elasticsearch.cluster.routing.IndexRoutingTable; +import org.elasticsearch.cluster.routing.IndexShardRoutingTable; +import org.elasticsearch.cluster.routing.RoutingTable; +import org.elasticsearch.cluster.routing.ShardRoutingState; +import org.elasticsearch.cluster.routing.TestShardRouting; +import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; @@ -30,13 +48,6 @@ import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.junit.Before; import org.junit.Test; -import java.util.Collections; - -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - /** */ public class WatchStoreTests extends ESTestCase { @@ -86,7 +97,7 @@ public class WatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); ClusterState cs = csBuilder.build(); assertThat(watchStore.validate(cs), is(false)); @@ -110,7 +121,7 @@ public class WatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); RefreshResponse refreshResponse = mockRefreshResponse(1, 0); when(clientProxy.refresh(any(RefreshRequest.class))).thenReturn(refreshResponse); @@ -145,7 +156,7 @@ public class WatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); RefreshResponse refreshResponse = mockRefreshResponse(1, 1); when(clientProxy.refresh(any(RefreshRequest.class))).thenReturn(refreshResponse); @@ -184,7 +195,7 @@ public class WatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); RefreshResponse refreshResponse = mockRefreshResponse(1, 1); when(clientProxy.refresh(any(RefreshRequest.class))).thenReturn(refreshResponse); @@ -221,7 +232,7 @@ public class WatchStoreTests extends ESTestCase { indexRoutingTableBuilder.addReplica(); routingTableBuilder.add(indexRoutingTableBuilder.build()); csBuilder.metaData(metaDateBuilder); - csBuilder.routingTable(routingTableBuilder); + csBuilder.routingTable(routingTableBuilder.build()); RefreshResponse refreshResponse = mockRefreshResponse(1, 1); when(clientProxy.refresh(any(RefreshRequest.class))).thenReturn(refreshResponse); From 1d61278b2d84a8749b8f8bd6306cfdf0fb955037 Mon Sep 17 00:00:00 2001 From: Nik Everett Date: Mon, 5 Oct 2015 12:54:40 -0400 Subject: [PATCH 2/4] More ImmutableMap banning Original commit: elastic/x-pack-elasticsearch@59fee6e288c3570c8d80e959af995a4dea029c8e --- .../authc/esusers/FileUserPasswdStore.java | 12 ++-- .../authc/esusers/FileUserRolesStore.java | 18 ++++-- .../shield/authc/support/DnRoleMapper.java | 22 +++++--- .../shield/authz/Permission.java | 10 ++-- .../shield/transport/filter/IPFilter.java | 13 ++++- .../integration/ClusterPrivilegeTests.java | 20 +++---- .../integration/IndexPrivilegeTests.java | 28 ++-------- .../esusers/FileUserPasswdStoreTests.java | 28 ++++------ .../authc/support/DnRoleMapperTests.java | 33 +++++------ ...dIndexSearcherWrapperIntegrationTests.java | 5 +- .../ShieldIndexSearcherWrapperUnitTests.java | 7 +-- ...ServerTransportFilterIntegrationTests.java | 4 +- .../watcher/actions/ActionRegistry.java | 5 +- .../watcher/condition/ConditionRegistry.java | 5 +- .../watcher/input/InputRegistry.java | 5 +- .../support/WatcherIndexTemplateRegistry.java | 19 +++---- .../support/http/HttpRequestTemplate.java | 18 +++--- .../watcher/support/http/HttpResponse.java | 18 +++--- .../support/http/auth/HttpAuthRegistry.java | 5 +- .../support/xcontent/WatcherParams.java | 15 +++-- .../watcher/transform/TransformRegistry.java | 3 +- .../trigger/schedule/ScheduleRegistry.java | 6 +- .../watcher/WatcherServiceTests.java | 26 +++++---- .../actions/email/DataAttachmentTests.java | 9 ++- .../actions/index/IndexActionTests.java | 11 ++-- .../actions/logging/LoggingActionTests.java | 36 ++++++------ .../actions/webhook/WebhookActionTests.java | 31 ++++++---- .../compare/CompareConditionTests.java | 12 ++-- .../script/ScriptConditionTests.java | 9 +-- .../execution/ExecutionServiceTests.java | 42 +++++++++----- .../watcher/input/InputRegistryTests.java | 6 +- .../watcher/input/http/HttpInputTests.java | 38 ++++++++----- .../input/search/SearchInputTests.java | 18 +++--- .../watcher/support/http/HttpClientTests.java | 17 +++--- .../http/HttpRequestTemplateTests.java | 14 +++-- .../support/http/HttpResponseTests.java | 7 ++- .../support/text/TextTemplateTests.java | 26 +++++---- .../text/xmustache/XMustacheTests.java | 8 +-- .../support/xcontent/MapPathTests.java | 24 ++++---- .../watcher/test/WatcherTestUtils.java | 37 ++++++++---- .../bench/ScheduleEngineTriggerBenchmark.java | 15 ++++- .../transform/chain/ChainTransformTests.java | 15 +++-- .../search/SearchTransformTests.java | 24 ++++++-- .../action/execute/ExecuteWatchTests.java | 8 +-- .../watcher/watch/WatchTests.java | 56 +++++++++---------- 45 files changed, 437 insertions(+), 351 deletions(-) diff --git a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java index b3becf452d4..072e9f3248d 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java +++ b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java @@ -6,6 +6,7 @@ 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; @@ -32,6 +33,7 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; +import static java.util.Collections.emptyMap; import static org.elasticsearch.shield.support.ShieldFiles.openAtomicMoveWriter; /** @@ -44,7 +46,7 @@ public class FileUserPasswdStore { private final Path file; final Hasher hasher = Hasher.BCRYPT; - private volatile ImmutableMap users; + private volatile Map users; private CopyOnWriteArrayList listeners; @@ -105,12 +107,12 @@ public class FileUserPasswdStore { * Internally in this class, we try to load the file, but if for some reason we can't, we're being more lenient by * logging the error and skipping all users. This is aligned with how we handle other auto-loaded files in shield. */ - static ImmutableMap parseFileLenient(Path path, ESLogger logger) { + static Map parseFileLenient(Path path, ESLogger logger) { try { return parseFile(path, logger); } catch (Throwable t) { logger.error("failed to parse users file [{}]. skipping/removing all users...", t, path.toAbsolutePath()); - return ImmutableMap.of(); + return emptyMap(); } } @@ -118,14 +120,14 @@ public class FileUserPasswdStore { * parses the esusers file. Should never return {@code null}, if the file doesn't exist an * empty map is returned */ - public static ImmutableMap parseFile(Path path, @Nullable ESLogger logger) { + public static Map parseFile(Path path, @Nullable ESLogger logger) { if (logger == null) { logger = NoOpLogger.INSTANCE; } logger.trace("reading users file [{}]...", path.toAbsolutePath()); if (!Files.exists(path)) { - return ImmutableMap.of(); + return emptyMap(); } List lines; diff --git a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java index 3b4e0299b99..ec1bc9d17bd 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java +++ b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java @@ -6,6 +6,7 @@ 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; @@ -26,10 +27,15 @@ import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Pattern; +import static java.util.Collections.emptyMap; import static org.elasticsearch.shield.support.ShieldFiles.openAtomicMoveWriter; /** @@ -43,7 +49,7 @@ public class FileUserRolesStore { private final Path file; private CopyOnWriteArrayList listeners; - private volatile ImmutableMap userRoles; + private volatile Map userRoles; public FileUserRolesStore(RealmConfig config, ResourceWatcherService watcherService) { this(config, watcherService, null); @@ -95,12 +101,12 @@ public class FileUserRolesStore { * Internally in this class, we try to load the file, but if for some reason we can't, we're being more lenient by * logging the error and skipping all enries. This is aligned with how we handle other auto-loaded files in shield. */ - static ImmutableMap parseFileLenient(Path path, ESLogger logger) { + static Map parseFileLenient(Path path, ESLogger logger) { try { return parseFile(path, logger); } catch (Throwable t) { logger.error("failed to parse users_roles file [{}]. skipping/removing all entries...", t, path.toAbsolutePath()); - return ImmutableMap.of(); + return emptyMap(); } } @@ -109,7 +115,7 @@ public class FileUserRolesStore { * an empty map is returned. The read file holds a mapping per line of the form "role -> users" while the returned * map holds entries of the form "user -> roles". */ - public static ImmutableMap parseFile(Path path, @Nullable ESLogger logger) { + public static Map parseFile(Path path, @Nullable ESLogger logger) { if (logger == null) { logger = NoOpLogger.INSTANCE; } @@ -117,7 +123,7 @@ public class FileUserRolesStore { if (!Files.exists(path)) { - return ImmutableMap.of(); + return emptyMap(); } List lines; diff --git a/shield/src/main/java/org/elasticsearch/shield/authc/support/DnRoleMapper.java b/shield/src/main/java/org/elasticsearch/shield/authc/support/DnRoleMapper.java index 2ae57e97ceb..9c235f873c2 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authc/support/DnRoleMapper.java +++ b/shield/src/main/java/org/elasticsearch/shield/authc/support/DnRoleMapper.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.shield.authc.support; -import com.google.common.collect.ImmutableMap; import com.unboundid.ldap.sdk.DN; import com.unboundid.ldap.sdk.LDAPException; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.logging.ESLogger; @@ -23,9 +23,15 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.shield.authc.ldap.support.LdapUtils.dn; import static org.elasticsearch.shield.authc.ldap.support.LdapUtils.relativeName; @@ -44,7 +50,7 @@ public class DnRoleMapper { private final String realmType; private final Path file; private final boolean useUnmappedGroupsAsRoles; - protected volatile ImmutableMap> dnRoles; + protected volatile Map> dnRoles; private CopyOnWriteArrayList listeners; @@ -86,21 +92,21 @@ public class DnRoleMapper { * logging the error and skipping/removing all mappings. This is aligned with how we handle other auto-loaded files * in shield. */ - public static ImmutableMap> parseFileLenient(Path path, ESLogger logger, String realmType, String realmName) { + public static Map> parseFileLenient(Path path, ESLogger logger, String realmType, String realmName) { try { return parseFile(path, logger, realmType, realmName); } catch (Throwable t) { logger.error("failed to parse role mappings file [{}]. skipping/removing all mappings...", t, path.toAbsolutePath()); - return ImmutableMap.of(); + return emptyMap(); } } - public static ImmutableMap> parseFile(Path path, ESLogger logger, String realmType, String realmName) { + public static Map> parseFile(Path path, ESLogger logger, String realmType, String realmName) { logger.trace("reading realm [{}/{}] role mappings file [{}]...", realmType, realmName, path.toAbsolutePath()); if (!Files.exists(path)) { - return ImmutableMap.of(); + return emptyMap(); } try (InputStream in = Files.newInputStream(path)) { @@ -131,7 +137,7 @@ public class DnRoleMapper { logger.warn("no mappings found in role mappings file [{}] for realm [{}/{}]", path.toAbsolutePath(), realmType, realmName); } - return ImmutableMap.copyOf(dnToRoles); + return unmodifiableMap(dnToRoles); } catch (IOException e) { throw new ElasticsearchException("could not read realm [" + realmType + "/" + realmName + "] role mappings file [" + path.toAbsolutePath() + "]", e); diff --git a/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java b/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java index 277b3962a5a..fbf94899a52 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java +++ b/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java @@ -30,6 +30,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; +import static java.util.Collections.emptyMap; +import static java.util.Collections.unmodifiableMap; import static java.util.Collections.unmodifiableSet; /** @@ -443,9 +445,9 @@ public interface Permission { } @Override - public ImmutableMap authorize(String action, Set requestedIndicesOrAliases, MetaData metaData) { + public Map authorize(String action, Set requestedIndicesOrAliases, MetaData metaData) { if (isEmpty()) { - return ImmutableMap.of(); + return emptyMap(); } // What this code does is just merge `IndexAccessControl` instances from the permissions this class holds: @@ -466,9 +468,9 @@ public interface Permission { } } if (indicesAccessControl == null) { - return ImmutableMap.of(); + return emptyMap(); } else { - return ImmutableMap.copyOf(indicesAccessControl); + return unmodifiableMap(indicesAccessControl); } } diff --git a/shield/src/main/java/org/elasticsearch/shield/transport/filter/IPFilter.java b/shield/src/main/java/org/elasticsearch/shield/transport/filter/IPFilter.java index 5af4cf576c2..9cbc69811cd 100644 --- a/shield/src/main/java/org/elasticsearch/shield/transport/filter/IPFilter.java +++ b/shield/src/main/java/org/elasticsearch/shield/transport/filter/IPFilter.java @@ -6,7 +6,7 @@ package org.elasticsearch.shield.transport.filter; import com.carrotsearch.hppc.ObjectObjectHashMap; -import com.google.common.collect.ImmutableMap; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.collect.HppcMaps; import org.elasticsearch.common.component.AbstractLifecycleComponent; @@ -23,7 +23,14 @@ import org.elasticsearch.shield.audit.AuditTrail; import org.elasticsearch.transport.Transport; import java.net.InetAddress; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static java.util.Collections.unmodifiableMap; public class IPFilter extends AbstractLifecycleComponent { @@ -174,7 +181,7 @@ public class IPFilter extends AbstractLifecycleComponent { } logger.debug("loaded ip filtering profiles: {}", profileRules.keySet()); - return ImmutableMap.copyOf(profileRules); + return unmodifiableMap(profileRules); } private ShieldIpFilterRule[] createRules(String[] allow, String[] deny, TransportAddress[] boundAddresses) { diff --git a/shield/src/test/java/org/elasticsearch/integration/ClusterPrivilegeTests.java b/shield/src/test/java/org/elasticsearch/integration/ClusterPrivilegeTests.java index e91b850f456..e06c0ec0f0e 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ClusterPrivilegeTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ClusterPrivilegeTests.java @@ -5,22 +5,21 @@ */ package org.elasticsearch.integration; -import com.google.common.collect.ImmutableMap; - import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse; import org.elasticsearch.cluster.SnapshotsInProgress; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.Node; +import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.junit.annotations.TestLogging; import org.junit.AfterClass; import org.junit.BeforeClass; -import org.junit.Test; import java.nio.file.Path; +import java.util.Map; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.test.ESIntegTestCase.ClusterScope; import static org.elasticsearch.test.ESIntegTestCase.Scope.TEST; @ClusterScope(scope = TEST) @@ -83,7 +82,6 @@ public class ClusterPrivilegeTests extends AbstractPrivilegeTestCase { return super.configUsersRoles() + USERS_ROLES; } - @Test @TestLogging("org.elasticsearch.test.rest.client.http:TRACE") public void testThatClusterPrivilegesWorkAsExpectedViaHttp() throws Exception { // user_a can do all the things @@ -124,7 +122,6 @@ public class ClusterPrivilegeTests extends AbstractPrivilegeTestCase { assertAccessIsDenied("user_c", "PUT", "/_cluster/settings", "{ \"transient\" : { \"indices.ttl.interval\": \"1m\" } }"); } - @Test @TestLogging("org.elasticsearch.test.rest.client.http:TRACE") public void testThatSnapshotAndRestore() throws Exception { String repoJson = jsonBuilder().startObject().field("type", "fs").startObject("settings").field("location", repositoryLocation.toString()).endObject().endObject().string(); @@ -132,7 +129,7 @@ public class ClusterPrivilegeTests extends AbstractPrivilegeTestCase { assertAccessIsDenied("user_c", "PUT", "/_snapshot/my-repo", repoJson); assertAccessIsAllowed("user_a", "PUT", "/_snapshot/my-repo", repoJson); - ImmutableMap params = ImmutableMap.of("refresh", "true"); + Map params = singletonMap("refresh", "true"); assertAccessIsDenied("user_a", "PUT", "/someindex/bar/1", "{ \"name\" : \"elasticsearch\" }", params); assertAccessIsDenied("user_b", "PUT", "/someindex/bar/1", "{ \"name\" : \"elasticsearch\" }", params); assertAccessIsAllowed("user_c", "PUT", "/someindex/bar/1", "{ \"name\" : \"elasticsearch\" }", params); @@ -152,11 +149,10 @@ public class ClusterPrivilegeTests extends AbstractPrivilegeTestCase { assertAccessIsDenied("user_b", "DELETE", "/someindex"); assertAccessIsAllowed("user_c", "DELETE", "/someindex"); - ImmutableMap restoreParams = ImmutableMap.of("wait_for_completion", "true"); - assertAccessIsDenied("user_b", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, restoreParams); - assertAccessIsDenied("user_c", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, restoreParams); - - assertAccessIsAllowed("user_a", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, restoreParams); + params = singletonMap("wait_for_completion", "true"); + assertAccessIsDenied("user_b", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, params); + assertAccessIsDenied("user_c", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, params); + assertAccessIsAllowed("user_a", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, params); assertAccessIsDenied("user_a", "GET", "/someindex/bar/1"); assertAccessIsDenied("user_b", "GET", "/someindex/bar/1"); diff --git a/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java b/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java index be0e63840b8..fcfc296eda7 100644 --- a/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java @@ -5,16 +5,16 @@ */ package org.elasticsearch.integration; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.Node; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.junit.Before; -import org.junit.Test; import java.util.HashMap; import java.util.Locale; +import java.util.Map; +import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.is; public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { @@ -138,14 +138,13 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { @Before public void insertBaseDocumentsAsAdmin() throws Exception { // indices: a,b,c,abc - ImmutableMap params = ImmutableMap.of("refresh", "true"); + Map params = singletonMap("refresh", "true"); assertAccessIsAllowed("admin", "PUT", "/a/foo/1", jsonDoc, params); assertAccessIsAllowed("admin", "PUT", "/b/foo/1", jsonDoc, params); assertAccessIsAllowed("admin", "PUT", "/c/foo/1", jsonDoc, params); assertAccessIsAllowed("admin", "PUT", "/abc/foo/1", jsonDoc, params); } - @Test public void testUserU1() throws Exception { // u1 has all_a_role and read_a_role assertUserIsAllowed("u1", "all", "a"); @@ -153,7 +152,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u1", "all", "c"); } - @Test public void testUserU2() throws Exception { // u2 has all_all and read a/b role assertUserIsAllowed("u2", "all", "a"); @@ -164,7 +162,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u2", "all", "c"); } - @Test public void testUserU3() throws Exception { // u3 has get b role, but all access to a* and b* via regex assertUserIsAllowed("u3", "all", "a"); @@ -172,7 +169,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u3", "all", "c"); } - @Test public void testUserU4() throws Exception { // u4 has read access to a/b and manage access to a* assertUserIsAllowed("u4", "read", "a"); @@ -189,7 +185,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsAllowed("u4", "manage", "an_index"); } - @Test public void testUserU5() throws Exception { // u5 may read a and get b assertUserIsAllowed("u5", "read", "a"); @@ -202,7 +197,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertAccessIsDenied("u5", "GET", "/b/_search"); } - @Test public void testUserU6() throws Exception { // u6 has all access on a and search access on b assertUserIsAllowed("u6", "all", "a"); @@ -212,7 +206,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u6", "all", "c"); } - @Test public void testUserU7() throws Exception { // no access at all assertUserIsDenied("u7", "all", "a"); @@ -220,7 +213,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u7", "all", "c"); } - @Test public void testUserU8() throws Exception { // u8 has admin access and get access on b assertUserIsAllowed("u8", "all", "a"); @@ -228,7 +220,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsAllowed("u8", "all", "c"); } - @Test public void testUserU9() throws Exception { // u9 has write access to a and read access to a/b assertUserIsAllowed("u9", "crud", "a"); @@ -239,7 +230,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u9", "all", "c"); } - @Test public void testUserU10() throws Exception { // u10 has access on get/search on b assertUserIsDenied("u10", "all", "a"); @@ -249,7 +239,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u10", "all", "c"); } - @Test public void testUserU11() throws Exception { // u11 has access to create c and delete b assertUserIsDenied("u11", "all", "a"); @@ -265,7 +254,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u11", "monitor", "c"); } - @Test public void testUserU12() throws Exception { // u12 has data_access to all indices+ crud access to a assertUserIsDenied("u12", "manage", "a"); @@ -276,7 +264,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsAllowed("u12", "data_access", "c"); } - @Test public void testUserU13() throws Exception { // u13 has search access on b and index access on a assertUserIsDenied("u13", "manage", "a"); @@ -291,7 +278,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u13", "all", "c"); } - @Test public void testUserU14() throws Exception { // u14 has access to read a and monitor b assertUserIsDenied("u14", "manage", "a"); @@ -306,7 +292,6 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u14", "all", "c"); } - @Test public void testUserU15() throws Exception { //u15 has access to manage and search a, so that adding warmer templates work assertUserIsAllowed("u15", "manage", "a"); @@ -318,14 +303,13 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertUserIsDenied("u15", "all", "c"); } - @Test public void testThatUnknownUserIsRejectedProperly() throws Exception { HttpResponse response = executeRequest("idonotexist", "GET", "/", null, new HashMap<>()); assertThat(response.getStatusCode(), is(401)); } private void assertUserExecutes(String user, String action, String index, boolean userIsAllowed) throws Exception { - ImmutableMap refreshParams = ImmutableMap.of("refresh", "true"); + Map refreshParams = singletonMap("refresh", "true"); switch (action) { case "all" : @@ -353,7 +337,7 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { // wait until index ready, but as admin client().admin().cluster().prepareHealth(index).setWaitForGreenStatus().get(); assertAccessIsAllowed(user, "POST", "/" + index + "/_refresh"); - ImmutableMap analyzeParams = ImmutableMap.of("text", "test"); + Map analyzeParams = singletonMap("text", "test"); assertAccessIsAllowed(user, "GET", "/" + index + "/_analyze", null, analyzeParams); assertAccessIsAllowed(user, "POST", "/" + index + "/_flush"); assertAccessIsAllowed(user, "POST", "/" + index + "/_optimize"); @@ -374,7 +358,7 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { assertAccessIsDenied(user, "DELETE", "/" + index); assertUserIsDenied(user, "create_index", index); assertAccessIsDenied(user, "POST", "/" + index + "/_refresh"); - ImmutableMap analyzeParams = ImmutableMap.of("text", "test"); + Map analyzeParams = singletonMap("text", "test"); assertAccessIsDenied(user, "GET", "/" + index + "/_analyze", null, analyzeParams); assertAccessIsDenied(user, "POST", "/" + index + "/_flush"); assertAccessIsDenied(user, "POST", "/" + index + "/_optimize"); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStoreTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStoreTests.java index 26597f39938..428f5def1de 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStoreTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStoreTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.shield.authc.esusers; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.settings.Settings; @@ -20,7 +19,6 @@ import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; @@ -35,9 +33,17 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.contains; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Matchers.contains; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * @@ -63,7 +69,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { terminate(threadPool); } - @Test public void testStore_ConfiguredWithUnreadableFile() throws Exception { Path file = createTempFile(); @@ -81,7 +86,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(store.usersCount(), is(0)); } - @Test public void testStore_AutoReload() throws Exception { Path users = getDataPath("users"); Path tmp = createTempFile(); @@ -121,7 +125,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(store.verifyPassword("foobar", SecuredStringTests.build("barfoo")), is(true)); } - @Test public void testStore_AutoReload_WithParseFailures() throws Exception { Path users = getDataPath("users"); Path tmp = createTempFile(); @@ -157,7 +160,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(store.usersCount(), is(0)); } - @Test public void testParseFile() throws Exception { Path path = getDataPath("users"); Map users = FileUserPasswdStore.parseFile(path, null); @@ -177,17 +179,15 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(new String(users.get("sha")), equalTo("{SHA}cojt0Pw//L6ToM8G41aOKFIWh7w=")); } - @Test public void testParseFile_Empty() throws Exception { Path empty = createTempFile(); ESLogger log = ESLoggerFactory.getLogger("test"); log = spy(log); - ImmutableMap users = FileUserPasswdStore.parseFile(empty, log); + Map users = FileUserPasswdStore.parseFile(empty, log); assertThat(users.isEmpty(), is(true)); verify(log, times(1)).warn(contains("no users found"), eq(empty)); } - @Test public void testParseFile_WhenFileDoesNotExist() throws Exception { Path file = createTempDir().resolve(randomAsciiOfLength(10)); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.INFO); @@ -196,7 +196,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(users.isEmpty(), is(true)); } - @Test public void testParseFile_WhenCannotReadFile() throws Exception { Path file = createTempFile(); // writing in utf_16 should cause a parsing error as we try to read the file in utf_8 @@ -210,7 +209,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { } } - @Test public void testParseFile_InvalidLineDoesNotResultInLoggerNPE() throws Exception { Path file = createTempFile(); Files.write(file, Arrays.asList("NotValidUsername=Password", "user:pass"), StandardCharsets.UTF_8); @@ -219,7 +217,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(users.keySet(), hasSize(1)); } - @Test public void testParseFileLenient_WhenCannotReadFile() throws Exception { Path file = createTempFile(); // writing in utf_16 should cause a parsing error as we try to read the file in utf_8 @@ -233,7 +230,6 @@ public class FileUserPasswdStoreTests extends ESTestCase { assertThat(msgs.get(0).text, containsString("failed to parse users file")); } - @Test public void testParseFileWithLineWithEmptyPasswordAndWhitespace() throws Exception { Path file = createTempFile(); Files.write(file, Collections.singletonList("user: "), StandardCharsets.UTF_8); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/support/DnRoleMapperTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/support/DnRoleMapperTests.java index 6147138333b..2dece894ad3 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/support/DnRoleMapperTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/support/DnRoleMapperTests.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.shield.authc.support; -import com.google.common.collect.ImmutableMap; import com.unboundid.ldap.sdk.DN; + import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.shield.audit.logfile.CapturingLogger; @@ -18,7 +18,6 @@ import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; @@ -29,11 +28,20 @@ import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @@ -70,7 +78,6 @@ public class DnRoleMapperTests extends ESTestCase { terminate(threadPool); } - @Test public void testMapper_ConfiguredWithUnreadableFile() throws Exception { Path file = createTempFile(); // writing in utf_16 should cause a parsing error as we try to read the file in utf_8 @@ -81,7 +88,6 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(mapper.mappingsCount(), is(0)); } - @Test public void testMapper_AutoReload() throws Exception { Path roleMappingFile = getDataPath("role_mapping.yml"); Path file = env.binFile().getParent().resolve("test_role_mapping.yml"); @@ -121,7 +127,6 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(roles, contains("fantastic_four")); } - @Test public void testMapper_AutoReload_WithParseFailures() throws Exception { Path roleMappingFile = getDataPath("role_mapping.yml"); Path file = env.binFile().getParent().resolve("test_role_mapping.yml"); @@ -155,11 +160,10 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(mapper.mappingsCount(), is(0)); } - @Test public void testParseFile() throws Exception { Path file = getDataPath("role_mapping.yml"); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.INFO); - ImmutableMap> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name"); + Map> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name"); assertThat(mappings, notNullValue()); assertThat(mappings.size(), is(3)); @@ -185,11 +189,10 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(roles, contains("avenger")); } - @Test public void testParseFile_Empty() throws Exception { Path file = createTempFile(); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.INFO); - ImmutableMap> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name"); + Map> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name"); assertThat(mappings, notNullValue()); assertThat(mappings.isEmpty(), is(true)); List msgs = logger.output(CapturingLogger.Level.WARN); @@ -197,16 +200,14 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(msgs.get(0).text, containsString("no mappings found")); } - @Test public void testParseFile_WhenFileDoesNotExist() throws Exception { Path file = createTempDir().resolve(randomAsciiOfLength(10)); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.INFO); - ImmutableMap> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name"); + Map> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name"); assertThat(mappings, notNullValue()); assertThat(mappings.isEmpty(), is(true)); } - @Test public void testParseFile_WhenCannotReadFile() throws Exception { Path file = createTempFile(); // writing in utf_16 should cause a parsing error as we try to read the file in utf_8 @@ -220,13 +221,12 @@ public class DnRoleMapperTests extends ESTestCase { } } - @Test public void testParseFileLenient_WhenCannotReadFile() throws Exception { Path file = createTempFile(); // writing in utf_16 should cause a parsing error as we try to read the file in utf_8 Files.write(file, Collections.singletonList("aldlfkjldjdflkjd"), StandardCharsets.UTF_16); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.INFO); - ImmutableMap> mappings = DnRoleMapper.parseFileLenient(file, logger, "_type", "_name"); + Map> mappings = DnRoleMapper.parseFileLenient(file, logger, "_type", "_name"); assertThat(mappings, notNullValue()); assertThat(mappings.isEmpty(), is(true)); List msgs = logger.output(CapturingLogger.Level.ERROR); @@ -234,7 +234,6 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(msgs.get(0).text, containsString("failed to parse role mappings file")); } - @Test public void testYaml() throws Exception { Path file = getDataPath("role_mapping.yml"); Settings ldapSettings = Settings.settingsBuilder() @@ -250,7 +249,6 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(roles, hasItems("shield", "avenger")); } - @Test public void testRelativeDN() { Settings ldapSettings = Settings.builder() .put(DnRoleMapper.USE_UNMAPPED_GROUPS_AS_ROLES_SETTING, true) @@ -263,7 +261,6 @@ public class DnRoleMapperTests extends ESTestCase { assertThat(roles, hasItems("genius", "billionaire", "playboy", "philanthropist", "shield", "avengers")); } - @Test public void testUserDNMapping() throws Exception { Path file = getDataPath("role_mapping.yml"); Settings ldapSettings = Settings.builder() diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperIntegrationTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperIntegrationTests.java index c250af7967d..dfe6818be90 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperIntegrationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperIntegrationTests.java @@ -5,8 +5,6 @@ */ package org.elasticsearch.shield.authz.accesscontrol; -import com.google.common.collect.ImmutableMap; - import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; @@ -51,6 +49,7 @@ import java.util.Collection; import java.util.Collections; import static java.util.Collections.singleton; +import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; @@ -76,7 +75,7 @@ public class ShieldIndexSearcherWrapperIntegrationTests extends ESTestCase { TransportRequest request = new TransportRequest.Empty(); RequestContext.setCurrent(new RequestContext(request)); IndicesAccessControl.IndexAccessControl indexAccessControl = new IndicesAccessControl.IndexAccessControl(true, null, singleton(new BytesArray("{}"))); - request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, ImmutableMap.of("_index", indexAccessControl))); + request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, singletonMap("_index", indexAccessControl))); IndexQueryParserService parserService = mock(IndexQueryParserService.class); IndicesLifecycle indicesLifecycle = mock(IndicesLifecycle.class); diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperUnitTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperUnitTests.java index f627bb0122b..4ff7fb22f19 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperUnitTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/accesscontrol/ShieldIndexSearcherWrapperUnitTests.java @@ -5,8 +5,6 @@ */ package org.elasticsearch.shield.authz.accesscontrol; -import com.google.common.collect.ImmutableMap; - import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; @@ -59,6 +57,7 @@ import java.io.IOException; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.shield.authz.accesscontrol.ShieldIndexSearcherWrapper.intersectScorerAndRoleBits; import static org.hamcrest.Matchers.equalTo; @@ -114,7 +113,7 @@ public class ShieldIndexSearcherWrapperUnitTests extends ESTestCase { mapperService.merge("type", new CompressedXContent(mappingSource.string()), false, false); IndicesAccessControl.IndexAccessControl indexAccessControl = new IndicesAccessControl.IndexAccessControl(true, emptySet(), null); - request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, ImmutableMap.of("_index", indexAccessControl))); + request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, singletonMap("_index", indexAccessControl))); FieldSubsetReader.FieldSubsetDirectoryReader result = (FieldSubsetReader.FieldSubsetDirectoryReader) shieldIndexSearcherWrapper.wrap(esIn); assertThat(result.getFieldNames().size(), equalTo(11)); @@ -324,7 +323,7 @@ public class ShieldIndexSearcherWrapperUnitTests extends ESTestCase { private void assertResolvedFields(String expression, String... expectedFields) { IndicesAccessControl.IndexAccessControl indexAccessControl = new IndicesAccessControl.IndexAccessControl(true, singleton(expression), null); - request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, ImmutableMap.of("_index", indexAccessControl))); + request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, singletonMap("_index", indexAccessControl))); FieldSubsetReader.FieldSubsetDirectoryReader result = (FieldSubsetReader.FieldSubsetDirectoryReader) shieldIndexSearcherWrapper.wrap(esIn); assertThat(result.getFieldNames().size() - shieldIndexSearcherWrapper.getAllowedMetaFields().size(), equalTo(expectedFields.length)); for (String expectedField : expectedFields) { diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java index 1f17e56b209..6a69d1f32e1 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.shield.transport; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.Version; import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.settings.Settings; @@ -29,6 +28,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.shield.test.ShieldTestUtils.createFolder; import static org.elasticsearch.shield.test.ShieldTestUtils.writeFile; @@ -151,7 +151,7 @@ public class ServerTransportFilterIntegrationTests extends ShieldIntegTestCase { // wait for a timeout, because as long as the node is not connected to the cluster // the license is disabled and therefore blocking health & stats calls. node.client().admin().cluster().prepareUpdateSettings() - .setTransientSettings(ImmutableMap.of("key", "value")) + .setTransientSettings(singletonMap("key", "value")) .setMasterNodeTimeout(TimeValue.timeValueSeconds(2)) .get(); fail("Expected to fail update settings as the node should not be able to connect to the cluster, and therefore there should be no master"); diff --git a/watcher/src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java index 6999defd9ae..e99306e7a65 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/actions/ActionRegistry.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.actions; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -23,14 +22,14 @@ import java.util.Map; */ public class ActionRegistry { - private final ImmutableMap parsers; + private final Map parsers; private final TransformRegistry transformRegistry; private final Clock clock; private final LicenseService licenseService; @Inject public ActionRegistry(Map parsers, TransformRegistry transformRegistry, Clock clock, LicenseService licenseService) { - this.parsers = ImmutableMap.copyOf(parsers); + this.parsers = parsers; this.transformRegistry = transformRegistry; this.clock = clock; this.licenseService = licenseService; diff --git a/watcher/src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java index 0958267fb88..c284a7b183f 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/condition/ConditionRegistry.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.condition; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.ToXContent; @@ -21,11 +20,11 @@ import java.util.Set; */ public class ConditionRegistry { - private final ImmutableMap factories; + private final Map factories; @Inject public ConditionRegistry(Map factories) { - this.factories = ImmutableMap.copyOf(factories); + this.factories = factories; } public Set types() { diff --git a/watcher/src/main/java/org/elasticsearch/watcher/input/InputRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/input/InputRegistry.java index b22951cfef7..d1aa5b93725 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/input/InputRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/input/InputRegistry.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.input; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -18,11 +17,11 @@ import java.util.Map; */ public class InputRegistry { - private final ImmutableMap factories; + private final Map factories; @Inject public InputRegistry(Map factories) { - this.factories = ImmutableMap.copyOf(factories); + this.factories = factories; } /** diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistry.java index 559dc70879d..51c4b12f423 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistry.java @@ -5,15 +5,12 @@ */ package org.elasticsearch.watcher.support; -import com.google.common.collect.ImmutableMap; - import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest; import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateListener; -import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.Streams; @@ -26,11 +23,13 @@ import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.elasticsearch.watcher.watch.WatchStore; import java.io.InputStream; +import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; +import static java.util.Collections.unmodifiableMap; import static java.util.Collections.unmodifiableSet; /** @@ -43,7 +42,7 @@ public class WatcherIndexTemplateRegistry extends AbstractComponent implements C private final ClusterService clusterService; private final Set indexTemplates; - private volatile ImmutableMap customIndexSettings; + private volatile Map customIndexSettings; @Inject public WatcherIndexTemplateRegistry(Settings settings, NodeSettingsService nodeSettingsService, ClusterService clusterService, @@ -56,12 +55,12 @@ public class WatcherIndexTemplateRegistry extends AbstractComponent implements C clusterService.add(this); nodeSettingsService.addListener(this); - ImmutableMap.Builder customIndexSettingsBuilder = ImmutableMap.builder(); + Map customIndexSettings = new HashMap<>(); for (TemplateConfig indexTemplate : indexTemplates) { Settings customSettings = this.settings.getAsSettings(indexTemplate.getSettingsPrefix()); - customIndexSettings = customIndexSettingsBuilder.put(indexTemplate.getSettingsPrefix(), customSettings).build(); + customIndexSettings.put(indexTemplate.getSettingsPrefix(), customSettings); } - customIndexSettings = customIndexSettingsBuilder.build(); + this.customIndexSettings = unmodifiableMap(customIndexSettings); } @Override @@ -142,9 +141,9 @@ public class WatcherIndexTemplateRegistry extends AbstractComponent implements C } if (changed) { - customIndexSettings = MapBuilder.newMapBuilder(customIndexSettings) - .put(config.getSettingsPrefix(), builder.build()) - .immutableMap(); + Map customIndexSettings = new HashMap(this.customIndexSettings); + customIndexSettings.put(config.getSettingsPrefix(), builder.build()); + this.customIndexSettings = customIndexSettings; putTemplate(config, false); } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequestTemplate.java b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequestTemplate.java index cb7f157d032..9a65e864688 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequestTemplate.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequestTemplate.java @@ -5,7 +5,6 @@ */ 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.ParseFieldMatcher; @@ -24,11 +23,12 @@ import org.elasticsearch.watcher.support.text.TextTemplateEngine; import org.jboss.netty.handler.codec.http.HttpHeaders; import java.io.IOException; -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 java.util.Collections.unmodifiableMap; /** */ @@ -54,8 +54,8 @@ public class HttpRequestTemplate implements ToXContent { this.scheme = scheme != null ? scheme :Scheme.HTTP; this.method = method != null ? method : HttpMethod.GET; this.path = path; - this.params = params != null ? ImmutableMap.copyOf(params) : emptyMap(); - this.headers = headers != null ? ImmutableMap.copyOf(headers) : emptyMap(); + this.params = params != null ? params : emptyMap(); + this.headers = headers != null ? headers : emptyMap(); this.auth = auth; this.body = body; this.connectionTimeout = connectionTimeout; @@ -121,7 +121,7 @@ public class HttpRequestTemplate implements ToXContent { request.setParams(mapBuilder.map()); } if ((headers == null || headers.isEmpty()) && body != null && body.getContentType() != null) { - request.setHeaders(ImmutableMap.of(HttpHeaders.Names.CONTENT_TYPE, body.getContentType().restContentType())); + request.setHeaders(singletonMap(HttpHeaders.Names.CONTENT_TYPE, body.getContentType().restContentType())); } else if (headers != null && !headers.isEmpty()) { MapBuilder mapBuilder = MapBuilder.newMapBuilder(); if (body != null && body.getContentType() != null) { @@ -148,6 +148,7 @@ public class HttpRequestTemplate implements ToXContent { return request.build(); } + @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field(Field.SCHEME.getPreferredName(), scheme, params); @@ -334,8 +335,8 @@ public class HttpRequestTemplate implements ToXContent { private Scheme scheme; private HttpMethod method; private TextTemplate path; - private final ImmutableMap.Builder params = ImmutableMap.builder(); - private final ImmutableMap.Builder headers = ImmutableMap.builder(); + private final Map params = new HashMap<>(); + private final Map headers = new HashMap<>(); private HttpAuth auth; private TextTemplate body; private TimeValue connectionTimeout; @@ -433,7 +434,8 @@ public class HttpRequestTemplate implements ToXContent { } public HttpRequestTemplate build() { - return new HttpRequestTemplate(host, port, scheme, method, path, params.build(), headers.build(), auth, body, connectionTimeout, readTimeout); + return new HttpRequestTemplate(host, port, scheme, method, path, unmodifiableMap(new HashMap<>(params)), + unmodifiableMap(new HashMap<>(headers)), auth, body, connectionTimeout, readTimeout); } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpResponse.java b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpResponse.java index 16f37ac075c..a0d8c62fe78 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpResponse.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpResponse.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.support.http; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseFieldMatcher; @@ -17,17 +16,18 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.jboss.netty.handler.codec.http.HttpHeaders; -import javax.annotation.Nullable; - -import static java.util.Collections.emptyMap; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.annotation.Nullable; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.unmodifiableMap; + public class HttpResponse implements ToXContent { private final int status; @@ -51,7 +51,7 @@ public class HttpResponse implements ToXContent { } public HttpResponse(int status, @Nullable byte[] body) { - this(status, body != null ? new BytesArray(body) : null, ImmutableMap.of()); + this(status, body != null ? new BytesArray(body) : null, emptyMap()); } public HttpResponse(int status, @Nullable byte[] body, Map headers) { @@ -160,7 +160,7 @@ public class HttpResponse implements ToXContent { int status = -1; String body = null; - ImmutableMap.Builder headers = ImmutableMap.builder(); + Map headers = new HashMap<>(); String currentFieldName = null; XContentParser.Token token; @@ -210,7 +210,7 @@ public class HttpResponse implements ToXContent { if (status < 0) { throw new ElasticsearchParseException("could not parse http response. missing required numeric [{}] field holding the response's http status code", Field.STATUS.getPreferredName()); } - return new HttpResponse(status, body, headers.build()); + return new HttpResponse(status, body, unmodifiableMap(headers)); } interface Field { diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/http/auth/HttpAuthRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/support/http/auth/HttpAuthRegistry.java index 9a289e761b4..74573dcd8e9 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/http/auth/HttpAuthRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/http/auth/HttpAuthRegistry.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.support.http.auth; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -20,11 +19,11 @@ import static org.elasticsearch.watcher.support.Exceptions.illegalArgument; */ public class HttpAuthRegistry { - private final ImmutableMap factories; + private final Map factories; @Inject public HttpAuthRegistry(Map factories) { - this.factories = ImmutableMap.copyOf(factories); + this.factories = factories; } public HttpAuth parse(XContentParser parser) throws IOException { diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/xcontent/WatcherParams.java b/watcher/src/main/java/org/elasticsearch/watcher/support/xcontent/WatcherParams.java index 6c3af51faf5..f2ace14f278 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/xcontent/WatcherParams.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/xcontent/WatcherParams.java @@ -5,9 +5,14 @@ */ package org.elasticsearch.watcher.support.xcontent; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.ToXContent; +import java.util.HashMap; +import java.util.Map; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.unmodifiableMap; + /** * */ @@ -31,7 +36,7 @@ public class WatcherParams extends ToXContent.DelegatingMapParams { return wrap(params).debug(); } - private WatcherParams(ImmutableMap params, ToXContent.Params delegate) { + private WatcherParams(Map params, ToXContent.Params delegate) { super(params, delegate); } @@ -50,7 +55,7 @@ public class WatcherParams extends ToXContent.DelegatingMapParams { public static WatcherParams wrap(ToXContent.Params params) { return params instanceof WatcherParams ? (WatcherParams) params : - new WatcherParams(ImmutableMap.of(), params); + new WatcherParams(emptyMap(), params); } public static Builder builder() { @@ -64,7 +69,7 @@ public class WatcherParams extends ToXContent.DelegatingMapParams { public static class Builder { private final ToXContent.Params delegate; - private final ImmutableMap.Builder params = ImmutableMap.builder(); + private final Map params = new HashMap<>(); private Builder(ToXContent.Params delegate) { this.delegate = delegate; @@ -91,7 +96,7 @@ public class WatcherParams extends ToXContent.DelegatingMapParams { } public WatcherParams build() { - return new WatcherParams(params.build(), delegate); + return new WatcherParams(unmodifiableMap(new HashMap<>(params)), delegate); } } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java index e055560b6ae..0398ffa2e82 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/transform/TransformRegistry.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.transform; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -22,7 +21,7 @@ public class TransformRegistry { @Inject public TransformRegistry(Map factories) { - this.factories = ImmutableMap.copyOf(factories); + this.factories = factories; } public TransformFactory factory(String type) { diff --git a/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistry.java b/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistry.java index 56fb650f812..bbfe0910da2 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistry.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistry.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.trigger.schedule; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; @@ -18,12 +17,11 @@ import java.util.Set; * */ public class ScheduleRegistry { - - private final ImmutableMap parsers; + private final Map parsers; @Inject public ScheduleRegistry(Map parsers) { - this.parsers = ImmutableMap.copyOf(parsers); + this.parsers = parsers; } public Set types() { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/WatcherServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/WatcherServiceTests.java index de4e284c389..246729cc1ca 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/WatcherServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/WatcherServiceTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; @@ -15,7 +14,6 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.execution.ExecutionService; import org.elasticsearch.watcher.support.WatcherIndexTemplateRegistry; import org.elasticsearch.watcher.support.clock.ClockMock; @@ -32,13 +30,21 @@ import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; -import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicReference; +import static java.util.Collections.emptyMap; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * @@ -219,7 +225,7 @@ public class WatcherServiceTests extends ESTestCase { when(watchLockService.tryAcquire("_id", timeout)).thenReturn(lock); Watch watch = mock(Watch.class); when(watch.ack(now, "_all")).thenReturn(true); - WatchStatus status = new WatchStatus(now, ImmutableMap.of()); + WatchStatus status = new WatchStatus(now, emptyMap()); when(watch.status()).thenReturn(status); when(watchStore.get("_id")).thenReturn(watch); @@ -266,7 +272,7 @@ public class WatcherServiceTests extends ESTestCase { when(watchLockService.tryAcquire("_id", timeout)).thenReturn(lock); Watch watch = mock(Watch.class); - WatchStatus status = new WatchStatus(now, ImmutableMap.of()); + WatchStatus status = new WatchStatus(now, emptyMap()); when(watch.status()).thenReturn(status); when(watch.setState(true, now)).thenReturn(false); @@ -296,7 +302,7 @@ public class WatcherServiceTests extends ESTestCase { when(watchLockService.tryAcquire("_id", timeout)).thenReturn(lock); Watch watch = mock(Watch.class); - WatchStatus status = new WatchStatus(now, ImmutableMap.of()); + WatchStatus status = new WatchStatus(now, emptyMap()); when(watch.status()).thenReturn(status); when(watch.setState(true, now)).thenReturn(true); @@ -325,7 +331,7 @@ public class WatcherServiceTests extends ESTestCase { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); - WatchStatus status = new WatchStatus(now, ImmutableMap.of()); + WatchStatus status = new WatchStatus(now, emptyMap()); when(watch.status()).thenReturn(status); when(watch.setState(false, now)).thenReturn(true); @@ -356,7 +362,7 @@ public class WatcherServiceTests extends ESTestCase { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); - WatchStatus status = new WatchStatus(now, ImmutableMap.of()); + WatchStatus status = new WatchStatus(now, emptyMap()); when(watch.status()).thenReturn(status); when(watch.setState(false, now)).thenReturn(false); @@ -384,7 +390,7 @@ public class WatcherServiceTests extends ESTestCase { when(watchLockService.tryAcquire("_id", timeout)).thenReturn(lock); Watch watch = mock(Watch.class); when(watch.ack(now)).thenReturn(false); - WatchStatus status = new WatchStatus(now, ImmutableMap.of()); + WatchStatus status = new WatchStatus(now, emptyMap()); when(watch.status()).thenReturn(status); when(watchStore.get("_id")).thenReturn(watch); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/DataAttachmentTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/DataAttachmentTests.java index 62819d299dc..57613b17769 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/DataAttachmentTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/DataAttachmentTests.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.watcher.actions.email; -import com.google.common.collect.ImmutableMap; +import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.common.io.Streams; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.actions.email.service.Attachment; @@ -16,10 +16,9 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Map; +import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.is; -import org.apache.lucene.util.LuceneTestCase.AwaitsFix; - /** * */ @@ -28,7 +27,7 @@ public class DataAttachmentTests extends ESTestCase { @Test public void testCreate_Json() throws Exception { - Map data = ImmutableMap.of("key", "value"); + Map data = singletonMap("key", "value"); Attachment attachment = DataAttachment.JSON.create(data); InputStream input = attachment.bodyPart().getDataHandler().getInputStream(); String content = Streams.copyToString(new InputStreamReader(input, StandardCharsets.UTF_8)); @@ -37,7 +36,7 @@ public class DataAttachmentTests extends ESTestCase { @Test public void testCreate_Yaml() throws Exception { - Map data = ImmutableMap.of("key", "value"); + Map data = singletonMap("key", "value"); Attachment attachment = DataAttachment.YAML.create(data); InputStream input = attachment.bodyPart().getDataHandler().getInputStream(); String content = Streams.copyToString(new InputStreamReader(input, StandardCharsets.UTF_8)); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java index a11abe43d92..b945a14adab 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java @@ -5,8 +5,6 @@ */ package org.elasticsearch.watcher.actions.index; -import com.google.common.collect.ImmutableMap; - import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.settings.Settings; @@ -32,6 +30,7 @@ import org.junit.Test; import java.util.Arrays; import java.util.Map; +import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableSet; import static org.elasticsearch.common.util.set.Sets.newHashSet; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; @@ -79,7 +78,7 @@ public class IndexActionTests extends ESIntegTestCase { IndexAction action = new IndexAction("test-index", "test-type", timestampField, null, null); ExecutableIndexAction executable = new ExecutableIndexAction(action, logger, ClientProxy.of(client()), null); DateTime executionTime = DateTime.now(UTC); - Payload payload = randomBoolean() ? new Payload.Simple("foo", "bar") : new Payload.Simple("_doc", ImmutableMap.of("foo", "bar")); + Payload payload = randomBoolean() ? new Payload.Simple("foo", "bar") : new Payload.Simple("_doc", singletonMap("foo", "bar")); WatchExecutionContext ctx = WatcherTestUtils.mockExecutionContext("_id", executionTime, payload); Action.Result result = executable.execute("_id", ctx, ctx.payload()); @@ -134,9 +133,9 @@ public class IndexActionTests extends ESIntegTestCase { } Object list = randomFrom( - new Map[] { ImmutableMap.of("foo", "bar"), ImmutableMap.of("foo", "bar1") }, - Arrays.asList(ImmutableMap.of("foo", "bar"), ImmutableMap.of("foo", "bar1")), - unmodifiableSet(newHashSet(ImmutableMap.of("foo", "bar"), ImmutableMap.of("foo", "bar1"))) + new Map[] { singletonMap("foo", "bar"), singletonMap("foo", "bar1") }, + Arrays.asList(singletonMap("foo", "bar"), singletonMap("foo", "bar1")), + unmodifiableSet(newHashSet(singletonMap("foo", "bar"), singletonMap("foo", "bar1"))) ); IndexAction action = new IndexAction("test-index", "test-type", timestampField, null, null); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java index 82f10093302..db45cad786e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.actions.logging; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.Settings; @@ -25,9 +24,11 @@ import org.junit.Before; import org.junit.Test; import java.io.IOException; -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.actions.ActionBuilders.loggingAction; import static org.hamcrest.CoreMatchers.instanceOf; @@ -35,7 +36,10 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; import static org.joda.time.DateTimeZone.UTC; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** */ @@ -60,20 +64,18 @@ public class LoggingActionTests extends ESTestCase { .time("_watch_id", now) .buildMock(); - final Map expectedModel = ImmutableMap.builder() - .put("ctx", ImmutableMap.builder() - .put("id", ctx.id().value()) - .put("watch_id", "_watch_id") - .put("execution_time", now) - .put("payload", ImmutableMap.of()) - .put("metadata", ImmutableMap.of()) - .put("trigger", ImmutableMap.builder() - .put("scheduled_time", now) - .put("triggered_time", now) - .build()) - .put("vars", Collections.emptyMap()) - .build()) - .build(); + Map triggerModel = new HashMap<>(); + triggerModel.put("scheduled_time", now); + triggerModel.put("triggered_time", now); + Map ctxModel = new HashMap<>(); + ctxModel.put("id", ctx.id().value()); + ctxModel.put("watch_id", "_watch_id"); + ctxModel.put("execution_time", now); + ctxModel.put("payload", emptyMap()); + ctxModel.put("metadata", emptyMap()); + ctxModel.put("vars", emptyMap()); + ctxModel.put("trigger", triggerModel); + Map expectedModel = singletonMap("ctx", ctxModel); String text = randomAsciiOfLength(10); TextTemplate template = TextTemplate.inline(text).build(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java index 2e391101a91..7afe2e59ad1 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java @@ -5,8 +5,6 @@ */ package org.elasticsearch.watcher.actions.webhook; -import com.google.common.collect.ImmutableMap; - import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.settings.Settings; @@ -18,11 +16,18 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.actions.Action; import org.elasticsearch.watcher.actions.Action.Result.Status; -import org.elasticsearch.watcher.actions.email.service.*; +import org.elasticsearch.watcher.actions.email.service.Attachment; +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.Profile; import org.elasticsearch.watcher.execution.TriggeredExecutionContext; import org.elasticsearch.watcher.execution.WatchExecutionContext; -import org.elasticsearch.watcher.support.http.*; -import org.elasticsearch.watcher.support.http.auth.HttpAuthFactory; +import org.elasticsearch.watcher.support.http.HttpClient; +import org.elasticsearch.watcher.support.http.HttpMethod; +import org.elasticsearch.watcher.support.http.HttpRequest; +import org.elasticsearch.watcher.support.http.HttpRequestTemplate; +import org.elasticsearch.watcher.support.http.HttpResponse; import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuthFactory; import org.elasticsearch.watcher.support.init.proxy.ClientProxy; @@ -41,21 +46,27 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import javax.mail.internet.AddressException; - import java.io.IOException; import java.util.HashMap; import java.util.Map; +import javax.mail.internet.AddressException; + +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.core.Is.is; import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** @@ -86,7 +97,7 @@ public class WebhookActionTests extends ESTestCase { SecretService secretService = mock(SecretService.class); testBody = TextTemplate.inline(TEST_BODY_STRING).build(); testPath = TextTemplate.inline(TEST_PATH_STRING).build(); - authRegistry = new HttpAuthRegistry(ImmutableMap.of("basic", (HttpAuthFactory) new BasicAuthFactory(secretService))); + authRegistry = new HttpAuthRegistry(singletonMap("basic", new BasicAuthFactory(secretService))); } @After diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java index 8de028e3343..66b1e791ecd 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.condition.compare; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -23,6 +22,7 @@ import org.junit.Test; import java.util.Arrays; import java.util.Locale; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.Matchers.is; @@ -46,8 +46,8 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.EQ.eval("a", "aa"), is(false)); assertThat(Op.EQ.eval("a", "a"), is(true)); assertThat(Op.EQ.eval("aa", "ab"), is(false)); - assertThat(Op.EQ.eval(ImmutableMap.of("k", "v"), ImmutableMap.of("k", "v")), is(true)); - assertThat(Op.EQ.eval(ImmutableMap.of("k", "v"), ImmutableMap.of("k1", "v1")), is(false)); + assertThat(Op.EQ.eval(singletonMap("k", "v"), singletonMap("k", "v")), is(true)); + assertThat(Op.EQ.eval(singletonMap("k", "v"), singletonMap("k1", "v1")), is(false)); assertThat(Op.EQ.eval(Arrays.asList("k", "v"), Arrays.asList("k", "v")), is(true)); assertThat(Op.EQ.eval(Arrays.asList("k", "v"), Arrays.asList("k1", "v1")), is(false)); } @@ -66,8 +66,8 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.NOT_EQ.eval("a", "aa"), is(true)); assertThat(Op.NOT_EQ.eval("a", "a"), is(false)); assertThat(Op.NOT_EQ.eval("aa", "ab"), is(true)); - assertThat(Op.NOT_EQ.eval(ImmutableMap.of("k", "v"), ImmutableMap.of("k", "v")), is(false)); - assertThat(Op.NOT_EQ.eval(ImmutableMap.of("k", "v"), ImmutableMap.of("k1", "v1")), is(true)); + assertThat(Op.NOT_EQ.eval(singletonMap("k", "v"), singletonMap("k", "v")), is(false)); + assertThat(Op.NOT_EQ.eval(singletonMap("k", "v"), singletonMap("k1", "v1")), is(true)); assertThat(Op.NOT_EQ.eval(Arrays.asList("k", "v"), Arrays.asList("k", "v")), is(false)); assertThat(Op.NOT_EQ.eval(Arrays.asList("k", "v"), Arrays.asList("k1", "v1")), is(true)); } @@ -226,7 +226,7 @@ public class CompareConditionTests extends ESTestCase { @Test(expected = ElasticsearchParseException.class) public void testParse_InValid_WrongValueForOp() throws Exception { - Object value = randomFrom(Arrays.asList("1", "2"), ImmutableMap.of("key", "value")); + Object value = randomFrom(Arrays.asList("1", "2"), singletonMap("key", "value")); String op = randomFrom("lt", "lte", "gt", "gte"); CompareConditionFactory factory = new CompareConditionFactory(Settings.EMPTY, SystemClock.INSTANCE); XContentBuilder builder = jsonBuilder(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java index 6a6a1620e0d..fc5cac97511 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java @@ -6,8 +6,6 @@ package org.elasticsearch.watcher.condition.script; -import com.google.common.collect.ImmutableMap; - import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.search.SearchResponse; @@ -35,11 +33,14 @@ import org.junit.Test; import java.io.IOException; +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.getScriptServiceProxy; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** */ @@ -71,7 +72,7 @@ public class ScriptConditionTests extends ESTestCase { @Test public void testExecute_MergedParams() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); - Script script = Script.inline("ctx.payload.hits.total > threshold").lang(ScriptService.DEFAULT_LANG).params(ImmutableMap.of("threshold", 1)).build(); + Script script = Script.inline("ctx.payload.hits.total > threshold").lang(ScriptService.DEFAULT_LANG).params(singletonMap("threshold", 1)).build(); ExecutableScriptCondition executable = new ExecutableScriptCondition(new ScriptCondition(script), logger, scriptService); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java index fbaa931f2ff..e260dd50aee 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java @@ -5,11 +5,14 @@ */ package org.elasticsearch.watcher.execution; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.actions.*; +import org.elasticsearch.watcher.actions.Action; +import org.elasticsearch.watcher.actions.ActionStatus; +import org.elasticsearch.watcher.actions.ActionWrapper; +import org.elasticsearch.watcher.actions.ExecutableAction; +import org.elasticsearch.watcher.actions.ExecutableActions; import org.elasticsearch.watcher.actions.throttler.ActionThrottler; import org.elasticsearch.watcher.actions.throttler.Throttler; import org.elasticsearch.watcher.condition.Condition; @@ -26,7 +29,11 @@ import org.elasticsearch.watcher.support.validation.WatcherSettingsValidation; import org.elasticsearch.watcher.transform.ExecutableTransform; import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.elasticsearch.watcher.watch.*; +import org.elasticsearch.watcher.watch.Payload; +import org.elasticsearch.watcher.watch.Watch; +import org.elasticsearch.watcher.watch.WatchLockService; +import org.elasticsearch.watcher.watch.WatchStatus; +import org.elasticsearch.watcher.watch.WatchStore; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; @@ -36,10 +43,19 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ArrayBlockingQueue; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; -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.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** */ @@ -127,7 +143,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(clock.nowUTC()))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(clock.nowUTC()))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -201,7 +217,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(clock.nowUTC()))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(clock.nowUTC()))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -270,7 +286,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(clock.nowUTC()))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(clock.nowUTC()))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -338,7 +354,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(clock.nowUTC()))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(clock.nowUTC()))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -408,7 +424,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(clock.nowUTC()))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(clock.nowUTC()))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -473,7 +489,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(now))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -519,7 +535,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, transform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(now))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -565,7 +581,7 @@ public class ExecutionServiceTests extends ESTestCase { ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionTransform, action); ExecutableActions actions = new ExecutableActions(Arrays.asList(actionWrapper)); - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), ImmutableMap.of("_action", new ActionStatus(now))); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java index 818705b85d8..5b3059ea6f3 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java @@ -5,13 +5,13 @@ */ package org.elasticsearch.watcher.input; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import org.junit.Test; +import static java.util.Collections.emptyMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** @@ -21,7 +21,7 @@ public class InputRegistryTests extends ESTestCase { @Test(expected = ElasticsearchParseException.class) public void testParse_EmptyInput() throws Exception { - InputRegistry registry = new InputRegistry(ImmutableMap.of()); + InputRegistry registry = new InputRegistry(emptyMap()); XContentParser parser = JsonXContent.jsonXContent.createParser( jsonBuilder().startObject().endObject().bytes()); parser.nextToken(); @@ -31,7 +31,7 @@ public class InputRegistryTests extends ESTestCase { @Test(expected = ElasticsearchParseException.class) public void testParse_ArrayInput() throws Exception { - InputRegistry registry = new InputRegistry(ImmutableMap.of()); + InputRegistry registry = new InputRegistry(emptyMap()); XContentParser parser = JsonXContent.jsonXContent.createParser( jsonBuilder().startArray().endArray().bytes()); parser.nextToken(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java index 16ea2ad342b..6a3c14ef4ac 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java @@ -6,10 +6,7 @@ package org.elasticsearch.watcher.input.http; import org.elasticsearch.common.bytes.BytesReference; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.collect.MapBuilder; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.joda.time.DateTime; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -17,7 +14,6 @@ import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.actions.ActionWrapper; import org.elasticsearch.watcher.actions.ExecutableActions; import org.elasticsearch.watcher.condition.always.ExecutableAlwaysCondition; @@ -26,9 +22,14 @@ import org.elasticsearch.watcher.execution.WatchExecutionContext; import org.elasticsearch.watcher.input.InputBuilders; import org.elasticsearch.watcher.input.simple.ExecutableSimpleInput; import org.elasticsearch.watcher.input.simple.SimpleInput; -import org.elasticsearch.watcher.support.http.*; +import org.elasticsearch.watcher.support.http.HttpClient; +import org.elasticsearch.watcher.support.http.HttpContentType; +import org.elasticsearch.watcher.support.http.HttpMethod; +import org.elasticsearch.watcher.support.http.HttpRequest; +import org.elasticsearch.watcher.support.http.HttpRequestTemplate; +import org.elasticsearch.watcher.support.http.HttpResponse; +import org.elasticsearch.watcher.support.http.Scheme; import org.elasticsearch.watcher.support.http.auth.HttpAuth; -import org.elasticsearch.watcher.support.http.auth.HttpAuthFactory; import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuth; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuthFactory; @@ -41,6 +42,8 @@ import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.watcher.watch.WatchStatus; +import org.jboss.netty.handler.codec.http.HttpHeaders; +import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; @@ -48,9 +51,14 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Map; -import static org.joda.time.DateTimeZone.UTC; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; @@ -70,7 +78,7 @@ public class HttpInputTests extends ESTestCase { httpClient = mock(HttpClient.class); templateEngine = mock(TextTemplateEngine.class); secretService = mock(SecretService.class); - HttpAuthRegistry registry = new HttpAuthRegistry(ImmutableMap.of("basic", new BasicAuthFactory(secretService))); + HttpAuthRegistry registry = new HttpAuthRegistry(singletonMap("basic", new BasicAuthFactory(secretService))); httpParser = new HttpInputFactory(Settings.EMPTY, httpClient, templateEngine, new HttpRequest.Parser(registry), new HttpRequestTemplate.Parser(registry)); } @@ -94,19 +102,19 @@ public class HttpInputTests extends ESTestCase { httpInput = InputBuilders.httpInput(request.build()).expectedResponseXContentType(HttpContentType.YAML).build(); break; case 3: - response = new HttpResponse(123, "{\"key\" : \"value\"}".getBytes(StandardCharsets.UTF_8), ImmutableMap.of(HttpHeaders.Names.CONTENT_TYPE, new String[] { XContentType.JSON.restContentType() })); + response = new HttpResponse(123, "{\"key\" : \"value\"}".getBytes(StandardCharsets.UTF_8), singletonMap(HttpHeaders.Names.CONTENT_TYPE, new String[] { XContentType.JSON.restContentType() })); httpInput = InputBuilders.httpInput(request.build()).build(); break; case 4: - response = new HttpResponse(123, "key: value".getBytes(StandardCharsets.UTF_8), ImmutableMap.of(HttpHeaders.Names.CONTENT_TYPE, new String[] { XContentType.YAML.restContentType() })); + response = new HttpResponse(123, "key: value".getBytes(StandardCharsets.UTF_8), singletonMap(HttpHeaders.Names.CONTENT_TYPE, new String[] { XContentType.YAML.restContentType() })); httpInput = InputBuilders.httpInput(request.build()).build(); break; case 5: - response = new HttpResponse(123, "---\nkey: value".getBytes(StandardCharsets.UTF_8), ImmutableMap.of(HttpHeaders.Names.CONTENT_TYPE, new String[] { "unrecognized_content_type" })); + response = new HttpResponse(123, "---\nkey: value".getBytes(StandardCharsets.UTF_8), singletonMap(HttpHeaders.Names.CONTENT_TYPE, new String[] { "unrecognized_content_type" })); httpInput = InputBuilders.httpInput(request.build()).expectedResponseXContentType(HttpContentType.YAML).build(); break; default: - response = new HttpResponse(123, "{\"key\" : \"value\"}".getBytes(StandardCharsets.UTF_8), ImmutableMap.of(HttpHeaders.Names.CONTENT_TYPE, new String[] { "unrecognized_content_type" })); + response = new HttpResponse(123, "{\"key\" : \"value\"}".getBytes(StandardCharsets.UTF_8), singletonMap(HttpHeaders.Names.CONTENT_TYPE, new String[] { "unrecognized_content_type" })); httpInput = InputBuilders.httpInput(request.build()).build(); break; } @@ -125,7 +133,7 @@ public class HttpInputTests extends ESTestCase { null, new ExecutableActions(new ArrayList()), null, - new WatchStatus(new DateTime(0, UTC), ImmutableMap.of())); + new WatchStatus(new DateTime(0, UTC), emptyMap())); WatchExecutionContext ctx = new TriggeredExecutionContext(watch, new DateTime(0, UTC), new ScheduleTriggerEvent(watch.id(), new DateTime(0, UTC), new DateTime(0, UTC)), @@ -156,7 +164,7 @@ public class HttpInputTests extends ESTestCase { null, new ExecutableActions(new ArrayList()), null, - new WatchStatus(new DateTime(0, UTC), ImmutableMap.of())); + new WatchStatus(new DateTime(0, UTC), emptyMap())); WatchExecutionContext ctx = new TriggeredExecutionContext(watch, new DateTime(0, UTC), new ScheduleTriggerEvent(watch.id(), new DateTime(0, UTC), new DateTime(0, UTC)), diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java index debd34a33d5..d581b1bf58e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java @@ -5,8 +5,6 @@ */ package org.elasticsearch.watcher.input.search; -import com.google.common.collect.ImmutableMap; - import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; @@ -21,7 +19,6 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.actions.ActionWrapper; import org.elasticsearch.watcher.actions.ExecutableActions; import org.elasticsearch.watcher.condition.always.ExecutableAlwaysCondition; @@ -49,15 +46,20 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import static java.util.Collections.emptyMap; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.elasticsearch.watcher.test.WatcherTestUtils.areJsonEquivalent; import static org.elasticsearch.watcher.test.WatcherTestUtils.getRandomSupportedSearchType; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.startsWith; import static org.joda.time.DateTimeZone.UTC; /** @@ -121,7 +123,7 @@ public class SearchInputTests extends ESIntegTestCase { null, new ExecutableActions(new ArrayList()), null, - new WatchStatus(new DateTime(0, UTC), ImmutableMap.of())), + new WatchStatus(new DateTime(0, UTC), emptyMap())), new DateTime(0, UTC), new ScheduleTriggerEvent("test-watch", new DateTime(0, UTC), new DateTime(0, UTC)), timeValueSeconds(5)); @@ -228,7 +230,7 @@ public class SearchInputTests extends ESIntegTestCase { null, new ExecutableActions(new ArrayList()), null, - new WatchStatus(new DateTime(0, UTC), ImmutableMap.of())), + new WatchStatus(new DateTime(0, UTC), emptyMap())), new DateTime(0, UTC), new ScheduleTriggerEvent("test-watch", new DateTime(0, UTC), new DateTime(0, UTC)), timeValueSeconds(5)); @@ -271,7 +273,7 @@ public class SearchInputTests extends ESIntegTestCase { null, new ExecutableActions(new ArrayList()), null, - new WatchStatus(new DateTime(50000, UTC), ImmutableMap.of())), + new WatchStatus(new DateTime(50000, UTC), emptyMap())), new DateTime(60000, UTC), new ScheduleTriggerEvent("test-watch", new DateTime(60000, UTC), new DateTime(60000, UTC)), timeValueSeconds(5)); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java index e5307e9da67..e873000f146 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java @@ -5,18 +5,16 @@ */ package org.elasticsearch.watcher.support.http; -import com.google.common.collect.ImmutableMap; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ExceptionsHelper; -import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; -import org.elasticsearch.watcher.support.http.auth.HttpAuthFactory; import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuth; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuthFactory; @@ -25,8 +23,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; import java.io.IOException; import java.net.BindException; import java.net.InetAddress; @@ -36,7 +32,14 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.UnrecoverableKeyException; -import static org.hamcrest.Matchers.*; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +import static java.util.Collections.singletonMap; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; /** @@ -54,7 +57,7 @@ public class HttpClientTests extends ESTestCase { @Before public void init() throws Exception { secretService = new SecretService.PlainText(); - authRegistry = new HttpAuthRegistry(ImmutableMap.of(BasicAuth.TYPE, new BasicAuthFactory(secretService))); + authRegistry = new HttpAuthRegistry(singletonMap(BasicAuth.TYPE, new BasicAuthFactory(secretService))); for (webPort = 9200; webPort < 9300; webPort++) { try { webServer = new MockWebServer(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java index 20fbe466841..5e3655c9036 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.support.http; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -13,7 +12,6 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.support.http.auth.HttpAuthFactory; import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuth; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuthFactory; @@ -25,8 +23,12 @@ import org.junit.Test; 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.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.is; /** * @@ -39,7 +41,7 @@ public class HttpRequestTemplateTests extends ESTestCase { HttpRequestTemplate template = HttpRequestTemplate.builder("_host", 1234) .body(XContentBuilder.builder(type.xContent()).startObject().endObject()) .build(); - HttpRequest request = template.render(new MockTextTemplateEngine(), ImmutableMap.of()); + HttpRequest request = template.render(new MockTextTemplateEngine(), emptyMap()); assertThat(request.headers, hasEntry(HttpHeaders.Names.CONTENT_TYPE, type.restContentType())); } @@ -48,7 +50,7 @@ public class HttpRequestTemplateTests extends ESTestCase { HttpRequestTemplate template = HttpRequestTemplate.builder("_host", 1234) .body("_body") .build(); - HttpRequest request = template.render(new MockTextTemplateEngine(), ImmutableMap.of()); + HttpRequest request = template.render(new MockTextTemplateEngine(), emptyMap()); assertThat(request.headers.size(), is(0)); } @@ -90,7 +92,7 @@ public class HttpRequestTemplateTests extends ESTestCase { HttpRequestTemplate template = builder.build(); - HttpAuthRegistry registry = new HttpAuthRegistry(ImmutableMap.of(BasicAuth.TYPE, new BasicAuthFactory(new SecretService.PlainText()))); + HttpAuthRegistry registry = new HttpAuthRegistry(singletonMap(BasicAuth.TYPE, new BasicAuthFactory(new SecretService.PlainText()))); HttpRequestTemplate.Parser parser = new HttpRequestTemplate.Parser(registry); XContentBuilder xContentBuilder = template.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java index a1dfc5ab3dd..e6d5dad50e0 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.watcher.support.http; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; @@ -16,6 +15,8 @@ import org.junit.Test; import java.nio.charset.StandardCharsets; 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.xContentParser; import static org.hamcrest.CoreMatchers.nullValue; @@ -31,9 +32,9 @@ public class HttpResponseTests extends ESTestCase { @Test public void testParse_SelfGenerated() throws Exception { int status = randomIntBetween(200, 600); - ImmutableMap headers = ImmutableMap.of(); + Map headers = emptyMap(); if (randomBoolean()) { - headers = ImmutableMap.of("key", new String[] { "value" }); + headers = singletonMap("key", new String[] { "value" }); } String body = randomBoolean() ? "body" : null; final HttpResponse response; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java index 368c47f7aec..871209ea5f4 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.watcher.support.text; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; @@ -21,11 +20,16 @@ import org.elasticsearch.watcher.support.text.xmustache.XMustacheTextTemplateEng import org.junit.Before; import org.junit.Test; +import java.util.HashMap; import java.util.Map; +import static java.util.Collections.singletonMap; +import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.support.Exceptions.illegalArgument; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -49,9 +53,11 @@ public class TextTemplateTests extends ESTestCase { @Test public void testRender() throws Exception { String templateText = "_template"; - Map params = ImmutableMap.of("param_key", "param_val"); - Map model = ImmutableMap.of("model_key", "model_val"); - Map merged = ImmutableMap.builder().putAll(params).putAll(model).build(); + Map params = singletonMap("param_key", "param_val"); + Map model = singletonMap("model_key", "model_val"); + Map merged = new HashMap<>(params); + merged.putAll(model); + merged = unmodifiableMap(merged); ScriptType type = randomFrom(ScriptType.values()); when(proxy.executable(new org.elasticsearch.script.Template(templateText, type, lang, null, merged))).thenReturn(script); @@ -64,8 +70,8 @@ public class TextTemplateTests extends ESTestCase { @Test public void testRender_OverridingModel() throws Exception { String templateText = "_template"; - Map params = ImmutableMap.of("key", "param_val"); - Map model = ImmutableMap.of("key", "model_val"); + Map params = singletonMap("key", "param_val"); + Map model = singletonMap("key", "model_val"); ScriptType scriptType = randomFrom(ScriptType.values()); when(proxy.executable(new org.elasticsearch.script.Template(templateText, scriptType, lang, null, model))).thenReturn(script); @@ -78,7 +84,7 @@ public class TextTemplateTests extends ESTestCase { @Test public void testRender_Defaults() throws Exception { String templateText = "_template"; - Map model = ImmutableMap.of("key", "model_val"); + Map model = singletonMap("key", "model_val"); when(proxy.executable(new org.elasticsearch.script.Template(templateText, ScriptType.INLINE, lang, null, model))).thenReturn(script); when(script.run()).thenReturn("rendered_text"); @@ -90,7 +96,7 @@ public class TextTemplateTests extends ESTestCase { @Test public void testParser() throws Exception { ScriptType type = randomScriptType(); - TextTemplate template = templateBuilder(type, "_template").params(ImmutableMap.of("param_key", "param_val")).build(); + TextTemplate template = templateBuilder(type, "_template").params(singletonMap("param_key", "param_val")).build(); XContentBuilder builder = jsonBuilder().startObject(); switch (type) { case INLINE: @@ -114,7 +120,7 @@ public class TextTemplateTests extends ESTestCase { @Test public void testParser_ParserSelfGenerated() throws Exception { - TextTemplate template = templateBuilder(randomScriptType(), "_template").params(ImmutableMap.of("param_key", "param_val")).build(); + TextTemplate template = templateBuilder(randomScriptType(), "_template").params(singletonMap("param_key", "param_val")).build(); XContentBuilder builder = jsonBuilder().value(template); BytesReference bytes = builder.bytes(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java index 2188b9e06b6..7625e86b289 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.watcher.support.text.xmustache; import com.fasterxml.jackson.core.io.JsonStringEncoder; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; @@ -26,6 +25,7 @@ import java.util.HashMap; import java.util.Map; import static java.util.Collections.singleton; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.util.set.Sets.newHashSet; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.containsString; @@ -93,8 +93,8 @@ public class XMustacheTests extends ESTestCase { CompiledScript mustache = new CompiledScript(ScriptService.ScriptType.INLINE, "inline", "mustache", engine.compile(template)); Map vars = new HashMap<>(); Object data = randomFrom( - new Map[] { ImmutableMap.of("key", "foo"), ImmutableMap.of("key", "bar") }, - Arrays.asList(ImmutableMap.of("key", "foo"), ImmutableMap.of("key", "bar"))); + new Map[] { singletonMap("key", "foo"), singletonMap("key", "bar") }, + Arrays.asList(singletonMap("key", "foo"), singletonMap("key", "bar"))); vars.put("data", data); Object output = engine.execute(mustache, vars); assertThat(output, notNullValue()); @@ -103,7 +103,7 @@ public class XMustacheTests extends ESTestCase { assertThat(bytes.toUtf8(), equalTo("foo bar")); // HashSet iteration order isn't fixed - vars.put("data", newHashSet(ImmutableMap.of("key", "foo"), ImmutableMap.of("key", "bar"))); + vars.put("data", newHashSet(singletonMap("key", "foo"), singletonMap("key", "bar"))); output = engine.execute(mustache, vars); assertThat(output, notNullValue()); assertThat(output, instanceOf(BytesReference.class)); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java index 5a72f9b70e6..8e3c2b8d71f 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java @@ -5,12 +5,16 @@ */ package org.elasticsearch.watcher.support.xcontent; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.test.ESTestCase; import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static java.util.Collections.singletonMap; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; @@ -21,9 +25,7 @@ public class MapPathTests extends ESTestCase { @Test public void testEval() throws Exception { - Map map = ImmutableMap.builder() - .put("key", "value") - .build(); + Map map = singletonMap("key", "value"); assertThat(ObjectPath.eval("key", map), is((Object) "value")); assertThat(ObjectPath.eval("key1", map), nullValue()); @@ -32,9 +34,7 @@ public class MapPathTests extends ESTestCase { @Test public void testEval_List() throws Exception { List list = Arrays.asList(1, 2, 3, 4); - Map map = ImmutableMap.builder() - .put("key", list) - .build(); + Map map = singletonMap("key", list); int index = randomInt(3); assertThat(ObjectPath.eval("key." + index, map), is(list.get(index))); @@ -43,9 +43,7 @@ public class MapPathTests extends ESTestCase { @Test public void testEval_Array() throws Exception { int[] array = new int[] { 1, 2, 3, 4 }; - Map map = ImmutableMap.builder() - .put("key", array) - .build(); + Map map = singletonMap("key", array); int index = randomInt(3); assertThat(((Number) ObjectPath.eval("key." + index, map)).intValue(), is(array[index])); @@ -53,9 +51,7 @@ public class MapPathTests extends ESTestCase { @Test public void testEval_Map() throws Exception { - Map map = ImmutableMap.builder() - .put("a", ImmutableMap.of("b", "val")) - .build(); + Map map = singletonMap("a", singletonMap("b", "val")); assertThat(ObjectPath.eval("a.b", map), is((Object) "val")); } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java b/watcher/src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java index e7bcdefd46a..dd19a01a666 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/WatcherTestUtils.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.test; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; @@ -15,7 +14,12 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.*; +import org.elasticsearch.common.xcontent.XContent; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.common.xcontent.XContentHelper; +import org.elasticsearch.common.xcontent.XContentParser; +import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.env.Environment; import org.elasticsearch.script.ScriptContextRegistry; import org.elasticsearch.script.ScriptEngineService; @@ -29,7 +33,11 @@ import org.elasticsearch.watcher.actions.ActionWrapper; import org.elasticsearch.watcher.actions.ExecutableActions; import org.elasticsearch.watcher.actions.email.EmailAction; import org.elasticsearch.watcher.actions.email.ExecutableEmailAction; -import org.elasticsearch.watcher.actions.email.service.*; +import org.elasticsearch.watcher.actions.email.service.Authentication; +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.actions.webhook.ExecutableWebhookAction; import org.elasticsearch.watcher.actions.webhook.WebhookAction; import org.elasticsearch.watcher.condition.script.ExecutableScriptCondition; @@ -65,12 +73,21 @@ import org.elasticsearch.watcher.watch.WatchStatus; import org.hamcrest.Matcher; import org.joda.time.DateTime; -import javax.mail.internet.AddressException; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.mail.internet.AddressException; import static com.carrotsearch.randomizedtesting.RandomizedTest.randomInt; +import static java.util.Collections.emptyMap; import static org.apache.lucene.util.LuceneTestCase.createTempDir; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -85,7 +102,7 @@ import static org.mockito.Mockito.when; */ public final class WatcherTestUtils { - public static final Payload EMPTY_PAYLOAD = new Payload.Simple(ImmutableMap.of()); + public static final Payload EMPTY_PAYLOAD = new Payload.Simple(emptyMap()); private WatcherTestUtils() { } @@ -214,6 +231,9 @@ public final class WatcherTestUtils { when(licenseService.enabled()).thenReturn(true); DateTime now = DateTime.now(UTC); + Map statuses = new HashMap<>(); + statuses.put("_webhook", new ActionStatus(now)); + statuses.put("_email", new ActionStatus(now)); return new Watch( watchName, new ScheduleTrigger(new CronSchedule("0/5 * * * * ? *")), @@ -223,10 +243,7 @@ public final class WatcherTestUtils { new TimeValue(0), new ExecutableActions(actions), metadata, - new WatchStatus(now, ImmutableMap.builder() - .put("_webhook", new ActionStatus(now)) - .put("_email", new ActionStatus(now)) - .build())); + new WatchStatus(now, statuses)); } public static ScriptServiceProxy getScriptServiceProxy(ThreadPool tp) throws Exception { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/bench/ScheduleEngineTriggerBenchmark.java b/watcher/src/test/java/org/elasticsearch/watcher/test/bench/ScheduleEngineTriggerBenchmark.java index 90d63eeee8a..7043b8885aa 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/bench/ScheduleEngineTriggerBenchmark.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/bench/ScheduleEngineTriggerBenchmark.java @@ -12,14 +12,23 @@ import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.trigger.Trigger; import org.elasticsearch.watcher.trigger.TriggerEngine; 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.elasticsearch.watcher.trigger.schedule.engine.SchedulerScheduleTriggerEngine; import org.elasticsearch.watcher.trigger.schedule.engine.TickerScheduleTriggerEngine; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import static java.util.Collections.emptyMap; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; /** @@ -54,7 +63,7 @@ public class ScheduleEngineTriggerBenchmark { for (int i = 0; i < numWatches; i++) { jobs.add(new SimpleJob("job_" + i, interval(interval + "s"))); } - ScheduleRegistry scheduleRegistry = new ScheduleRegistry(Collections.emptyMap()); + ScheduleRegistry scheduleRegistry = new ScheduleRegistry(emptyMap()); List impls = new ArrayList<>(Arrays.asList(new String[]{"schedule", "ticker"})); Collections.shuffle(impls); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java index 88dd82959b5..f12ef5c3e1e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.transform.chain; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -26,8 +25,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; /** @@ -110,10 +116,7 @@ public class ChainTransformTests extends ESTestCase { @Test public void testParser() throws Exception { - Map factories = ImmutableMap.builder() - .put("named", new NamedExecutableTransform.Factory(logger)) - .build(); - TransformRegistry registry = new TransformRegistry(factories); + TransformRegistry registry = new TransformRegistry(singletonMap("named", new NamedExecutableTransform.Factory(logger))); ChainTransformFactory transformParser = new ChainTransformFactory(registry); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java index 932718afa20..138b39db88b 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.transform.search; -import com.google.common.collect.ImmutableMap; import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; @@ -22,7 +21,6 @@ import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.actions.ActionWrapper; import org.elasticsearch.watcher.actions.ExecutableActions; import org.elasticsearch.watcher.condition.always.ExecutableAlwaysCondition; @@ -52,15 +50,29 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import static java.util.Collections.emptyMap; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.parseDate; -import static org.elasticsearch.watcher.test.WatcherTestUtils.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD; +import static org.elasticsearch.watcher.test.WatcherTestUtils.areJsonEquivalent; +import static org.elasticsearch.watcher.test.WatcherTestUtils.getRandomSupportedSearchType; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; +import static org.elasticsearch.watcher.test.WatcherTestUtils.simplePayload; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; import static org.joda.time.DateTimeZone.UTC; /** @@ -425,7 +437,7 @@ public class SearchTransformTests extends ESIntegTestCase { null, new ExecutableActions(new ArrayList()), null, - new WatchStatus( new DateTime(40000, UTC), ImmutableMap.of())), + new WatchStatus( new DateTime(40000, UTC), emptyMap())), new DateTime(60000, UTC), new ScheduleTriggerEvent("test-watch", new DateTime(60000, UTC), new DateTime(60000, UTC)), timeValueSeconds(5)); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java index b9af623dd24..b632b57c926 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java @@ -6,9 +6,6 @@ package org.elasticsearch.watcher.transport.action.execute; import org.elasticsearch.action.ActionRequestValidationException; -import com.google.common.collect.ImmutableMap; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.client.WatcherClient; @@ -25,11 +22,14 @@ import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.WatchStatus; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import org.junit.Test; import java.util.HashMap; import java.util.Map; +import static java.util.Collections.singletonMap; import static org.elasticsearch.watcher.actions.ActionBuilders.loggingAction; import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondition; @@ -180,7 +180,7 @@ public class ExecuteWatchTests extends AbstractWatcherIntegrationTestCase { assertThat(putWatchResponse.isCreated(), is(true)); ExecuteWatchResponse response = watcherClient.prepareExecuteWatch("_id") - .setAlternativeInput(ImmutableMap.of("foo1", "bar1")) + .setAlternativeInput(singletonMap("foo1", "bar1")) .get(); assertThat(response, notNullValue()); assertThat(response.getRecordId(), notNullValue()); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java index 43a53812966..64e83eff035 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java @@ -5,8 +5,6 @@ */ package org.elasticsearch.watcher.watch; -import com.google.common.collect.ImmutableMap; - import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.logging.ESLogger; @@ -72,7 +70,6 @@ import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.support.http.HttpClient; import org.elasticsearch.watcher.support.http.HttpMethod; import org.elasticsearch.watcher.support.http.HttpRequestTemplate; -import org.elasticsearch.watcher.support.http.auth.HttpAuthFactory; import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; import org.elasticsearch.watcher.support.http.auth.basic.BasicAuthFactory; import org.elasticsearch.watcher.support.init.proxy.ClientProxy; @@ -121,10 +118,13 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Collections.singleton; +import static java.util.Collections.singletonMap; +import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.watcher.input.InputBuilders.searchInput; import static org.elasticsearch.watcher.test.WatcherTestUtils.matchAllRequest; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; @@ -160,7 +160,7 @@ public class WatchTests extends ESTestCase { htmlSanitizer = mock(HtmlSanitizer.class); secretService = mock(SecretService.class); licenseService = mock(LicenseService.class); - authRegistry = new HttpAuthRegistry(ImmutableMap.of("basic", (HttpAuthFactory) new BasicAuthFactory(secretService))); + authRegistry = new HttpAuthRegistry(singletonMap("basic", new BasicAuthFactory(secretService))); logger = Loggers.getLogger(WatchTests.class); } @@ -189,13 +189,13 @@ public class WatchTests extends ESTestCase { ExecutableActions actions = randomActions(); ActionRegistry actionRegistry = registry(actions, transformRegistry); - Map metadata = ImmutableMap.of("_key", "_val"); + Map metadata = singletonMap("_key", "_val"); - ImmutableMap.Builder actionsStatuses = ImmutableMap.builder(); + Map actionsStatuses = new HashMap<>(); for (ActionWrapper action : actions) { actionsStatuses.put(action.id(), new ActionStatus(now)); } - WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), actionsStatuses.build()); + WatchStatus watchStatus = new WatchStatus(clock.nowUTC(), unmodifiableMap(actionsStatuses)); TimeValue throttlePeriod = randomBoolean() ? null : TimeValue.timeValueSeconds(randomIntBetween(5, 10)); @@ -303,29 +303,29 @@ public class WatchTests extends ESTestCase { } private static ScheduleRegistry registry(Schedule schedule) { - ImmutableMap.Builder parsers = ImmutableMap.builder(); + Map parsers = new HashMap<>(); switch (schedule.type()) { case CronSchedule.TYPE: parsers.put(CronSchedule.TYPE, new CronSchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); case HourlySchedule.TYPE: parsers.put(HourlySchedule.TYPE, new HourlySchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); case DailySchedule.TYPE: parsers.put(DailySchedule.TYPE, new DailySchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); case WeeklySchedule.TYPE: parsers.put(WeeklySchedule.TYPE, new WeeklySchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); case MonthlySchedule.TYPE: parsers.put(MonthlySchedule.TYPE, new MonthlySchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); case YearlySchedule.TYPE: parsers.put(YearlySchedule.TYPE, new YearlySchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); case IntervalSchedule.TYPE: parsers.put(IntervalSchedule.TYPE, new IntervalSchedule.Parser()); - return new ScheduleRegistry(parsers.build()); + return new ScheduleRegistry(parsers); default: throw new IllegalArgumentException("unknown schedule [" + schedule + "]"); } @@ -338,20 +338,20 @@ public class WatchTests extends ESTestCase { SearchInput searchInput = searchInput(WatcherTestUtils.newInputSearchRequest("idx")).build(); return new ExecutableSearchInput(searchInput, logger, client, null); default: - SimpleInput simpleInput = InputBuilders.simpleInput(ImmutableMap.builder().put("_key", "_val")).build(); + SimpleInput simpleInput = InputBuilders.simpleInput(singletonMap("_key", "_val")).build(); return new ExecutableSimpleInput(simpleInput, logger); } } private InputRegistry registry(ExecutableInput input) { - ImmutableMap.Builder parsers = ImmutableMap.builder(); + Map parsers = new HashMap<>(); switch (input.type()) { case SearchInput.TYPE: parsers.put(SearchInput.TYPE, new SearchInputFactory(settings, client)); - return new InputRegistry(parsers.build()); + return new InputRegistry(parsers); default: parsers.put(SimpleInput.TYPE, new SimpleInputFactory(settings)); - return new InputRegistry(parsers.build()); + return new InputRegistry(parsers); } } @@ -370,20 +370,20 @@ public class WatchTests extends ESTestCase { } private ConditionRegistry registry(ExecutableCondition condition) { - ImmutableMap.Builder parsers = ImmutableMap.builder(); + Map parsers = new HashMap<>(); switch (condition.type()) { case ScriptCondition.TYPE: parsers.put(ScriptCondition.TYPE, new ScriptConditionFactory(settings, scriptService)); - return new ConditionRegistry(parsers.build()); + return new ConditionRegistry(parsers); case CompareCondition.TYPE: parsers.put(CompareCondition.TYPE, new CompareConditionFactory(settings, SystemClock.INSTANCE)); - return new ConditionRegistry(parsers.build()); + return new ConditionRegistry(parsers); case ArrayCompareCondition.TYPE: parsers.put(ArrayCompareCondition.TYPE, new ArrayCompareConditionFactory(settings, SystemClock.INSTANCE)); - return new ConditionRegistry(parsers.build()); + return new ConditionRegistry(parsers); default: parsers.put(AlwaysCondition.TYPE, new AlwaysConditionFactory(settings)); - return new ConditionRegistry(parsers.build()); + return new ConditionRegistry(parsers); } } @@ -406,12 +406,12 @@ public class WatchTests extends ESTestCase { } private TransformRegistry transformRegistry() { - ImmutableMap.Builder factories = ImmutableMap.builder(); + Map factories = new HashMap<>(); ChainTransformFactory parser = new ChainTransformFactory(); factories.put(ChainTransform.TYPE, parser); factories.put(ScriptTransform.TYPE, new ScriptTransformFactory(settings, scriptService)); factories.put(SearchTransform.TYPE, new SearchTransformFactory(settings, client)); - TransformRegistry registry = new TransformRegistry(factories.build()); + TransformRegistry registry = new TransformRegistry(unmodifiableMap(factories)); parser.init(registry); return registry; } @@ -441,7 +441,7 @@ public class WatchTests extends ESTestCase { } private ActionRegistry registry(ExecutableActions actions, TransformRegistry transformRegistry) { - ImmutableMap.Builder parsers = ImmutableMap.builder(); + Map parsers = new HashMap<>(); for (ActionWrapper action : actions) { switch (action.action().type()) { case EmailAction.TYPE: @@ -455,7 +455,7 @@ public class WatchTests extends ESTestCase { break; } } - return new ActionRegistry(parsers.build(), transformRegistry, SystemClock.INSTANCE, licenseService); + return new ActionRegistry(unmodifiableMap(parsers), transformRegistry, SystemClock.INSTANCE, licenseService); } private ActionThrottler randomThrottler() { From dab504f6ba0b870c8e40752131629bc129996454 Mon Sep 17 00:00:00 2001 From: Nik Everett Date: Mon, 5 Oct 2015 17:11:33 -0400 Subject: [PATCH 3/4] Remove ImmutableMap$Builder Original commit: elastic/x-pack-elasticsearch@f0d3f71887061afc9c7321d0900ebd82ac75ba78 --- .../authc/esusers/FileUserPasswdStore.java | 11 ++--- .../authc/esusers/FileUserRolesStore.java | 10 ++-- .../shield/authz/Permission.java | 8 ++- .../watcher/actions/email/service/Email.java | 49 +++++++++++++------ .../execution/ManualExecutionContext.java | 17 +++++-- .../watcher/input/InputBuilders.java | 5 -- .../watcher/support/http/HttpClient.java | 28 ++++++++--- .../watcher/support/http/HttpRequest.java | 32 +++++++++--- .../watcher/trigger/TriggerService.java | 9 ++-- .../SchedulerScheduleTriggerEngine.java | 35 +++++++------ .../elasticsearch/watcher/watch/Watch.java | 10 ++-- .../watcher/watch/WatchStatus.java | 21 +++++--- .../actions/email/EmailActionTests.java | 45 ++++++++++------- .../actions/email/service/EmailTests.java | 8 +-- .../actions/hipchat/HipChatActionTests.java | 34 +++++++------ .../actions/slack/SlackActionTests.java | 40 ++++++++------- .../watcher/support/VariablesTests.java | 14 +++--- .../watcher/support/WatcherUtilsTests.java | 33 ++++++------- .../script/ScriptTransformTests.java | 9 ++-- .../ExecuteWatchWithDateMathTests.java | 17 ++++--- 20 files changed, 258 insertions(+), 177 deletions(-) diff --git a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java index 072e9f3248d..60ec7deeb67 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java +++ b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserPasswdStore.java @@ -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 users = ImmutableMap.builder(); + Map users = new HashMap<>(); int lineNr = 0; for (String line : lines) { @@ -164,11 +164,10 @@ public class FileUserPasswdStore { users.put(username, hash.toCharArray()); } - ImmutableMap 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 esUsers, Path path) { diff --git a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java index ec1bc9d17bd..b1df110a914 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java +++ b/shield/src/main/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStore.java @@ -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 builder = ImmutableMap.builder(); + Map usersRoles = new HashMap<>(); for (Map.Entry> 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 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); } /** diff --git a/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java b/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java index fbf94899a52..4b36bfba1a8 100644 --- a/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java +++ b/shield/src/main/java/org/elasticsearch/shield/authz/Permission.java @@ -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 authorize(String action, Set requestedIndicesOrAliases, MetaData metaData) { + public Map authorize(String action, Set 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 indexPermissions = ImmutableMap.builder(); + Map indexPermissions = new HashMap<>(); for (Map.Entry entry : grantedBuilder.entrySet()) { String index = entry.getKey(); Set 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); } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java b/watcher/src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java index 17feb4f1d3b..a105f482dea 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/actions/email/service/Email.java @@ -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 attachments; - final ImmutableMap inlines; + final Map attachments; + final Map 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 attachments, ImmutableMap inlines) { + Map attachments, Map inlines) { this.id = id; this.from = from; @@ -107,11 +115,11 @@ public class Email implements ToXContent { return htmlBody; } - public ImmutableMap attachments() { + public Map attachments() { return attachments; } - public ImmutableMap inlines() { + public Map inlines() { return inlines; } @@ -239,8 +247,8 @@ public class Email implements ToXContent { private String subject; private String textBody; private String htmlBody; - private ImmutableMap.Builder attachments = ImmutableMap.builder(); - private ImmutableMap.Builder inlines = ImmutableMap.builder(); + private Map attachments = new HashMap<>(); + private Map 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 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; } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/execution/ManualExecutionContext.java b/watcher/src/main/java/org/elasticsearch/watcher/execution/ManualExecutionContext.java index b4614b6e51f..e935a2a3eb7 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/execution/ManualExecutionContext.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/execution/ManualExecutionContext.java @@ -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 actionModes = ImmutableMap.builder(); + private Map 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; } } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/input/InputBuilders.java b/watcher/src/main/java/org/elasticsearch/watcher/input/InputBuilders.java index 31ddc1d5508..5fde3b9dc48 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/input/InputBuilders.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/input/InputBuilders.java @@ -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.newMapBuilder().put(key, value)); } - public static SimpleInput.Builder simpleInput(ImmutableMap.Builder data) { - return simpleInput(data.build()); - } - public static SimpleInput.Builder simpleInput(MapBuilder data) { return simpleInput(data.map()); } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpClient.java b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpClient.java index 152b21283ee..d7451da98c1 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpClient.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpClient.java @@ -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 { urlConnection.connect(); final int statusCode = urlConnection.getResponseCode(); - ImmutableMap.Builder responseHeaders = ImmutableMap.builder(); + Map responseHeaders = new HashMap<>(); for (Map.Entry> 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 { 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 { 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 **/ diff --git a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequest.java b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequest.java index e76e6d6ea42..1d4e7504e16 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequest.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/support/http/HttpRequest.java @@ -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 params, @Nullable ImmutableMap headers, + @Nullable Map params, @Nullable Map 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 params = ImmutableMap.builder(); - private ImmutableMap.Builder headers = ImmutableMap.builder(); + private Map params = new HashMap<>(); + private Map 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 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 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; } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/trigger/TriggerService.java b/watcher/src/main/java/org/elasticsearch/watcher/trigger/TriggerService.java index 0250344d4ae..11d93a17a1f 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/trigger/TriggerService.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/trigger/TriggerService.java @@ -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 engines; + private final Map engines; @Inject public TriggerService(Settings settings, Set engines) { super(settings); listeners = new Listeners(); - ImmutableMap.Builder builder = ImmutableMap.builder(); + Map 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 jobs) throws Exception { diff --git a/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/engine/SchedulerScheduleTriggerEngine.java b/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/engine/SchedulerScheduleTriggerEngine.java index a2cec65cc8c..833aa762ffc 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/engine/SchedulerScheduleTriggerEngine.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/trigger/schedule/engine/SchedulerScheduleTriggerEngine.java @@ -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 scheduleByName; + private final Map scheduleByName; Schedules(Collection schedules) { - ImmutableMap.Builder builder = ImmutableMap.builder(); + Map 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 scheduleByName) { + public Schedules(ActiveSchedule[] schedules, Map 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 newScheduleByName = ImmutableMap.builder() - .putAll(scheduleByName) - .put(schedule.name, schedule) - .build(); - return new Schedules(newSchedules, newScheduleByName); + Map newScheduleByName = new HashMap<>(scheduleByName); + newScheduleByName.put(schedule.name, schedule); + return new Schedules(newSchedules, unmodifiableMap(newScheduleByName)); } ActiveSchedule[] newSchedules = new ActiveSchedule[schedules.length]; - ImmutableMap.Builder builder = ImmutableMap.builder(); + Map 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 builder = ImmutableMap.builder(); + Map 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)); } } diff --git a/watcher/src/main/java/org/elasticsearch/watcher/watch/Watch.java b/watcher/src/main/java/org/elasticsearch/watcher/watch/Watch.java index 5b48f869870..211ed3e56b7 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/watch/Watch.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/watch/Watch.java @@ -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 actionsStatuses = ImmutableMap.builder(); + Map 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); diff --git a/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java b/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java index 2068110bac3..6d023f330fd 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java @@ -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 builder = ImmutableMap.builder(); int count = in.readInt(); + Map 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 actions = null; + Map 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 { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java index 27d5a9dde6f..526aea25db7 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java @@ -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 expectedModel = ImmutableMap.builder() - .put("ctx", ImmutableMap.builder() - .put("id", ctx.id().value()) - .put("watch_id", "watch1") - .put("payload", data) - .put("metadata", metadata) - .put("execution_time", now) - .put("trigger", ImmutableMap.builder() - .put("triggered_time", now) - .put("scheduled_time", now) - .build()) - .put("vars", Collections.emptyMap()) - .build()) - .build(); + Map triggerModel = new HashMap<>(); + triggerModel.put("triggered_time", now); + triggerModel.put("scheduled_time", now); + Map 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 expectedModel = singletonMap("ctx", ctxModel); if (subject != null) { when(engine.render(subject, expectedModel)).thenReturn(subject.getTemplate()); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java index 7e56305077c..563e5007eb4 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java @@ -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("
BODY
", "", null); - ImmutableMap attachments = null; - ImmutableMap inlines = null; + Map attachments = null; + Map inlines = null; Email email = new Email(id, from, replyTo, priority, sentDate, to, cc, bcc, subject, textBody, htmlBody, attachments, inlines); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java index 7c0d0420eb8..af51cec1751 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java @@ -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 expectedModel = ImmutableMap.builder() - .put("ctx", ImmutableMap.builder() - .put("id", ctx.id().value()) - .put("watch_id", wid.watchId()) - .put("payload", data) - .put("metadata", metadata) - .put("execution_time", now) - .put("trigger", ImmutableMap.builder() - .put("triggered_time", now) - .put("scheduled_time", now) - .build()) - .put("vars", Collections.emptyMap()) - .build()) - .build(); + Map triggerModel = new HashMap<>(); + triggerModel.put("triggered_time", now); + triggerModel.put("scheduled_time", now); + Map 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 expectedModel = singletonMap("ctx", ctxModel); if (body != null) { when(templateEngine.render(body, expectedModel)).thenReturn(body.getTemplate()); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java index ff64b499e62..72d46543344 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java @@ -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 expectedModel = ImmutableMap.builder() - .put("ctx", ImmutableMap.builder() - .put("id", ctx.id().value()) - .put("watch_id", wid.watchId()) - .put("payload", data) - .put("metadata", metadata) - .put("execution_time", now) - .put("trigger", ImmutableMap.builder() - .put("triggered_time", now) - .put("scheduled_time", now) - .build()) - .put("vars", Collections.emptyMap()) - .build()) - .build(); + Map triggerModel = new HashMap<>(); + triggerModel.put("triggered_time", now); + triggerModel.put("scheduled_time", now); + Map 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 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); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java index 24645e5c810..77506ff9a1e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java @@ -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.builder().put("payload_key", "payload_value").build()); - Map metatdata = ImmutableMap.builder().put("metadata_key", "metadata_value").build(); + Payload payload = new Payload.Simple(singletonMap("payload_key", "payload_value")); + Map 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") diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java index 8976f606b71..4d9357233fc 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherUtilsTests.java @@ -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 map = ImmutableMap.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 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 result = (Map) flattenModel(map); + Map 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 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(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java index 36ecba54b6d..b2a2299f57e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java @@ -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 model = Variables.createCtxModel(ctx, payload); - Map transformed = ImmutableMap.builder() - .put("key", "value") - .build(); + Map 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.builder().put("key", "value").build()).build(); + Script script = scriptBuilder(type, "_script").lang("_lang").params(singletonMap("key", "value")).build(); assertThat(transform.transform().getScript(), equalTo(script)); } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java index a0ad7b192b5..bc03a5a8204 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java @@ -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.builder() - .put("triggered_time", "now") - .put("scheduled_time", "now+1m") - .build()) - .get(); + Map 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()); From f18b66fdc48381a54e143a8b9be2885702ae8063 Mon Sep 17 00:00:00 2001 From: Nik Everett Date: Fri, 9 Oct 2015 12:27:01 -0400 Subject: [PATCH 4/4] Handle missing actions when parsing WatchStatus Original commit: elastic/x-pack-elasticsearch@b868aa1a623ed827b0cce5ddaaa2e5030649b86e --- .../java/org/elasticsearch/watcher/watch/WatchStatus.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java b/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java index 6d023f330fd..e90cb8f7830 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/watch/WatchStatus.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; +import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.parseDate; import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.readDate; @@ -326,8 +327,9 @@ public class WatchStatus implements ToXContent, Streamable { if (state == null) { state = new State(true, WatcherXContentParser.clock(parser).nowUTC()); } + actions = actions == null ? emptyMap() : unmodifiableMap(actions); - return new WatchStatus(-1, state, lastChecked, lastMetCondition, unmodifiableMap(actions)); + return new WatchStatus(-1, state, lastChecked, lastMetCondition, actions); } public static class State implements ToXContent {