More ImmutableMap banning

Original commit: elastic/x-pack-elasticsearch@59fee6e288
This commit is contained in:
Nik Everett 2015-10-05 12:54:40 -04:00
parent eb60d5925a
commit 1d61278b2d
45 changed files with 437 additions and 351 deletions

View File

@ -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<String, char[]> users;
private volatile Map<String, char[]> users;
private CopyOnWriteArrayList<RefreshListener> 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<String, char[]> parseFileLenient(Path path, ESLogger logger) {
static Map<String, char[]> 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<String, char[]> parseFile(Path path, @Nullable ESLogger logger) {
public static Map<String, char[]> 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<String> lines;

View File

@ -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<RefreshListener> listeners;
private volatile ImmutableMap<String, String[]> userRoles;
private volatile Map<String, String[]> 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<String, String[]> parseFileLenient(Path path, ESLogger logger) {
static Map<String, String[]> 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 -&gt; users" while the returned
* map holds entries of the form "user -&gt; roles".
*/
public static ImmutableMap<String, String[]> parseFile(Path path, @Nullable ESLogger logger) {
public static Map<String, String[]> 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<String> lines;

View File

@ -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<DN, Set<String>> dnRoles;
protected volatile Map<DN, Set<String>> dnRoles;
private CopyOnWriteArrayList<RefreshListener> 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<DN, Set<String>> parseFileLenient(Path path, ESLogger logger, String realmType, String realmName) {
public static Map<DN, Set<String>> 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<DN, Set<String>> parseFile(Path path, ESLogger logger, String realmType, String realmName) {
public static Map<DN, Set<String>> 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);

View File

@ -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<String, IndicesAccessControl.IndexAccessControl> authorize(String action, Set<String> requestedIndicesOrAliases, MetaData metaData) {
public Map<String, IndicesAccessControl.IndexAccessControl> authorize(String action, Set<String> 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);
}
}

View File

@ -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<IPFilter> {
@ -174,7 +181,7 @@ public class IPFilter extends AbstractLifecycleComponent<IPFilter> {
}
logger.debug("loaded ip filtering profiles: {}", profileRules.keySet());
return ImmutableMap.copyOf(profileRules);
return unmodifiableMap(profileRules);
}
private ShieldIpFilterRule[] createRules(String[] allow, String[] deny, TransportAddress[] boundAddresses) {

View File

@ -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<String, String> 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");

View File

@ -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<String, String> params = ImmutableMap.of("refresh", "true");
Map<String, String> 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<String, String> refreshParams = ImmutableMap.of("refresh", "true");
Map<String, String> 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<String, String> analyzeParams = ImmutableMap.of("text", "test");
Map<String, String> 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<String, String> analyzeParams = ImmutableMap.of("text", "test");
Map<String, String> analyzeParams = singletonMap("text", "test");
assertAccessIsDenied(user, "GET", "/" + index + "/_analyze", null, analyzeParams);
assertAccessIsDenied(user, "POST", "/" + index + "/_flush");
assertAccessIsDenied(user, "POST", "/" + index + "/_optimize");

View File

@ -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<String, char[]> 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<String, char[]> users = FileUserPasswdStore.parseFile(empty, log);
Map<String, char[]> 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);

View File

@ -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<DN, Set<String>> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name");
Map<DN, Set<String>> 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<DN, Set<String>> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name");
Map<DN, Set<String>> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name");
assertThat(mappings, notNullValue());
assertThat(mappings.isEmpty(), is(true));
List<CapturingLogger.Msg> 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<DN, Set<String>> mappings = DnRoleMapper.parseFile(file, logger, "_type", "_name");
Map<DN, Set<String>> 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<DN, Set<String>> mappings = DnRoleMapper.parseFileLenient(file, logger, "_type", "_name");
Map<DN, Set<String>> mappings = DnRoleMapper.parseFileLenient(file, logger, "_type", "_name");
assertThat(mappings, notNullValue());
assertThat(mappings.isEmpty(), is(true));
List<CapturingLogger.Msg> 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()

View File

@ -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);

View File

@ -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) {

View File

@ -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");

View File

@ -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<String, ActionFactory> parsers;
private final Map<String, ActionFactory> parsers;
private final TransformRegistry transformRegistry;
private final Clock clock;
private final LicenseService licenseService;
@Inject
public ActionRegistry(Map<String, ActionFactory> parsers, TransformRegistry transformRegistry, Clock clock, LicenseService licenseService) {
this.parsers = ImmutableMap.copyOf(parsers);
this.parsers = parsers;
this.transformRegistry = transformRegistry;
this.clock = clock;
this.licenseService = licenseService;

View File

@ -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<String, ConditionFactory> factories;
private final Map<String, ConditionFactory> factories;
@Inject
public ConditionRegistry(Map<String, ConditionFactory> factories) {
this.factories = ImmutableMap.copyOf(factories);
this.factories = factories;
}
public Set<String> types() {

View File

@ -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<String, InputFactory> factories;
private final Map<String, InputFactory> factories;
@Inject
public InputRegistry(Map<String, InputFactory> factories) {
this.factories = ImmutableMap.copyOf(factories);
this.factories = factories;
}
/**

View File

@ -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<TemplateConfig> indexTemplates;
private volatile ImmutableMap<String, Settings> customIndexSettings;
private volatile Map<String, Settings> 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<String, Settings> customIndexSettingsBuilder = ImmutableMap.builder();
Map<String, Settings> 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<String, Settings> customIndexSettings = new HashMap<String, Settings>(this.customIndexSettings);
customIndexSettings.put(config.getSettingsPrefix(), builder.build());
this.customIndexSettings = customIndexSettings;
putTemplate(config, false);
}
}

View File

@ -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<String, String> 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<String, TextTemplate> params = ImmutableMap.builder();
private final ImmutableMap.Builder<String, TextTemplate> headers = ImmutableMap.builder();
private final Map<String, TextTemplate> params = new HashMap<>();
private final Map<String, TextTemplate> 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);
}
}

View File

@ -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.<String, String[]>of());
this(status, body != null ? new BytesArray(body) : null, emptyMap());
}
public HttpResponse(int status, @Nullable byte[] body, Map<String, String[]> headers) {
@ -160,7 +160,7 @@ public class HttpResponse implements ToXContent {
int status = -1;
String body = null;
ImmutableMap.Builder<String, String[]> headers = ImmutableMap.builder();
Map<String, String[]> 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 {

View File

@ -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<String, HttpAuthFactory> factories;
private final Map<String, HttpAuthFactory> factories;
@Inject
public HttpAuthRegistry(Map<String, HttpAuthFactory> factories) {
this.factories = ImmutableMap.copyOf(factories);
this.factories = factories;
}
public HttpAuth parse(XContentParser parser) throws IOException {

View File

@ -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<String, String> params, ToXContent.Params delegate) {
private WatcherParams(Map<String, String> 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.<String, String>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<String, String> params = ImmutableMap.builder();
private final Map<String, String> 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);
}
}
}

View File

@ -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<String, TransformFactory> factories) {
this.factories = ImmutableMap.copyOf(factories);
this.factories = factories;
}
public TransformFactory factory(String type) {

View File

@ -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<String, Schedule.Parser> parsers;
private final Map<String, Schedule.Parser> parsers;
@Inject
public ScheduleRegistry(Map<String, Schedule.Parser> parsers) {
this.parsers = ImmutableMap.copyOf(parsers);
this.parsers = parsers;
}
public Set<String> types() {

View File

@ -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.<String, ActionStatus>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.<String, ActionStatus>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.<String, ActionStatus>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.<String, ActionStatus>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.<String, ActionStatus>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.<String, ActionStatus>of());
WatchStatus status = new WatchStatus(now, emptyMap());
when(watch.status()).thenReturn(status);
when(watchStore.get("_id")).thenReturn(watch);

View File

@ -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<String, Object> data = ImmutableMap.<String, Object>of("key", "value");
Map<String, Object> 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<String, Object> data = ImmutableMap.<String, Object>of("key", "value");
Map<String, Object> 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));

View File

@ -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);

View File

@ -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<String, Object> expectedModel = ImmutableMap.<String, Object>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<String, Object> triggerModel = new HashMap<>();
triggerModel.put("scheduled_time", now);
triggerModel.put("triggered_time", now);
Map<String, Object> 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<String, Object> expectedModel = singletonMap("ctx", ctxModel);
String text = randomAsciiOfLength(10);
TextTemplate template = TextTemplate.inline(text).build();

View File

@ -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

View File

@ -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();

View File

@ -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.<String, Object>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));

View File

@ -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);

View File

@ -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.<String, InputFactory>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.<String, InputFactory>of());
InputRegistry registry = new InputRegistry(emptyMap());
XContentParser parser = JsonXContent.jsonXContent.createParser(
jsonBuilder().startArray().endArray().bytes());
parser.nextToken();

View File

@ -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.<String, HttpAuthFactory>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<ActionWrapper>()),
null,
new WatchStatus(new DateTime(0, UTC), ImmutableMap.<String, ActionStatus>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<ActionWrapper>()),
null,
new WatchStatus(new DateTime(0, UTC), ImmutableMap.<String, ActionStatus>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)),

View File

@ -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<ActionWrapper>()),
null,
new WatchStatus(new DateTime(0, UTC), ImmutableMap.<String, ActionStatus>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<ActionWrapper>()),
null,
new WatchStatus(new DateTime(0, UTC), ImmutableMap.<String, ActionStatus>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<ActionWrapper>()),
null,
new WatchStatus(new DateTime(50000, UTC), ImmutableMap.<String, ActionStatus>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));

View File

@ -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.<String, HttpAuthFactory>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();

View File

@ -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.<String, Object>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.<String, Object>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.<String, HttpAuthFactory>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);

View File

@ -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<String, String[]> headers = ImmutableMap.of();
Map<String, String[]> 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;

View File

@ -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<String, Object> params = ImmutableMap.<String, Object>of("param_key", "param_val");
Map<String, Object> model = ImmutableMap.<String, Object>of("model_key", "model_val");
Map<String, Object> merged = ImmutableMap.<String, Object>builder().putAll(params).putAll(model).build();
Map<String, Object> params = singletonMap("param_key", "param_val");
Map<String, Object> model = singletonMap("model_key", "model_val");
Map<String, Object> 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<String, Object> params = ImmutableMap.<String, Object>of("key", "param_val");
Map<String, Object> model = ImmutableMap.<String, Object>of("key", "model_val");
Map<String, Object> params = singletonMap("key", "param_val");
Map<String, Object> 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<String, Object> model = ImmutableMap.<String, Object>of("key", "model_val");
Map<String, Object> 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.<String, Object>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.<String, Object>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();

View File

@ -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<String, Object> vars = new HashMap<>();
Object data = randomFrom(
new Map[] { ImmutableMap.<String, Object>of("key", "foo"), ImmutableMap.<String, Object>of("key", "bar") },
Arrays.asList(ImmutableMap.<String, Object>of("key", "foo"), ImmutableMap.<String, Object>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.<String, Object>of("key", "foo"), ImmutableMap.<String, Object>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));

View File

@ -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<String, Object> map = ImmutableMap.<String, Object>builder()
.put("key", "value")
.build();
Map<String, Object> 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<String, Object> map = ImmutableMap.<String, Object>builder()
.put("key", list)
.build();
Map<String, Object> 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<String, Object> map = ImmutableMap.<String, Object>builder()
.put("key", array)
.build();
Map<String, Object> 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<String, Object> map = ImmutableMap.<String, Object>builder()
.put("a", ImmutableMap.of("b", "val"))
.build();
Map<String, Object> map = singletonMap("a", singletonMap("b", "val"));
assertThat(ObjectPath.eval("a.b", map), is((Object) "val"));
}

View File

@ -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.<String, Object>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<String, ActionStatus> 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.<String, ActionStatus>builder()
.put("_webhook", new ActionStatus(now))
.put("_email", new ActionStatus(now))
.build()));
new WatchStatus(now, statuses));
}
public static ScriptServiceProxy getScriptServiceProxy(ThreadPool tp) throws Exception {

View File

@ -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.<String, Schedule.Parser>emptyMap());
ScheduleRegistry scheduleRegistry = new ScheduleRegistry(emptyMap());
List<String> impls = new ArrayList<>(Arrays.asList(new String[]{"schedule", "ticker"}));
Collections.shuffle(impls);

View File

@ -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<String, TransformFactory> factories = ImmutableMap.<String, TransformFactory>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);

View File

@ -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<ActionWrapper>()),
null,
new WatchStatus( new DateTime(40000, UTC), ImmutableMap.<String, ActionStatus>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));

View File

@ -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.<String, Object>of("foo1", "bar1"))
.setAlternativeInput(singletonMap("foo1", "bar1"))
.get();
assertThat(response, notNullValue());
assertThat(response.getRecordId(), notNullValue());

View File

@ -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<String, Object> metadata = ImmutableMap.<String, Object>of("_key", "_val");
Map<String, Object> metadata = singletonMap("_key", "_val");
ImmutableMap.Builder<String, ActionStatus> actionsStatuses = ImmutableMap.builder();
Map<String, ActionStatus> 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<String, Schedule.Parser> parsers = ImmutableMap.builder();
Map<String, Schedule.Parser> 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.<String, Object>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<String, InputFactory> parsers = ImmutableMap.builder();
Map<String, InputFactory> 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<String, ConditionFactory> parsers = ImmutableMap.builder();
Map<String, ConditionFactory> 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<String, TransformFactory> factories = ImmutableMap.builder();
Map<String, TransformFactory> 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<String, ActionFactory> parsers = ImmutableMap.builder();
Map<String, ActionFactory> 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() {