Deprecate plugin Change-Id: I85a339229e5aa4b71351455a842c8ea04e88b48f
diff --git a/.buckconfig b/.buckconfig deleted file mode 100644 index 2b818b6..0000000 --- a/.buckconfig +++ /dev/null
@@ -1,16 +0,0 @@ -[alias] - sync-index = //:sync-index - plugin = //:sync-index - src = //:sync-index-sources - -[java] - jar_spool_mode = direct_to_jar - src_roots = java, resources - -[project] - ignore = .git, eclipse-out/ - parallel_parsing = true - -[cache] - mode = dir - dir = buck-out/cache
diff --git a/.gitignore b/.gitignore deleted file mode 100644 index c27e17f..0000000 --- a/.gitignore +++ /dev/null
@@ -1,9 +0,0 @@ -/.buckd/ -/.buckversion -/.classpath -/.project -/.settings/ -/.watchmanconfig -/buck-out/ -/bucklets -/eclipse-out/
diff --git a/BUCK b/BUCK deleted file mode 100644 index bd6696e..0000000 --- a/BUCK +++ /dev/null
@@ -1,84 +0,0 @@ -include_defs('//bucklets/gerrit_plugin.bucklet') -include_defs('//bucklets/java_sources.bucklet') -include_defs('//bucklets/maven_jar.bucklet') - -SOURCES = glob(['src/main/java/**/*.java']) -RESOURCES = glob(['src/main/resources/**/*']) - -DEPS = [ - ':wiremock', -] - -TEST_DEPS = GERRIT_PLUGIN_API + GERRIT_TESTS + DEPS + [ - ':sync-index__plugin', - ':mockito', -] - -gerrit_plugin( - name = 'sync-index', - srcs = SOURCES, - resources = RESOURCES, - manifest_entries = [ - 'Gerrit-PluginName: sync-index', - 'Gerrit-ApiType: plugin', - 'Gerrit-Module: com.ericsson.gerrit.plugins.syncindex.Module', - 'Gerrit-HttpModule: com.ericsson.gerrit.plugins.syncindex.HttpModule', - 'Implementation-Title: sync-index plugin', - 'Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/sync-index', - 'Implementation-Vendor: Ericsson', - ], - provided_deps = GERRIT_TESTS, - deps = DEPS, -) - -java_sources( - name = 'sync-index-sources', - srcs = SOURCES + RESOURCES, -) - -java_library( - name = 'classpath', - deps = TEST_DEPS, -) - -java_test( - name = 'sync-index_tests', - srcs = glob(['src/test/java/**/*.java']), - labels = ['sync-index'], - deps = TEST_DEPS, -) - -maven_jar( - name = 'wiremock', - id = 'com.github.tomakehurst:wiremock:1.58:standalone', - sha1 = '21c8386a95c5dc54a9c55839c5a95083e42412ae', - license = 'Apache2.0', - attach_source = False, -) - -maven_jar( - name = 'mockito', - id = 'org.mockito:mockito-core:2.5.0', - sha1 = 'be28d46a52c7f2563580adeca350145e9ce916f8', - license = 'MIT', - deps = [ - ':byte-buddy', - ':objenesis', - ], -) - -maven_jar( - name = 'byte-buddy', - id = 'net.bytebuddy:byte-buddy:1.5.12', - sha1 = 'b1ba1d15f102b36ed43b826488114678d6d413da', - license = 'DO_NOT_DISTRIBUTE', - attach_source = False, -) - -maven_jar( - name = 'objenesis', - id = 'org.objenesis:objenesis:2.4', - sha1 = '2916b6c96b50c5b3ec4452ed99401db745aabb27', - license = 'DO_NOT_DISTRIBUTE', - attach_source = False, -)
diff --git a/README-THIS-REPO-IS-DEPRECATED.txt b/README-THIS-REPO-IS-DEPRECATED.txt new file mode 100644 index 0000000..497ef2a --- /dev/null +++ b/README-THIS-REPO-IS-DEPRECATED.txt
@@ -0,0 +1,3 @@ +This plugin is deprecated. The functionality has been merged into + +https://gerrit-review.googlesource.com/#/admin/projects/plugins/high-availability
diff --git a/lib/gerrit/BUCK b/lib/gerrit/BUCK deleted file mode 100644 index f83d917..0000000 --- a/lib/gerrit/BUCK +++ /dev/null
@@ -1,22 +0,0 @@ -include_defs('//bucklets/maven_jar.bucklet') - -VER = '2.13' -REPO = MAVEN_CENTRAL - -maven_jar( - name = 'acceptance-framework', - id = 'com.google.gerrit:gerrit-acceptance-framework:' + VER, - sha1 = 'a6913a61196a8fccdb45e761f43a0b7e21867c90', - license = 'Apache2.0', - attach_source = False, - repository = REPO, -) - -maven_jar( - name = 'plugin-api', - id = 'com.google.gerrit:gerrit-plugin-api:' + VER, - sha1 = 'e25d55b8f41627c4ae6b9d2069ec398638b219a3', - license = 'Apache2.0', - attach_source = False, - repository = REPO, -)
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/Configuration.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/Configuration.java deleted file mode 100644 index a93ba84..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/Configuration.java +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.common.base.CharMatcher; -import com.google.common.base.Strings; -import com.google.gerrit.extensions.annotations.PluginName; -import com.google.gerrit.server.config.PluginConfig; -import com.google.gerrit.server.config.PluginConfigFactory; -import com.google.inject.Inject; -import com.google.inject.Singleton; - -@Singleton -class Configuration { - private static final int DEFAULT_TIMEOUT_MS = 5000; - private static final int DEFAULT_MAX_TRIES = 5; - private static final int DEFAULT_RETRY_INTERVAL = 1000; - private static final int DEFAULT_THREAD_POOL_SIZE = 1; - - private final String url; - private final String user; - private final String password; - private final int connectionTimeout; - private final int socketTimeout; - private final int maxTries; - private final int retryInterval; - private final int threadPoolSize; - - @Inject - Configuration(PluginConfigFactory config, - @PluginName String pluginName) { - PluginConfig cfg = config.getFromGerritConfig(pluginName, true); - url = Strings.nullToEmpty(cfg.getString("url")); - user = Strings.nullToEmpty(cfg.getString("user")); - password = Strings.nullToEmpty(cfg.getString("password")); - connectionTimeout = cfg.getInt("connectionTimeout", DEFAULT_TIMEOUT_MS); - socketTimeout = cfg.getInt("socketTimeout", DEFAULT_TIMEOUT_MS); - maxTries = cfg.getInt("maxTries", DEFAULT_MAX_TRIES); - retryInterval = cfg.getInt("retryInterval", DEFAULT_RETRY_INTERVAL); - threadPoolSize = cfg.getInt("threadPoolSize", DEFAULT_THREAD_POOL_SIZE); - } - - int getConnectionTimeout() { - return connectionTimeout; - } - - int getMaxTries() { - return maxTries; - } - - int getRetryInterval() { - return retryInterval; - } - - int getSocketTimeout() { - return socketTimeout; - } - - String getUrl() { - return CharMatcher.is('/').trimTrailingFrom(url); - } - - String getUser() { - return user; - } - - String getPassword() { - return password; - } - - public int getThreadPoolSize() { - return threadPoolSize; - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/Context.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/Context.java deleted file mode 100644 index 67abc1e..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/Context.java +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -/** - * Allows to tag a forwarded event to avoid infinitely looping events. - */ -class Context { - private static final ThreadLocal<Boolean> FORWARDED_EVENT = - new ThreadLocal<Boolean>() { - @Override - protected Boolean initialValue() { - return false; - } - }; - - private Context() { - } - - static Boolean isForwardedEvent() { - return FORWARDED_EVENT.get(); - } - - static void setForwardedEvent(Boolean b) { - FORWARDED_EVENT.set(b); - } - - static void unsetForwardedEvent() { - FORWARDED_EVENT.remove(); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java deleted file mode 100644 index 3b2f177..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java +++ /dev/null
@@ -1,194 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.inject.Inject; -import com.google.inject.Provider; - -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.ServiceUnavailableRetryStrategy; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.protocol.HttpContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.net.URI; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -/** - * Provides an HTTP client with SSL capabilities. - */ -class HttpClientProvider implements Provider<CloseableHttpClient> { - private static final Logger log = LoggerFactory - .getLogger(HttpClientProvider.class); - private static final int CONNECTIONS_PER_ROUTE = 100; - // Up to 2 target instances with the max number of connections per host: - private static final int MAX_CONNECTIONS = 2 * CONNECTIONS_PER_ROUTE; - - private static final int ERROR_CODES = 500; - private static final int MAX_CONNECTION_INACTIVITY = 10000; - - private final Configuration cfg; - private final SSLConnectionSocketFactory sslSocketFactory; - - @Inject - HttpClientProvider(Configuration cfg) { - this.cfg = cfg; - this.sslSocketFactory = buildSslSocketFactory(); - } - - @Override - public CloseableHttpClient get() { - return HttpClients.custom().setSSLSocketFactory(sslSocketFactory) - .setConnectionManager(customConnectionManager()) - .setDefaultCredentialsProvider(buildCredentials()) - .setDefaultRequestConfig(customRequestConfig()) - .setRetryHandler(customRetryHandler()) - .setServiceUnavailableRetryStrategy(customServiceUnavailRetryStrategy()) - .build(); - } - - private RequestConfig customRequestConfig() { - return RequestConfig.custom().setConnectTimeout(cfg.getConnectionTimeout()) - .setSocketTimeout(cfg.getSocketTimeout()) - .setConnectionRequestTimeout(cfg.getConnectionTimeout()) - .build(); - } - - private HttpRequestRetryHandler customRetryHandler() { - return new HttpRequestRetryHandler() { - - @Override - public boolean retryRequest(IOException exception, int executionCount, - HttpContext context) { - if (executionCount > cfg.getMaxTries() - || exception instanceof SSLException) { - return false; - } - logRetry(exception.getMessage()); - try { - Thread.sleep(cfg.getRetryInterval()); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - return true; - } - }; - } - - private ServiceUnavailableRetryStrategy customServiceUnavailRetryStrategy() { - return new ServiceUnavailableRetryStrategy() { - @Override - public boolean retryRequest(HttpResponse response, int executionCount, - HttpContext context) { - if (executionCount > cfg.getMaxTries()) { - return false; - } - if (response.getStatusLine().getStatusCode() >= ERROR_CODES) { - logRetry(response.getStatusLine().getReasonPhrase()); - return true; - } - return false; - } - - @Override - public long getRetryInterval() { - return cfg.getRetryInterval(); - } - }; - } - - private void logRetry(String cause) { - log.debug("Retrying request to '" + cfg.getUrl() + "' Cause: " + cause); - } - - private HttpClientConnectionManager customConnectionManager() { - Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder - .<ConnectionSocketFactory> create().register("https", sslSocketFactory) - .register("http", PlainConnectionSocketFactory.INSTANCE).build(); - PoolingHttpClientConnectionManager connManager = - new PoolingHttpClientConnectionManager(socketFactoryRegistry); - connManager.setDefaultMaxPerRoute(CONNECTIONS_PER_ROUTE); - connManager.setMaxTotal(MAX_CONNECTIONS); - connManager.setValidateAfterInactivity(MAX_CONNECTION_INACTIVITY); - return connManager; - } - - private SSLConnectionSocketFactory buildSslSocketFactory() { - return new SSLConnectionSocketFactory(buildSslContext(), - NoopHostnameVerifier.INSTANCE); - } - - private SSLContext buildSslContext() { - try { - TrustManager[] trustAllCerts = - new TrustManager[] {new DummyX509TrustManager()}; - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, trustAllCerts, null); - return context; - } catch (KeyManagementException | NoSuchAlgorithmException e) { - log.warn("Error building SSLContext object", e); - return null; - } - } - - private BasicCredentialsProvider buildCredentials() { - URI uri = URI.create(cfg.getUrl()); - BasicCredentialsProvider creds = new BasicCredentialsProvider(); - creds.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), - new UsernamePasswordCredentials(cfg.getUser(), cfg.getPassword())); - return creds; - } - - private static class DummyX509TrustManager implements X509TrustManager { - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - @Override - public void checkClientTrusted(X509Certificate[] certs, String authType) { - // no check - } - - @Override - public void checkServerTrusted(X509Certificate[] certs, String authType) { - // no check - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpModule.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpModule.java deleted file mode 100644 index 334c195..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpModule.java +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.gerrit.httpd.plugins.HttpPluginModule; - -class HttpModule extends HttpPluginModule { - @Override - protected void configureServlets() { - serveRegex("/index/\\d+$").with(SyncIndexRestApiServlet.class); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpSession.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpSession.java deleted file mode 100644 index 159acad..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpSession.java +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.inject.Inject; - -import com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.IndexResult; - -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; - -class HttpSession { - private final CloseableHttpClient httpClient; - private final String url; - - @Inject - HttpSession(CloseableHttpClient httpClient, - @SyncUrl String url) { - this.httpClient = httpClient; - this.url = url; - } - - IndexResult post(String endpoint) throws IOException { - return httpClient.execute(new HttpPost(url + endpoint), - new IndexResponseHandler()); - } - - IndexResult delete(String endpoint) throws IOException { - return httpClient.execute(new HttpDelete(url + endpoint), - new IndexResponseHandler()); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandler.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandler.java deleted file mode 100644 index 1027565..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandler.java +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.common.base.Objects; -import com.google.gerrit.extensions.annotations.PluginName; -import com.google.gerrit.extensions.events.ChangeIndexedListener; -import com.google.inject.Inject; - -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; - -class IndexEventHandler implements ChangeIndexedListener { - private final Executor executor; - private final RestSession restClient; - private final String pluginName; - private final Set<SyncIndexTask> queuedTasks = Collections - .newSetFromMap(new ConcurrentHashMap<SyncIndexTask, Boolean>()); - - @Inject - IndexEventHandler(@SyncIndexExecutor Executor executor, - @PluginName String pluginName, - RestSession restClient) { - this.restClient = restClient; - this.executor = executor; - this.pluginName = pluginName; - } - - @Override - public void onChangeIndexed(int id) { - executeIndexTask(id, false); - } - - @Override - public void onChangeDeleted(int id) { - executeIndexTask(id, true); - } - - private void executeIndexTask(int id, boolean deleted) { - if (!Context.isForwardedEvent()) { - SyncIndexTask syncIndexTask = new SyncIndexTask(id, deleted); - if (queuedTasks.add(syncIndexTask)) { - executor.execute(syncIndexTask); - } - } - } - - class SyncIndexTask implements Runnable { - private int changeId; - private boolean deleted; - - SyncIndexTask(int changeId, boolean deleted) { - this.changeId = changeId; - this.deleted = deleted; - } - - @Override - public void run() { - queuedTasks.remove(this); - if (deleted) { - restClient.deleteFromIndex(changeId); - } else { - restClient.index(changeId); - } - } - - @Override - public int hashCode() { - return Objects.hashCode(changeId, deleted); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SyncIndexTask)) { - return false; - } - SyncIndexTask other = (SyncIndexTask) obj; - return changeId == other.changeId && deleted == other.deleted; - } - - @Override - public String toString() { - return String.format("[%s] Index change %s in target instance", - pluginName, changeId); - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/IndexResponseHandler.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/IndexResponseHandler.java deleted file mode 100644 index 2d549ae..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/IndexResponseHandler.java +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; - -import com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.IndexResult; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ResponseHandler; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -class IndexResponseHandler implements ResponseHandler<IndexResult> { - - static class IndexResult { - private boolean successful; - private String message; - - IndexResult(boolean successful, String message) { - this.successful = successful; - this.message = message; - } - - boolean isSuccessful() { - return successful; - } - - String getMessage() { - return message; - } - } - - private static final Logger log = LoggerFactory - .getLogger(IndexResponseHandler.class); - - @Override - public IndexResult handleResponse(HttpResponse response) { - return new IndexResult(isSuccessful(response), parseResponse(response)); - } - - private boolean isSuccessful(HttpResponse response) { - return response.getStatusLine().getStatusCode() == SC_NO_CONTENT; - } - - private String parseResponse(HttpResponse response) { - HttpEntity entity = response.getEntity(); - String asString = ""; - if (entity != null) { - try { - asString = EntityUtils.toString(entity); - } catch (IOException e) { - log.error("Error parsing entity", e); - } - } - return asString; - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/Module.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/Module.java deleted file mode 100644 index 314d119..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/Module.java +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.gerrit.extensions.events.ChangeIndexedListener; -import com.google.gerrit.extensions.registration.DynamicSet; -import com.google.gerrit.lifecycle.LifecycleModule; -import com.google.inject.Provides; -import com.google.inject.Scopes; - -import org.apache.http.impl.client.CloseableHttpClient; - -import java.util.concurrent.Executor; - -class Module extends LifecycleModule { - - @Override - protected void configure() { - bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class) - .in(Scopes.SINGLETON); - bind(Configuration.class).in(Scopes.SINGLETON); - bind(HttpSession.class); - bind(RestSession.class); - bind(Executor.class) - .annotatedWith(SyncIndexExecutor.class) - .toProvider(SyncIndexExecutorProvider.class); - listener().to(SyncIndexExecutorProvider.class); - DynamicSet.bind(binder(), ChangeIndexedListener.class).to( - IndexEventHandler.class); - } - - @Provides - @SyncUrl - String syncUrl(Configuration config) { - return config.getUrl(); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/RestSession.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/RestSession.java deleted file mode 100644 index 9cdd4ea..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/RestSession.java +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.common.base.Joiner; -import com.google.gerrit.extensions.annotations.PluginName; -import com.google.inject.Inject; - -import com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.IndexResult; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -class RestSession { - private static final Logger log = LoggerFactory.getLogger(RestSession.class); - - private final HttpSession httpSession; - private final String pluginName; - - @Inject - RestSession(HttpSession httpClient, @PluginName String pluginName) { - this.httpSession = httpClient; - this.pluginName = pluginName; - } - - boolean index(int changeId) { - try { - IndexResult result = httpSession.post(buildEndpoint(changeId)); - if (result.isSuccessful()) { - return true; - } - log.error("Unable to index change {}. Cause: {}", changeId, - result.getMessage()); - } catch (IOException e) { - log.error("Error trying to index change " + changeId, e); - } - return false; - } - - boolean deleteFromIndex(int changeId) { - try { - IndexResult result = httpSession.delete(buildEndpoint(changeId)); - if (result.isSuccessful()) { - return true; - } - log.error("Unable to delete from index change {}. Cause: {}", changeId, - result.getMessage()); - } catch (IOException e) { - log.error("Error trying to delete from index change " + changeId, e); - } - return false; - } - - private String buildEndpoint(int changeId) { - return Joiner.on("/").join("/plugins", pluginName, "index", changeId); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutor.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutor.java deleted file mode 100644 index 75932e9..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutor.java +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import com.google.inject.BindingAnnotation; - -import java.lang.annotation.Retention; - -@Retention(RUNTIME) -@BindingAnnotation -@interface SyncIndexExecutor { -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutorProvider.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutorProvider.java deleted file mode 100644 index 0400506..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutorProvider.java +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import com.google.gerrit.extensions.events.LifecycleListener; -import com.google.gerrit.server.git.WorkQueue; -import com.google.inject.Inject; -import com.google.inject.Provider; -import com.google.inject.Singleton; - -import java.util.concurrent.Executor; - -@Singleton -class SyncIndexExecutorProvider implements Provider<Executor>, - LifecycleListener { - private WorkQueue.Executor executor; - - @Inject - SyncIndexExecutorProvider(WorkQueue workQueue, Configuration config) { - executor = - workQueue.createQueue(config.getThreadPoolSize(), "Sync remote index"); - } - - @Override - public void start() { - //do nothing - } - - @Override - public void stop() { - executor.shutdown(); - executor.unregisterWorkQueue(); - executor = null; - } - - @Override - public Executor get() { - return executor; - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexRestApiServlet.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexRestApiServlet.java deleted file mode 100644 index b066628..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexRestApiServlet.java +++ /dev/null
@@ -1,147 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; -import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; -import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; - -import com.google.gerrit.reviewdb.client.Change; -import com.google.gerrit.reviewdb.server.ReviewDb; -import com.google.gerrit.server.index.change.ChangeIndexer; -import com.google.gwtorm.server.OrmException; -import com.google.gwtorm.server.SchemaFactory; -import com.google.inject.Inject; -import com.google.inject.Singleton; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@Singleton -class SyncIndexRestApiServlet extends HttpServlet { - private static final long serialVersionUID = -1L; - private static final Logger logger = - LoggerFactory.getLogger(SyncIndexRestApiServlet.class); - private static final Map<Change.Id, AtomicInteger> changeIdLocks = - new HashMap<>(); - - private final ChangeIndexer indexer; - private final SchemaFactory<ReviewDb> schemaFactory; - - @Inject - SyncIndexRestApiServlet(ChangeIndexer indexer, - SchemaFactory<ReviewDb> schemaFactory) { - this.indexer = indexer; - this.schemaFactory = schemaFactory; - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse rsp) - throws IOException, ServletException { - process(req, rsp, "index"); - } - - @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse rsp) - throws IOException, ServletException { - process(req, rsp, "delete"); - } - - private void process(HttpServletRequest req, HttpServletResponse rsp, - String operation) { - rsp.setContentType("text/plain"); - rsp.setCharacterEncoding("UTF-8"); - String path = req.getPathInfo(); - String changeId = path.substring(path.lastIndexOf('/') + 1); - Change.Id id = Change.Id.parse(changeId); - try { - Context.setForwardedEvent(true); - index(id, operation); - rsp.setStatus(SC_NO_CONTENT); - } catch (IOException e) { - sendError(rsp,SC_CONFLICT, e.getMessage()); - logger.error("Unable to update index", e); - } catch (OrmException e) { - String msg = "Error trying to find a change \n"; - sendError(rsp,SC_NOT_FOUND, msg); - logger.debug(msg, e); - } finally { - Context.unsetForwardedEvent(); - } - } - - private static void sendError(HttpServletResponse rsp, int statusCode, - String message) { - try { - rsp.sendError(statusCode, message); - } catch (IOException e) { - logger.error("Failed to send error messsage: " + e.getMessage(), e); - } - } - - private void index(Change.Id id, String operation) - throws IOException, OrmException { - AtomicInteger changeIdLock = getAndIncrementChangeIdLock(id); - synchronized (changeIdLock) { - if ("index".equals(operation)) { - try (ReviewDb db = schemaFactory.open()) { - Change change = db.changes().get(id); - if (change == null) { - indexer.delete(id); - return; - } - indexer.index(db, change); - } - logger.debug("Change {} successfully indexed", id); - } - if ("delete".equals(operation)) { - indexer.delete(id); - logger.debug("Change {} successfully deleted from index", id); - } - } - if (changeIdLock.decrementAndGet() == 0) { - removeChangeIdLock(id); - } - } - - private AtomicInteger getAndIncrementChangeIdLock(Change.Id id) { - synchronized (changeIdLocks) { - AtomicInteger changeIdLock = changeIdLocks.get(id); - if (changeIdLock == null) { - changeIdLock = new AtomicInteger(1); - changeIdLocks.put(id, changeIdLock); - } else { - changeIdLock.incrementAndGet(); - } - return changeIdLock; - } - } - - private void removeChangeIdLock(Change.Id id) { - synchronized (changeIdLocks) { - changeIdLocks.remove(id); - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncUrl.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncUrl.java deleted file mode 100644 index 8b3ac1a..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/SyncUrl.java +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import com.google.inject.BindingAnnotation; - -import java.lang.annotation.Retention; - -@Retention(RUNTIME) -@BindingAnnotation -@interface SyncUrl { -}
diff --git a/src/main/resources/Documentation/about.md b/src/main/resources/Documentation/about.md deleted file mode 100644 index f104962..0000000 --- a/src/main/resources/Documentation/about.md +++ /dev/null
@@ -1,11 +0,0 @@ -The @PLUGIN@ plugin allows to synchronize secondary indexes between two Gerrit -instances sharing the same git repositories and database. - -The plugin is installed in both instances and every time the secondary index -is modified in one of the instances, i.e., a change is added, updated or removed -from the index, the other instance index is updated accordingly. This way, both -indexes are kept synchronized. - -For this secondary index synchronization to work, http must be enabled in both -instances and the plugin must be configured with valid credentials. For further -information, refer to [config](config.md) documentation.
diff --git a/src/main/resources/Documentation/build.md b/src/main/resources/Documentation/build.md deleted file mode 100644 index 3babed2..0000000 --- a/src/main/resources/Documentation/build.md +++ /dev/null
@@ -1,106 +0,0 @@ -Build -===== - -This plugin is built with Buck. - -Two build modes are supported: Standalone and in Gerrit tree. Standalone -build mode is recommended, as this mode doesn't require local Gerrit -tree to exist. - -Build standalone ----------------- - -Clone bucklets library: - -``` - git clone https://gerrit.googlesource.com/bucklets - -``` -and link it to @PLUGIN@ directory: - -``` - cd @PLUGIN@ && ln -s ../bucklets . -``` - -Add link to the .buckversion file: - -``` - cd @PLUGIN@ && ln -s bucklets/buckversion .buckversion -``` - -Add link to the .watchmanconfig file: - -``` - cd @PLUGIN@ && ln -s bucklets/watchmanconfig .watchmanconfig -``` - -To build the plugin, issue the following command: - -``` - buck build plugin -``` - -The output is created in: - -``` - buck-out/gen/@PLUGIN@.jar -``` - -This project can be imported into the Eclipse IDE: - -``` - ./bucklets/tools/eclipse.py -``` - -To execute the tests run: - -``` - buck test -``` - -To build plugin sources run: - -``` - buck build src -``` - -The output is created in: - -``` - buck-out/gen/@PLUGIN@-sources.jar -``` - -Build in Gerrit tree --------------------- - -Clone or link this plugin to the plugins directory of Gerrit's source -tree, and issue the command: - -``` - buck build plugins/@PLUGIN@ -``` - -The output is created in: - -``` - buck-out/gen/plugins/@PLUGIN@/@PLUGIN@.jar -``` - -This project can be imported into the Eclipse IDE: - -``` - ./tools/eclipse/project.py -``` - -To execute the tests run: - -``` - buck test --include @PLUGIN@ -``` - -How to build the Gerrit Plugin API is described in the [Gerrit -documentation](../../../Documentation/dev-buck.html#_extension_and_plugin_api_jar_files). - -[Back to @PLUGIN@ documentation index][index] - -[index]: index.html
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md deleted file mode 100644 index 48b9e94..0000000 --- a/src/main/resources/Documentation/config.md +++ /dev/null
@@ -1,51 +0,0 @@ -@PLUGIN@ Configuration -========================= - -In order for the synchronization to work, the @PLUGIN@ plugin must be installed -in both instances and the following fields should be specified in the -corresponding Gerrit configuration file: - -File 'gerrit.config' --------------------- - -[plugin "@PLUGIN@"] -: url = target_instance_url -: user = username -: password = password - -plugin.@PLUGIN@.url -: Specify the URL for the secondary (target) instance. - -plugin.@PLUGIN@.user -: Username to connect to the secondary (target) instance. - -plugin.@PLUGIN@.password -: Password to connect to the secondary (target) instance. This value can - also be defined in secure.config. - -@PLUGIN@ plugin uses REST API calls to index changes in the target instance. It -is possible to customize the parameters of the underlying http client doing these -calls by specifying the following fields: - -@PLUGIN@.connectionTimeout -: Maximum interval of time in milliseconds the plugin waits for a connection - to the target instance. When not specified, the default value is set to 5000ms. - -@PLUGIN@.socketTimeout -: Maximum interval of time in milliseconds the plugin waits for a response from the - target instance once the connection has been established. When not specified, - the default value is set to 5000ms. - -@PLUGIN@.maxTries -: Maximum number of times the plugin should attempt to index the event in the - target instance. Setting this value to 0 will disable retries. When not - specified, the default value is 5. After this number of failed tries, an error - is logged so that admins can re-index the change manually. - -@PLUGIN@.retryInterval -: The interval of time in milliseconds between the subsequent auto-retries. - When not specified, the default value is set to 1000ms. - -@PLUGIN@.threadPoolSize -: Maximum number of threads used to send index events to the target instance. - Defaults to 1.
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/ConfigurationTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/ConfigurationTest.java deleted file mode 100644 index aab72d3..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/ConfigurationTest.java +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.when; - -import com.google.gerrit.server.config.PluginConfig; -import com.google.gerrit.server.config.PluginConfigFactory; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class ConfigurationTest { - private static final String PASS = "fakePass"; - private static final String USER = "fakeUser"; - private static final String URL = "fakeUrl"; - private static final String EMPTY = ""; - private static final boolean CUSTOM_VALUES = true; - private static final boolean DEFAULT_VALUES = false; - private static final int TIMEOUT = 5000; - private static final int MAX_TRIES = 5; - private static final int RETRY_INTERVAL = 1000; - private static final int THREAD_POOL_SIZE = 1; - - @Mock - private PluginConfigFactory cfgFactoryMock; - @Mock - private PluginConfig configMock; - private Configuration configuration; - private String pluginName = "sync-events"; - - @Before - public void setUp() throws Exception { - when(cfgFactoryMock.getFromGerritConfig(pluginName, true)) - .thenReturn(configMock); - } - - @Test - public void testValuesPresentInGerritConfig() throws Exception { - buildMocks(CUSTOM_VALUES); - assertThat(configuration.getUrl()).isEqualTo(URL); - assertThat(configuration.getUser()).isEqualTo(USER); - assertThat(configuration.getPassword()).isEqualTo(PASS); - assertThat(configuration.getConnectionTimeout()).isEqualTo(TIMEOUT); - assertThat(configuration.getSocketTimeout()).isEqualTo(TIMEOUT); - assertThat(configuration.getMaxTries()).isEqualTo(MAX_TRIES); - assertThat(configuration.getRetryInterval()).isEqualTo(RETRY_INTERVAL); - assertThat(configuration.getThreadPoolSize()).isEqualTo(THREAD_POOL_SIZE); - } - - @Test - public void testValuesNotPresentInGerritConfig() throws Exception { - buildMocks(DEFAULT_VALUES); - assertThat(configuration.getUrl()).isEqualTo(EMPTY); - assertThat(configuration.getUser()).isEqualTo(EMPTY); - assertThat(configuration.getPassword()).isEqualTo(EMPTY); - assertThat(configuration.getConnectionTimeout()).isEqualTo(0); - assertThat(configuration.getSocketTimeout()).isEqualTo(0); - assertThat(configuration.getMaxTries()).isEqualTo(0); - assertThat(configuration.getRetryInterval()).isEqualTo(0); - assertThat(configuration.getThreadPoolSize()).isEqualTo(0); - } - - @Test - public void testUrlTrailingSlashIsDropped() throws Exception { - when(configMock.getString("url")).thenReturn(URL + "/"); - - configuration = new Configuration(cfgFactoryMock, pluginName); - assertThat(configuration).isNotNull(); - assertThat(configuration.getUrl()).isEqualTo(URL); - } - - private void buildMocks(boolean values) { - when(configMock.getString("url")).thenReturn(values ? URL : null); - when(configMock.getString("user")).thenReturn(values ? USER : null); - when(configMock.getString("password")).thenReturn(values ? PASS : null); - when(configMock.getInt("connectionTimeout", TIMEOUT)) - .thenReturn(values ? TIMEOUT : 0); - when(configMock.getInt("socketTimeout", TIMEOUT)) - .thenReturn(values ? TIMEOUT : 0); - when(configMock.getInt("maxTries", MAX_TRIES)) - .thenReturn(values ? MAX_TRIES : 0); - when(configMock.getInt("retryInterval", RETRY_INTERVAL)) - .thenReturn(values ? RETRY_INTERVAL : 0); - when(configMock.getInt("threadPoolSize", THREAD_POOL_SIZE)) - .thenReturn(values ? THREAD_POOL_SIZE : 0); - - configuration = new Configuration(cfgFactoryMock, pluginName); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/ContextTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/ContextTest.java deleted file mode 100644 index a6898b5..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/ContextTest.java +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; - - -import org.junit.Test; - -public class ContextTest { - - @Test - public void testInitialValueNotNull() throws Exception { - assertThat(Context.isForwardedEvent()).isNotNull(); - assertThat(Context.isForwardedEvent()).isFalse(); - } - - @Test - public void testSetForwardedEvent() throws Exception { - Context.setForwardedEvent(true); - try { - assertThat(Context.isForwardedEvent()).isTrue(); - } finally { - Context.unsetForwardedEvent(); - } - } - - @Test - public void testUnsetForwardedEvent() throws Exception { - Context.setForwardedEvent(true); - Context.unsetForwardedEvent(); - assertThat(Context.isForwardedEvent()).isFalse(); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProviderTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProviderTest.java deleted file mode 100644 index 68577b8..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProviderTest.java +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.when; - -import com.google.gerrit.lifecycle.LifecycleModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Scopes; - -import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class HttpClientProviderTest { - private static final int TIME_INTERVAL = 1000; - private static final String EMPTY = ""; - - @Mock - private Configuration config; - - @Before - public void setUp() throws Exception { - when(config.getUrl()).thenReturn(EMPTY); - when(config.getUser()).thenReturn(EMPTY); - when(config.getPassword()).thenReturn(EMPTY); - when(config.getConnectionTimeout()).thenReturn(TIME_INTERVAL); - when(config.getSocketTimeout()).thenReturn(TIME_INTERVAL); - } - - @Test - public void testGet() throws Exception { - Injector injector = Guice.createInjector(new TestModule()); - CloseableHttpClient httpClient1 = - injector.getInstance(CloseableHttpClient.class); - assertThat(httpClient1).isNotNull(); - CloseableHttpClient httpClient2 = - injector.getInstance(CloseableHttpClient.class); - assertThat(httpClient1).isEqualTo(httpClient2); - } - - class TestModule extends LifecycleModule { - @Override - protected void configure() { - bind(Configuration.class).toInstance(config); - bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class) - .in(Scopes.SINGLETON); - } - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/HttpSessionTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/HttpSessionTest.java deleted file mode 100644 index f83b499..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/HttpSessionTest.java +++ /dev/null
@@ -1,200 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.IndexResult; -import com.github.tomakehurst.wiremock.http.Fault; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import com.github.tomakehurst.wiremock.stubbing.Scenario; - - -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.net.SocketTimeoutException; - -public class HttpSessionTest { - private static final int MAX_TRIES = 3; - private static final int RETRY_INTERVAL = 250; - private static final int TIMEOUT = 500; - private static final int ERROR = 500; - private static final int OK = 204; - private static final int NOT_FOUND = 404; - private static final int UNAUTHORIZED = 401; - - private static final String ENDPOINT = "/plugins/sync-index/index/1"; - private static final String ERROR_MESSAGE = "Error message"; - private static final String REQUEST_MADE = "Request made"; - private static final String SECOND_TRY = "Second try"; - private static final String THIRD_TRY = "Third try"; - private static final String RETRY_AT_ERROR = "Retry at error"; - private static final String RETRY_AT_DELAY = "Retry at delay"; - - private HttpSession httpSession; - - @ClassRule - public static WireMockRule wireMockRule = new WireMockRule(0); - - @Before - public void setUp() throws Exception { - String url = "http://localhost:" + wireMockRule.port(); - Configuration cfg = mock(Configuration.class); - when(cfg.getUrl()).thenReturn(url); - when(cfg.getUser()).thenReturn("user"); - when(cfg.getPassword()).thenReturn("pass"); - when(cfg.getMaxTries()).thenReturn(MAX_TRIES); - when(cfg.getConnectionTimeout()).thenReturn(TIMEOUT); - when(cfg.getSocketTimeout()).thenReturn(TIMEOUT); - when(cfg.getRetryInterval()).thenReturn(RETRY_INTERVAL); - - httpSession = - new HttpSession(new HttpClientProvider(cfg).get(), url); - wireMockRule.resetRequests(); - } - - @Test - public void testPostResponseOK() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.post(ENDPOINT).isSuccessful()).isTrue(); - } - - @Test - public void testDeleteResponseOK() throws Exception { - wireMockRule.givenThat(delete(urlEqualTo(ENDPOINT)) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.delete(ENDPOINT).isSuccessful()).isTrue(); - } - - @Test - public void testNotAuthorized() throws Exception { - String expected = "unauthorized"; - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)) - .willReturn(aResponse().withStatus(UNAUTHORIZED).withBody(expected))); - - IndexResult result = httpSession.post(ENDPOINT); - assertThat(result.isSuccessful()).isFalse(); - assertThat(result.getMessage()).isEqualTo(expected); - } - - @Test - public void testNotFound() throws Exception { - String expected = "not found"; - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)) - .willReturn(aResponse().withStatus(NOT_FOUND).withBody(expected))); - - IndexResult result = httpSession.post(ENDPOINT); - assertThat(result.isSuccessful()).isFalse(); - assertThat(result.getMessage()).isEqualTo(expected); - } - - @Test - public void testBadResponseRetryThenOK() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_ERROR) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withStatus(ERROR))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_ERROR) - .whenScenarioStateIs(REQUEST_MADE) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.post(ENDPOINT).isSuccessful()).isTrue(); - } - - @Test - public void testBadResponseRetryThenGiveUp() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)) - .willReturn(aResponse().withStatus(ERROR).withBody(ERROR_MESSAGE))); - - IndexResult result = httpSession.post(ENDPOINT); - assertThat(result.isSuccessful()).isFalse(); - assertThat(result.getMessage()).isEqualTo(ERROR_MESSAGE); - } - - @Test - public void testRetryAfterDelay() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withStatus(ERROR).withFixedDelay(TIMEOUT / 2))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(REQUEST_MADE) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.post(ENDPOINT).isSuccessful()).isTrue(); - } - - @Test - public void testRetryAfterTimeoutThenOK() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(REQUEST_MADE).willSetStateTo(SECOND_TRY) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(SECOND_TRY).willSetStateTo(THIRD_TRY) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(THIRD_TRY) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.post(ENDPOINT).isSuccessful()).isTrue(); - } - - @Test(expected = SocketTimeoutException.class) - public void testMaxRetriesAfterTimeoutThenGiveUp() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(REQUEST_MADE).willSetStateTo(SECOND_TRY) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(SECOND_TRY).willSetStateTo(THIRD_TRY) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(THIRD_TRY) - .willReturn(aResponse().withFixedDelay(TIMEOUT))); - - httpSession.post(ENDPOINT); - } - - @Test - public void testGiveUpAtTimeout() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withStatus(ERROR).withFixedDelay(TIMEOUT))); - - assertThat(httpSession.post(ENDPOINT).isSuccessful()).isFalse(); - } - - @Test - public void testResponseWithMalformedResponse() throws Exception { - wireMockRule.givenThat(post(urlEqualTo(ENDPOINT)) - .willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK))); - - assertThat(httpSession.post(ENDPOINT).isSuccessful()).isFalse(); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java deleted file mode 100644 index 045aefa..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java +++ /dev/null
@@ -1,127 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -import com.google.common.util.concurrent.MoreExecutors; -import com.google.gerrit.reviewdb.client.Change; -import com.google.gerrit.server.git.WorkQueue.Executor; -import com.google.gwtorm.client.KeyUtil; -import com.google.gwtorm.server.StandardKeyEncoder; - -import com.ericsson.gerrit.plugins.syncindex.IndexEventHandler.SyncIndexTask; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class IndexEventHandlerTest { - private static final String PLUGIN_NAME = "sync-index"; - private static final int CHANGE_ID = 1; - - private IndexEventHandler indexEventHandler; - @Mock - private RestSession restSessionMock; - private Change.Id id; - - @BeforeClass - public static void setUp() { - KeyUtil.setEncoderImpl(new StandardKeyEncoder()); - } - - @Before - public void setUpMocks() { - id = Change.Id.parse(Integer.toString(CHANGE_ID)); - indexEventHandler = new IndexEventHandler(MoreExecutors.directExecutor(), - PLUGIN_NAME, restSessionMock); - } - - @Test - public void shouldIndexInRemoteOnChangeIndexedEvent() throws Exception { - indexEventHandler.onChangeIndexed(id.get()); - verify(restSessionMock).index(CHANGE_ID); - } - - @Test - public void shouldDeleteFromIndexInRemoteOnChangeDeletedEvent() - throws Exception { - indexEventHandler.onChangeDeleted(id.get()); - verify(restSessionMock).deleteFromIndex(CHANGE_ID); - } - - @Test - public void shouldNotCallRemoteWhenEventIsForwarded() throws Exception { - Context.setForwardedEvent(true); - indexEventHandler.onChangeIndexed(id.get()); - indexEventHandler.onChangeDeleted(id.get()); - Context.unsetForwardedEvent(); - verifyZeroInteractions(restSessionMock); - } - - @Test - public void duplicateEventOfAQueuedEventShouldGetDiscarded() { - Executor poolMock = mock(Executor.class); - indexEventHandler = - new IndexEventHandler(poolMock, PLUGIN_NAME, restSessionMock); - indexEventHandler.onChangeIndexed(id.get()); - indexEventHandler.onChangeIndexed(id.get()); - verify(poolMock, times(1)) - .execute(indexEventHandler.new SyncIndexTask(CHANGE_ID, false)); - } - - @Test - public void testSyncIndexTaskToString() throws Exception { - SyncIndexTask syncIndexTask = - indexEventHandler.new SyncIndexTask(CHANGE_ID, false); - assertThat(syncIndexTask.toString()).isEqualTo(String.format( - "[%s] Index change %s in target instance", PLUGIN_NAME, CHANGE_ID)); - } - - @Test - public void testSyncIndexTaskHashCodeAndEquals() { - SyncIndexTask task = indexEventHandler.new SyncIndexTask(CHANGE_ID, false); - - assertThat(task.equals(task)).isTrue(); - assertThat(task.hashCode()).isEqualTo(task.hashCode()); - - SyncIndexTask identicalTask = - indexEventHandler.new SyncIndexTask(CHANGE_ID, false); - assertThat(task.equals(identicalTask)).isTrue(); - assertThat(task.hashCode()).isEqualTo(identicalTask.hashCode()); - - assertThat(task.equals(null)).isFalse(); - assertThat(task.equals("test")).isFalse(); - assertThat(task.hashCode()).isNotEqualTo("test".hashCode()); - - SyncIndexTask differentChangeIdTask = - indexEventHandler.new SyncIndexTask(123, false); - assertThat(task.equals(differentChangeIdTask)).isFalse(); - assertThat(task.hashCode()).isNotEqualTo(differentChangeIdTask.hashCode()); - - SyncIndexTask removeTask = - indexEventHandler.new SyncIndexTask(CHANGE_ID, true); - assertThat(task.equals(removeTask)).isFalse(); - assertThat(task.hashCode()).isNotEqualTo(removeTask.hashCode()); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexResponseHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexResponseHandlerTest.java deleted file mode 100644 index 46488b7..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexResponseHandlerTest.java +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.IndexResult; - -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.entity.StringEntity; -import org.junit.Before; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; - -public class IndexResponseHandlerTest { - private static final int ERROR = 400; - private static final int OK = 204; - private static final String EMPTY_ENTITY = ""; - private static final String ERROR_ENTITY = "Error"; - - private IndexResponseHandler handler; - - @Before - public void setUp() throws Exception { - handler = new IndexResponseHandler(); - } - - @Test - public void testIsSuccessful() throws Exception { - HttpResponse response = setupMocks(OK, EMPTY_ENTITY); - IndexResult result = handler.handleResponse(response); - assertThat(result.isSuccessful()).isTrue(); - assertThat(result.getMessage()).isEmpty(); - } - - @Test - public void testIsNotSuccessful() throws Exception { - HttpResponse response = setupMocks(ERROR, ERROR_ENTITY); - IndexResult result = handler.handleResponse(response); - assertThat(result.isSuccessful()).isFalse(); - assertThat(result.getMessage()).contains(ERROR_ENTITY); - } - - private HttpResponse setupMocks(int httpCode, String entity) - throws UnsupportedEncodingException { - StatusLine status = mock(StatusLine.class); - when(status.getStatusCode()).thenReturn(httpCode); - HttpResponse response = mock(HttpResponse.class); - when(response.getStatusLine()).thenReturn(status); - when(response.getEntity()).thenReturn(new StringEntity(entity)); - return response; - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/ModuleTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/ModuleTest.java deleted file mode 100644 index f997afa..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/ModuleTest.java +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Test; - -public class ModuleTest { - - @Test - public void testSyncUrlProvider() { - Configuration configMock = mock(Configuration.class); - String expected = "someUrl"; - when(configMock.getUrl()).thenReturn(expected); - Module module = new Module(); - assertThat(module.syncUrl(configMock)).isEqualTo(expected); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/RestSessionTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/RestSessionTest.java deleted file mode 100644 index 6f716c4..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/RestSessionTest.java +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.common.base.Joiner; - -import com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.IndexResult; - -import org.junit.Test; - -import java.io.IOException; - -public class RestSessionTest { - private static final int CHANGE_NUMBER = 1; - private static final String DELETE_OP = "delete"; - private static final String INDEX_OP = "index"; - private static final String PLUGIN_NAME = "sync-index"; - private static final String EMPTY_MSG = ""; - private static final String ERROR_MSG = "Error"; - private static final String EXCEPTION_MSG = "Exception"; - private static final boolean SUCCESSFUL = true; - private static final boolean FAILED = false; - private static final boolean DO_NOT_THROW_EXCEPTION = false; - private static final boolean THROW_EXCEPTION = true; - - private RestSession restClient; - - @Test - public void testIndexChangeOK() throws Exception { - setUpMocks(INDEX_OP, SUCCESSFUL, EMPTY_MSG, DO_NOT_THROW_EXCEPTION); - assertThat(restClient.index(CHANGE_NUMBER)).isTrue(); - } - - @Test - public void testIndexChangeFailed() throws Exception { - setUpMocks(INDEX_OP, FAILED, ERROR_MSG, DO_NOT_THROW_EXCEPTION); - assertThat(restClient.index(CHANGE_NUMBER)).isFalse(); - } - - @Test - public void testIndexChangeThrowsException() throws Exception { - setUpMocks(INDEX_OP, FAILED, EXCEPTION_MSG, THROW_EXCEPTION); - assertThat(restClient.index(CHANGE_NUMBER)).isFalse(); - } - - @Test - public void testChangeDeletedFromIndexOK() throws Exception { - setUpMocks(DELETE_OP, SUCCESSFUL, EMPTY_MSG, DO_NOT_THROW_EXCEPTION); - assertThat(restClient.deleteFromIndex(CHANGE_NUMBER)).isTrue(); - } - - @Test - public void testChangeDeletedFromIndexFailed() throws Exception { - setUpMocks(DELETE_OP, FAILED, ERROR_MSG, DO_NOT_THROW_EXCEPTION); - assertThat(restClient.deleteFromIndex(CHANGE_NUMBER)).isFalse(); - } - - @Test - public void testChangeDeletedFromThrowsException() throws Exception { - setUpMocks(DELETE_OP, FAILED, EXCEPTION_MSG, THROW_EXCEPTION); - assertThat(restClient.deleteFromIndex(CHANGE_NUMBER)).isFalse(); - } - - private void setUpMocks(String operation, boolean isOperationSuccessful, - String msg, boolean exception) throws Exception { - String request = - Joiner.on("/").join("/plugins", PLUGIN_NAME, INDEX_OP, CHANGE_NUMBER); - HttpSession httpSession = mock(HttpSession.class); - if (exception) { - if (operation.equals(INDEX_OP)) { - doThrow(new IOException()).when(httpSession).post(request); - } else { - doThrow(new IOException()).when(httpSession).delete(request); - } - } else { - IndexResult result = new IndexResult(isOperationSuccessful, msg); - if (operation.equals(INDEX_OP)) { - when(httpSession.post(request)).thenReturn(result); - } else { - when(httpSession.delete(request)).thenReturn(result); - } - } - restClient = new RestSession(httpSession, PLUGIN_NAME); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutorProviderTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutorProviderTest.java deleted file mode 100644 index a48dd9b..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexExecutorProviderTest.java +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright (C) 2015 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.gerrit.server.git.WorkQueue; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class SyncIndexExecutorProviderTest { - @Mock - private WorkQueue.Executor executorMock; - private SyncIndexExecutorProvider syncIndexExecutorProvider; - - @Before - public void setUp() throws Exception { - executorMock = mock(WorkQueue.Executor.class); - WorkQueue workQueueMock = mock(WorkQueue.class); - when(workQueueMock.createQueue(4, "Sync remote index")) - .thenReturn(executorMock); - Configuration configMock = mock(Configuration.class); - when(configMock.getThreadPoolSize()).thenReturn(4); - syncIndexExecutorProvider = - new SyncIndexExecutorProvider(workQueueMock, configMock); - } - - @Test - public void shouldReturnExecutor() throws Exception { - assertThat(syncIndexExecutorProvider.get()).isEqualTo(executorMock); - } - - @Test - public void testStop() throws Exception { - syncIndexExecutorProvider.start(); - assertThat(syncIndexExecutorProvider.get()).isEqualTo(executorMock); - syncIndexExecutorProvider.stop(); - verify(executorMock).shutdown(); - verify(executorMock).unregisterWorkQueue(); - assertThat(syncIndexExecutorProvider.get()).isNull(); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexRestApiServletTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexRestApiServletTest.java deleted file mode 100644 index 7e8ac83..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/SyncIndexRestApiServletTest.java +++ /dev/null
@@ -1,170 +0,0 @@ -// Copyright (C) 2016 Ericsson -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.ericsson.gerrit.plugins.syncindex; - -import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; -import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; -import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import com.google.gerrit.common.TimeUtil; -import com.google.gerrit.reviewdb.client.Change; -import com.google.gerrit.reviewdb.server.ChangeAccess; -import com.google.gerrit.reviewdb.server.ReviewDb; -import com.google.gerrit.server.index.change.ChangeIndexer; -import com.google.gwtorm.client.KeyUtil; -import com.google.gwtorm.server.OrmException; -import com.google.gwtorm.server.SchemaFactory; -import com.google.gwtorm.server.StandardKeyEncoder; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@RunWith(MockitoJUnitRunner.class) -public class SyncIndexRestApiServletTest { - private static final boolean CHANGE_EXISTS = true; - private static final boolean CHANGE_DOES_NOT_EXIST = false; - private static final boolean DO_NOT_THROW_IO_EXCEPTION = false; - private static final boolean DO_NOT_THROW_ORM_EXCEPTION = false; - private static final boolean THROW_IO_EXCEPTION = true; - private static final boolean THROW_ORM_EXCEPTION = true; - private static final String CHANGE_NUMBER = "1"; - - @Mock - private ChangeIndexer indexer; - @Mock - private SchemaFactory<ReviewDb> schemaFactory; - @Mock - private ReviewDb db; - @Mock - private HttpServletRequest req; - @Mock - private HttpServletResponse rsp; - private Change.Id id; - private Change change; - private SyncIndexRestApiServlet syncIndexRestApiServlet; - - @BeforeClass - public static void setup() { - KeyUtil.setEncoderImpl(new StandardKeyEncoder()); - } - - @Before - public void setUpMocks() { - syncIndexRestApiServlet = - new SyncIndexRestApiServlet(indexer, schemaFactory); - id = Change.Id.parse(CHANGE_NUMBER); - when(req.getPathInfo()).thenReturn("/index/" + CHANGE_NUMBER); - change = new Change(null, id, null, null, TimeUtil.nowTs()); - } - - @Test - public void changeIsIndexed() throws Exception { - setupPostMocks(CHANGE_EXISTS); - syncIndexRestApiServlet.doPost(req, rsp); - verify(indexer, times(1)).index(db, change); - verify(rsp).setStatus(SC_NO_CONTENT); - } - - @Test - public void changeToIndexDoNotExist() throws Exception { - setupPostMocks(CHANGE_DOES_NOT_EXIST); - syncIndexRestApiServlet.doPost(req, rsp); - verify(indexer, times(1)).delete(id); - verify(rsp).setStatus(SC_NO_CONTENT); - } - - @Test - public void schemaThrowsExceptionWhenLookingUpForChange() throws Exception { - setupPostMocks(CHANGE_EXISTS, THROW_ORM_EXCEPTION); - syncIndexRestApiServlet.doPost(req, rsp); - verify(rsp).sendError(SC_NOT_FOUND, "Error trying to find a change \n"); - } - - @Test - public void indexerThrowsIOExceptionTryingToIndexChange() throws Exception { - setupPostMocks(CHANGE_EXISTS, DO_NOT_THROW_ORM_EXCEPTION, - THROW_IO_EXCEPTION); - syncIndexRestApiServlet.doPost(req, rsp); - verify(rsp).sendError(SC_CONFLICT, "io-error"); - } - - @Test - public void changeIsDeletedFromIndex() throws Exception { - syncIndexRestApiServlet.doDelete(req, rsp); - verify(indexer, times(1)).delete(id); - verify(rsp).setStatus(SC_NO_CONTENT); - } - - @Test - public void indexerThrowsExceptionTryingToDeleteChange() throws Exception { - doThrow(new IOException("io-error")).when(indexer).delete(id); - syncIndexRestApiServlet.doDelete(req, rsp); - verify(rsp).sendError(SC_CONFLICT, "io-error"); - } - - @Test - public void sendErrorThrowsIOException() throws Exception { - doThrow(new IOException("someError")).when(rsp).sendError(SC_NOT_FOUND, - "Error trying to find a change \n"); - setupPostMocks(CHANGE_EXISTS, THROW_ORM_EXCEPTION); - syncIndexRestApiServlet.doPost(req, rsp); - verify(rsp).sendError(SC_NOT_FOUND, "Error trying to find a change \n"); - verifyZeroInteractions(indexer); - } - - private void setupPostMocks(boolean changeExist) throws Exception { - setupPostMocks(changeExist, DO_NOT_THROW_ORM_EXCEPTION, - DO_NOT_THROW_IO_EXCEPTION); - } - - private void setupPostMocks(boolean changeExist, boolean ormException) - throws OrmException, IOException { - setupPostMocks(changeExist, ormException, DO_NOT_THROW_IO_EXCEPTION); - } - - private void setupPostMocks(boolean changeExist, boolean ormException, - boolean ioException) throws OrmException, IOException { - if (ormException) { - doThrow(new OrmException("")).when(schemaFactory).open(); - } else { - when(schemaFactory.open()).thenReturn(db); - ChangeAccess ca = mock(ChangeAccess.class); - when(db.changes()).thenReturn(ca); - if (changeExist) { - when(ca.get(id)).thenReturn(change); - if (ioException) { - doThrow(new IOException("io-error")).when(indexer).index(db, change); - } - } else { - when(ca.get(id)).thenReturn(null); - } - } - } -}