Merge branch 'stable-2.13' * stable-2.13: Deprecate plugin Change-Id: I7ef8248e455c44eaa8c461b5134a9e1d7e963a26
diff --git a/.buckconfig b/.buckconfig deleted file mode 100644 index f28dcad..0000000 --- a/.buckconfig +++ /dev/null
@@ -1,16 +0,0 @@ -[alias] - sync-events = //:sync-events - plugin = //:sync-events - src = //:sync-events-sources - -[java] - src_roots = java, resources - source_level = 8 - target_level = 8 - -[project] - ignore = .git - -[cache] - mode = dir - dir = buck-out/cache
diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 175600f..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 6d69b86..0000000 --- a/BUCK +++ /dev/null
@@ -1,79 +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/**/*']) - -TEST_DEPS = GERRIT_PLUGIN_API + GERRIT_TESTS + [ - ':sync-events__plugin', - ':mockito', - ':wiremock', -] - -gerrit_plugin( - name = 'sync-events', - srcs = SOURCES, - resources = RESOURCES, - manifest_entries = [ - 'Gerrit-PluginName: sync-events', - 'Gerrit-ApiType: plugin', - 'Gerrit-Module: com.ericsson.gerrit.plugins.syncevents.Module', - 'Gerrit-HttpModule: com.ericsson.gerrit.plugins.syncevents.HttpModule', - 'Implementation-Title: sync-events plugin', - 'Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/sync-events', - 'Implementation-Vendor: Ericsson', - ], -) - -java_sources( - name = 'sync-events-sources', - srcs = SOURCES + RESOURCES, -) - -java_library( - name = 'classpath', - deps = TEST_DEPS, -) - -java_test( - name = 'sync-events_tests', - srcs = glob(['src/test/java/**/*.java']), - labels = ['sync-events'], - 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/BUILD b/BUILD deleted file mode 100644 index a7a7bad..0000000 --- a/BUILD +++ /dev/null
@@ -1,31 +0,0 @@ -load("//tools/bzl:junit.bzl", "junit_tests") -load( - "//tools/bzl:plugin.bzl", - "gerrit_plugin", - "PLUGIN_DEPS", - "PLUGIN_TEST_DEPS", -) - -gerrit_plugin( - name = "sync-events", - srcs = glob(["src/main/java/**/*.java"]), - resources = glob(["src/main/resources/**/*"]), - manifest_entries = [ - "Gerrit-PluginName: sync-events", - "Gerrit-Module: com.ericsson.gerrit.plugins.syncevents.Module", - "Gerrit-HttpModule: com.ericsson.gerrit.plugins.syncevents.HttpModule", - "Implementation-Title: sync-events plugin", - "Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/sync-events", - ], -) - -junit_tests( - name = "sync_events_tests", - srcs = glob(["src/test/java/**/*.java"]), - tags = ["sync-events"], - deps = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [ - ":sync-events__plugin", - "@mockito//jar", - "@wiremock//jar", - ], -)
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/external_plugin_deps.bzl b/external_plugin_deps.bzl deleted file mode 100644 index 6c723ba..0000000 --- a/external_plugin_deps.bzl +++ /dev/null
@@ -1,33 +0,0 @@ -load("//tools/bzl:maven_jar.bzl", "maven_jar") - -def external_plugin_deps(): - maven_jar( - name = 'wiremock', - artifact = 'com.github.tomakehurst:wiremock:1.58:standalone', - sha1 = '21c8386a95c5dc54a9c55839c5a95083e42412ae', - attach_source = False, - ) - - maven_jar( - name = 'mockito', - artifact = 'org.mockito:mockito-core:2.5.0', - sha1 = 'be28d46a52c7f2563580adeca350145e9ce916f8', - deps = [ - '@byte_buddy//jar', - '@objenesis//jar', - ], - ) - - maven_jar( - name = 'byte_buddy', - artifact = 'net.bytebuddy:byte-buddy:1.5.12', - sha1 = 'b1ba1d15f102b36ed43b826488114678d6d413da', - attach_source = False, - ) - - maven_jar( - name = 'objenesis', - artifact = 'org.objenesis:objenesis:2.4', - sha1 = '2916b6c96b50c5b3ec4452ed99401db745aabb27', - attach_source = False, - )
diff --git a/lib/BUCK b/lib/BUCK deleted file mode 100644 index 8892994..0000000 --- a/lib/BUCK +++ /dev/null
@@ -1,8 +0,0 @@ -include_defs('//bucklets/maven_jar.bucklet') - -maven_jar( - name = 'gson', - id = 'com.google.code.gson:gson:2.1', - sha1 = '2e66da15851f9f5b5079228f856c2f090ba98c38', - license = 'Apache2.0', -)
diff --git a/lib/gerrit/BUCK b/lib/gerrit/BUCK deleted file mode 100644 index 77ba66f..0000000 --- a/lib/gerrit/BUCK +++ /dev/null
@@ -1,20 +0,0 @@ -include_defs('//bucklets/maven_jar.bucklet') - -VER = '2.14-SNAPSHOT' -REPO = MAVEN_LOCAL - -maven_jar( - name = 'plugin-api', - id = 'com.google.gerrit:gerrit-plugin-api:' + VER, - license = 'Apache2.0', - attach_source = False, - repository = REPO, -) - -maven_jar( - name = 'acceptance-framework', - id = 'com.google.gerrit:gerrit-acceptance-framework:' + VER, - license = 'Apache2.0', - attach_source = False, - repository = REPO, -)
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/Configuration.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/Configuration.java deleted file mode 100644 index 01a6db9..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/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.syncevents; - -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; - } - - int getThreadPoolSize() { - return threadPoolSize; - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/Context.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/Context.java deleted file mode 100644 index ba677c9..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/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.syncevents; - -/** - * 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() { - FORWARDED_EVENT.set(true); - } - - static void unsetForwardedEvent() { - FORWARDED_EVENT.remove(); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/EventHandler.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/EventHandler.java deleted file mode 100644 index 73f8708..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/EventHandler.java +++ /dev/null
@@ -1,64 +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.syncevents; - -import com.google.gerrit.common.EventListener; -import com.google.gerrit.extensions.annotations.PluginName; -import com.google.gerrit.server.events.Event; -import com.google.gerrit.server.events.ProjectEvent; -import com.google.inject.Inject; - -import java.util.concurrent.ScheduledThreadPoolExecutor; - -class EventHandler implements EventListener { - private final ScheduledThreadPoolExecutor executor; - private final RestSession restClient; - private final String pluginName; - - @Inject - EventHandler(RestSession restClient, - @SyncEventExecutor ScheduledThreadPoolExecutor executor, - @PluginName String pluginName) { - this.restClient = restClient; - this.executor = executor; - this.pluginName = pluginName; - } - - @Override - public void onEvent(Event event) { - if (!Context.isForwardedEvent() && event instanceof ProjectEvent) { - executor.execute(new SyncEventTask(event)); - } - } - - class SyncEventTask implements Runnable { - private Event event; - - SyncEventTask(Event event) { - this.event = event; - } - - @Override - public void run() { - restClient.send(event); - } - - @Override - public String toString() { - return String.format("[%s] Send event '%s' to target instance", - pluginName, event.type); - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpClientProvider.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpClientProvider.java deleted file mode 100644 index 95821ce..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpClientProvider.java +++ /dev/null
@@ -1,203 +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.syncevents; - -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.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.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -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.warn("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(), - new DummyHostnameVerifier()); - } - - 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 - } - } - - private static class DummyHostnameVerifier implements HostnameVerifier { - @Override - public boolean verify(String hostname, SSLSession session) { - // always accept - return true; - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpModule.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpModule.java deleted file mode 100644 index 58cc1fc..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/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.syncevents; - -import com.google.gerrit.httpd.plugins.HttpPluginModule; - -class HttpModule extends HttpPluginModule { - @Override - protected void configureServlets() { - serve("/event").with(SyncEventsRestApiServlet.class); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpSession.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpSession.java deleted file mode 100644 index b1c32e5..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/HttpSession.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.syncevents; - -import com.google.common.base.Strings; -import com.google.common.net.MediaType; -import com.google.inject.Inject; - -import com.ericsson.gerrit.plugins.syncevents.SyncEventsResponseHandler.SyncResult; - -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -class HttpSession { - private final CloseableHttpClient httpClient; - private final String url; - - @Inject - HttpSession(CloseableHttpClient httpClient, - @SyncUrl String url) { - this.httpClient = httpClient; - this.url = url; - } - - SyncResult post(String endpoint, String content) throws IOException { - HttpPost post = new HttpPost(url + endpoint); - if (!Strings.isNullOrEmpty(content)) { - post.addHeader("Content-Type", MediaType.JSON_UTF_8.toString()); - post.setEntity(new StringEntity(content, StandardCharsets.UTF_8)); - } - return httpClient.execute(post, new SyncEventsResponseHandler()); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/Module.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/Module.java deleted file mode 100644 index 39d9453..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/Module.java +++ /dev/null
@@ -1,51 +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.syncevents; - -import com.google.gerrit.common.EventDispatcher; -import com.google.gerrit.common.EventListener; -import com.google.gerrit.extensions.registration.DynamicItem; -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.ScheduledThreadPoolExecutor; - -class Module extends LifecycleModule { - - @Override - protected void configure() { - bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class) - .in(Scopes.SINGLETON); - bind(Configuration.class); - bind(HttpSession.class); - bind(RestSession.class); - bind(ScheduledThreadPoolExecutor.class) - .annotatedWith(SyncEventExecutor.class) - .toProvider(SyncEventExecutorProvider.class); - listener().to(SyncEventExecutorProvider.class); - DynamicSet.bind(binder(), EventListener.class).to(EventHandler.class); - DynamicItem.bind(binder(), EventDispatcher.class).to(SyncEventBroker.class); - } - - @Provides - @SyncUrl - String syncUrl(Configuration config) { - return config.getUrl(); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/RestSession.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/RestSession.java deleted file mode 100644 index 94e1b90..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/RestSession.java +++ /dev/null
@@ -1,64 +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.syncevents; - -import com.google.common.base.Joiner; -import com.google.common.base.Supplier; -import com.google.gerrit.extensions.annotations.PluginName; -import com.google.gerrit.server.events.Event; -import com.google.gerrit.server.events.SupplierSerializer; -import com.google.gson.GsonBuilder; -import com.google.inject.Inject; - -import com.ericsson.gerrit.plugins.syncevents.SyncEventsResponseHandler.SyncResult; - -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 send(Event event) { - String serializedEvent = new GsonBuilder() - .registerTypeAdapter(Supplier.class, new SupplierSerializer()).create() - .toJson(event); - try { - SyncResult result = httpSession.post(buildEndpoint(), serializedEvent); - if (result.isSuccessful()) { - return true; - } - log.error( - "Unable to send event '" + event.type + "' " + result.getMessage()); - } catch (IOException e) { - log.error("Error trying to send event " + event.type, e); - } - return false; - } - - private String buildEndpoint() { - return Joiner.on("/").join("/plugins", pluginName, "event"); - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventBroker.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventBroker.java deleted file mode 100644 index 36cfc15..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventBroker.java +++ /dev/null
@@ -1,46 +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.syncevents; - -import com.google.gerrit.common.EventBroker; -import com.google.gerrit.common.EventListener; -import com.google.gerrit.common.UserScopedEventListener; -import com.google.gerrit.extensions.registration.DynamicSet; -import com.google.gerrit.reviewdb.server.ReviewDb; -import com.google.gerrit.server.events.Event; -import com.google.gerrit.server.notedb.ChangeNotes.Factory; -import com.google.gerrit.server.project.ProjectCache; -import com.google.inject.Inject; -import com.google.inject.Provider; - -class SyncEventBroker extends EventBroker { - - @Inject - SyncEventBroker(DynamicSet<UserScopedEventListener> listeners, - DynamicSet<EventListener> unrestrictedListeners, - ProjectCache projectCache, - Factory notesFactory, - Provider<ReviewDb> dbProvider) { - super(listeners, unrestrictedListeners, projectCache, notesFactory, - dbProvider); - } - - @Override - protected void fireEventForUnrestrictedListeners(Event event) { - if (!Context.isForwardedEvent()) { - super.fireEventForUnrestrictedListeners(event); - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutor.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutor.java deleted file mode 100644 index 841be21..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutor.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.syncevents; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import com.google.inject.BindingAnnotation; - -import java.lang.annotation.Retention; - -@Retention(RUNTIME) -@BindingAnnotation -@interface SyncEventExecutor { -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutorProvider.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutorProvider.java deleted file mode 100644 index 7fb0ab1..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutorProvider.java +++ /dev/null
@@ -1,54 +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.syncevents; - -import com.google.gerrit.extensions.annotations.PluginName; -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.ScheduledThreadPoolExecutor; - -@Singleton -class SyncEventExecutorProvider - implements Provider<ScheduledThreadPoolExecutor>, LifecycleListener { - private WorkQueue.Executor executor; - - @Inject - SyncEventExecutorProvider(WorkQueue workQueue, - @PluginName String pluginName, - Configuration config) { - executor = workQueue.createQueue(config.getThreadPoolSize(), - "Sync stream events [" + pluginName + " plugin]"); - } - - @Override - public void start() { - // do nothing - } - - @Override - public void stop() { - executor.shutdown(); - executor = null; - } - - @Override - public ScheduledThreadPoolExecutor get() { - return executor; - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsResponseHandler.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsResponseHandler.java deleted file mode 100644 index 59cebf3..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsResponseHandler.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.syncevents; - -import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; - -import com.ericsson.gerrit.plugins.syncevents.SyncEventsResponseHandler.SyncResult; - -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 SyncEventsResponseHandler implements ResponseHandler<SyncResult> { - - static class SyncResult { - private boolean successful; - private String message; - - SyncResult(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(SyncEventsResponseHandler.class); - - @Override - public SyncResult handleResponse(HttpResponse response) { - return new SyncResult(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/syncevents/SyncEventsRestApiServlet.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsRestApiServlet.java deleted file mode 100644 index eae220b..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsRestApiServlet.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.syncevents; - -import static com.google.common.net.MediaType.JSON_UTF_8; -import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; -import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; -import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; -import static javax.servlet.http.HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE; - -import com.google.common.base.Supplier; -import com.google.common.io.CharStreams; -import com.google.common.net.MediaType; -import com.google.gerrit.common.EventDispatcher; -import com.google.gerrit.server.events.Event; -import com.google.gerrit.server.events.EventDeserializer; -import com.google.gerrit.server.events.SupplierDeserializer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gwtorm.server.OrmException; -import com.google.inject.Inject; -import com.google.inject.Singleton; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@Singleton -class SyncEventsRestApiServlet extends HttpServlet { - private static final long serialVersionUID = -1L; - private static final Logger logger = LoggerFactory - .getLogger(SyncEventsRestApiServlet.class); - - private final EventDispatcher dispatcher; - - @Inject - SyncEventsRestApiServlet(EventDispatcher dispatcher) { - this.dispatcher = dispatcher; - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse rsp) - throws IOException, ServletException { - rsp.setContentType("text/plain"); - rsp.setCharacterEncoding("UTF-8"); - try { - Context.setForwardedEvent(); - if (!MediaType.parse(req.getContentType()).is(JSON_UTF_8)) { - sendError(rsp, SC_UNSUPPORTED_MEDIA_TYPE, - "Expecting " + JSON_UTF_8.toString() + " content type"); - return; - } - Event event = getEventFromRequest(req); - dispatcher.postEvent(event); - rsp.setStatus(SC_NO_CONTENT); - } catch (OrmException e) { - logger.debug("Error trying to find a change ", e); - sendError(rsp, SC_NOT_FOUND, "Change not found\n"); - } catch (IOException e) { - logger.error("Unable to re-trigger event", e); - sendError(rsp, SC_BAD_REQUEST, e.getMessage()); - } finally { - Context.unsetForwardedEvent(); - } - } - - private Event getEventFromRequest(HttpServletRequest req) throws IOException { - String jsonEvent = CharStreams.toString(req.getReader()); - Gson gson = new GsonBuilder() - .registerTypeAdapter(Event.class, new EventDeserializer()) - .registerTypeAdapter(Supplier.class, new SupplierDeserializer()) - .create(); - return gson.fromJson(jsonEvent, Event.class); - } - - 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); - } - } -}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncUrl.java b/src/main/java/com/ericsson/gerrit/plugins/syncevents/SyncUrl.java deleted file mode 100644 index 851aec8..0000000 --- a/src/main/java/com/ericsson/gerrit/plugins/syncevents/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.syncevents; - -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 e12f31a..0000000 --- a/src/main/resources/Documentation/about.md +++ /dev/null
@@ -1,13 +0,0 @@ -The @PLUGIN@ plugin allows to share stream events between two Gerrit instances -sharing the same git repositories and database. - -The plugin needs to be installed in both instances and every time a stream event occurs in -one of the instances (see [more events info] -(https://gerrit-review.googlesource.com/Documentation/cmd-stream-events.html#events)), -the event is forwarded to the other instance which re-plays it. This way, the output -of the stream-events command is the same, no matter what instance a client is -connected to. - -For this 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 3f0527b..0000000 --- a/src/main/resources/Documentation/build.md +++ /dev/null
@@ -1,53 +0,0 @@ -Build -===== - -Build -===== - -This plugin is built with Bazel. - -Clone (or link) this plugin to the `plugins` directory of Gerrit's source tree. - -Put the external dependency Bazel build file into the Gerrit /plugins directory, -replacing the existing empty one. - -``` - cd gerrit/plugins - rm external_plugin_deps.bzl - ln -s @PLUGIN@/external_plugin_deps.bzl . -``` - -Then issue - -``` - bazel build plugins/@PLUGIN@ -``` - -in the root of Gerrit's source tree to build - -The output is created in - -``` - bazel-genfiles/plugins/@PLUGIN@/@PLUGIN@.jar -``` - -This project can be imported into the Eclipse IDE. -Add the plugin name to the `CUSTOM_PLUGINS` set in -Gerrit core in `tools/bzl/plugins.bzl`, and execute: - -``` - ./tools/eclipse/project.py -``` - -To execute the tests run: - -``` - bazel test plugins/@PLUGIN@:sync_events_tests -``` - -How to build the Gerrit Plugin API is described in the [Gerrit -documentation](../../../Documentation/dev-bazel.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 f01df3f..0000000 --- a/src/main/resources/Documentation/config.md +++ /dev/null
@@ -1,45 +0,0 @@ -@PLUGIN@ Configuration -========================= - -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 -: 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 send events to 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 send the event to 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. - -@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 stream events to the target instance. - Defaults to 1.
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/ConfigurationTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/ConfigurationTest.java deleted file mode 100644 index f14df56..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/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.syncevents; - -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/syncevents/ContextTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/ContextTest.java deleted file mode 100644 index c3dd4cd..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/ContextTest.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.syncevents; - -import static com.google.common.truth.Truth.assertThat; - -import org.junit.Test; - -import com.ericsson.gerrit.plugins.syncevents.Context; - -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(); - try { - assertThat(Context.isForwardedEvent()).isTrue(); - } finally { - Context.unsetForwardedEvent(); - } - } - - @Test - public void testUnsetForwardedEvent() throws Exception { - Context.setForwardedEvent(); - Context.unsetForwardedEvent(); - assertThat(Context.isForwardedEvent()).isFalse(); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/EventHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/EventHandlerTest.java deleted file mode 100644 index b84be73..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/EventHandlerTest.java +++ /dev/null
@@ -1,95 +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.syncevents; - -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.verifyZeroInteractions; - -import com.google.gerrit.server.events.Event; -import com.google.gerrit.server.events.RefEvent; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.concurrent.ScheduledThreadPoolExecutor; - -@RunWith(MockitoJUnitRunner.class) -public class EventHandlerTest { - private static final String PLUGIN_NAME = "sync-event"; - - private Event event; - private EventHandler eventHandler; - @Mock - private RestSession restSession; - - @Test - public void testRightEventAndNotForwarded() throws Exception { - setUpMocks(true); - eventHandler.onEvent(event); - verify(restSession).send(event); - } - - @Test - public void testRightEventIsForwarded() throws Exception { - setUpMocks(true); - Context.setForwardedEvent(); - eventHandler.onEvent(event); - Context.unsetForwardedEvent(); - verifyZeroInteractions(restSession); - } - - @Test - public void testBadEventAndNotForwarded() throws Exception { - setUpMocks(false); - eventHandler.onEvent(event); - verifyZeroInteractions(restSession); - } - - @Test - public void testBadEventAndItIsForwarded() throws Exception { - setUpMocks(false); - Context.setForwardedEvent(); - eventHandler.onEvent(event); - Context.unsetForwardedEvent(); - verifyZeroInteractions(restSession); - } - - private void setUpMocks(boolean rightEvent) { - ScheduledThreadPoolExecutor pool = new PoolMock(1); - if (rightEvent) { - event = mock(RefEvent.class); - } else { - event = mock(Event.class); - } - eventHandler = new EventHandler(restSession, pool, PLUGIN_NAME); - } - - private class PoolMock extends ScheduledThreadPoolExecutor { - PoolMock(int corePoolSize) { - super(corePoolSize); - } - - @Override - public void execute(Runnable command) { - assertThat(command.toString()).isEqualTo(String.format( - "[%s] Send event '%s' to target instance", PLUGIN_NAME, null)); - command.run(); - } - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/HttpClientProviderTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/HttpClientProviderTest.java deleted file mode 100644 index 30b4cf2..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/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.syncevents; - -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/syncevents/HttpSessionTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/HttpSessionTest.java deleted file mode 100644 index 3b8e182..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/HttpSessionTest.java +++ /dev/null
@@ -1,155 +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.syncevents; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -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.syncevents.SyncEventsResponseHandler.SyncResult; -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.Rule; -import org.junit.Test; - -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-events/event"; - private static final String BODY = "SerializedEvent"; - private static final String ERROR_MESSAGE = "Error message"; - private static final String REQUEST_MADE = "Request made"; - private static final String RETRY_AT_ERROR = "Retry at error"; - private static final String RETRY_AT_DELAY = "Retry at delay"; - - private HttpSession httpSession; - - @Rule - public 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); - } - - @Test - public void testResponseOK() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).willReturn(aResponse().withStatus(OK))); - assertThat(httpSession.post(ENDPOINT, BODY).isSuccessful()).isTrue(); - } - - @Test - public void testResponseOKEmptyBody() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).willReturn(aResponse().withStatus(OK))); - assertThat(httpSession.post(ENDPOINT, "").isSuccessful()).isTrue(); - } - - @Test - public void testNotAuthorized() throws Exception { - String expected = "unauthorized"; - stubFor(post(urlEqualTo(ENDPOINT)).willReturn( - aResponse().withStatus(UNAUTHORIZED).withBody(expected))); - - SyncResult result = httpSession.post(ENDPOINT, BODY); - assertThat(result.isSuccessful()).isFalse(); - assertThat(result.getMessage()).isEqualTo(expected); - } - - @Test - public void testNotFound() throws Exception { - String expected = "not found"; - stubFor(post(urlEqualTo(ENDPOINT)).willReturn( - aResponse().withStatus(NOT_FOUND).withBody(expected))); - - SyncResult result = httpSession.post(ENDPOINT, BODY); - assertThat(result.isSuccessful()).isFalse(); - assertThat(result.getMessage()).isEqualTo(expected); - } - - @Test - public void testBadResponseRetryThenOK() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_ERROR) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withStatus(ERROR))); - stubFor(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_ERROR) - .whenScenarioStateIs(REQUEST_MADE) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.post(ENDPOINT, BODY).isSuccessful()).isTrue(); - } - - @Test - public void testBadResponseRetryThenGiveUp() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).willReturn( - aResponse().withStatus(ERROR).withBody(ERROR_MESSAGE))); - - assertThat(httpSession.post(ENDPOINT, BODY).isSuccessful()).isFalse(); - assertThat(httpSession.post(ENDPOINT, BODY).getMessage()) - .isEqualTo(ERROR_MESSAGE); - } - - @Test - public void testRetryAfterDelay() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withStatus(ERROR).withFixedDelay(TIMEOUT / 2))); - stubFor(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(REQUEST_MADE) - .willReturn(aResponse().withStatus(OK))); - - assertThat(httpSession.post(ENDPOINT, BODY).isSuccessful()).isTrue(); - } - - @Test - public void testGiveUpAtTimeout() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).inScenario(RETRY_AT_DELAY) - .whenScenarioStateIs(Scenario.STARTED).willSetStateTo(REQUEST_MADE) - .willReturn(aResponse().withStatus(ERROR).withFixedDelay(TIMEOUT))); - - assertThat(httpSession.post(ENDPOINT, BODY).isSuccessful()).isFalse(); - } - - @Test - public void testResponseWithMalformedResponse() throws Exception { - stubFor(post(urlEqualTo(ENDPOINT)).willReturn( - aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK))); - - assertThat(httpSession.post(ENDPOINT, BODY).isSuccessful()).isFalse(); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/ModuleTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/ModuleTest.java deleted file mode 100644 index 3a0addf..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/ModuleTest.java +++ /dev/null
@@ -1,34 +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.syncevents; - -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/syncevents/RestSessionTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/RestSessionTest.java deleted file mode 100644 index 9385c5f..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/RestSessionTest.java +++ /dev/null
@@ -1,82 +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.syncevents; - -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.google.gerrit.server.events.Event; -import com.google.gson.GsonBuilder; - -import com.ericsson.gerrit.plugins.syncevents.SyncEventsResponseHandler.SyncResult; - -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -public class RestSessionTest { - private static final String PLUGIN_NAME = "sync-events"; - private static final String REQUEST = - Joiner.on("/").join("/plugins", PLUGIN_NAME, "event"); - - private RestSession restSession; - private Event event; - - @Before - public void setup() { - event = new SyncEventTest(); - } - - @Test - public void testEventSentOK() throws Exception { - setUpMocks(true, "", false); - assertThat(restSession.send(event)).isTrue(); - } - - @Test - public void testEventSentFailed() throws Exception { - setUpMocks(false, "Error", false); - assertThat(restSession.send(event)).isFalse(); - } - - @Test - public void testEventSentThrowsException() throws Exception { - setUpMocks(false, "Exception", true); - assertThat(restSession.send(event)).isFalse(); - } - - private void setUpMocks(boolean isOk, String msg, boolean throwException) - throws Exception { - String content = new GsonBuilder().create().toJson(event); - HttpSession httpSession = mock(HttpSession.class); - if (throwException) { - doThrow(new IOException()).when(httpSession).post(REQUEST, content); - } else { - SyncResult result = new SyncResult(isOk, msg); - when(httpSession.post(REQUEST, content)).thenReturn(result); - } - restSession = new RestSession(httpSession, PLUGIN_NAME); - } - - class SyncEventTest extends Event { - public SyncEventTest() { - super("test-event"); - } - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventBrokerTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventBrokerTest.java deleted file mode 100644 index 1ca7170..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventBrokerTest.java +++ /dev/null
@@ -1,58 +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.syncevents; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -import com.google.gerrit.common.EventListener; -import com.google.gerrit.extensions.registration.DynamicSet; -import com.google.gerrit.server.events.Event; - -import org.junit.Before; -import org.junit.Test; - -public class SyncEventBrokerTest { - - private EventListener listenerMock; - private SyncEventBroker broker; - private Event event = new Event(null) {}; - - @Before - public void setUp() { - listenerMock = mock(EventListener.class); - DynamicSet<EventListener> listeners = DynamicSet.emptySet(); - listeners.add(listenerMock); - broker = new SyncEventBroker(null, listeners, null, null, null); - } - - @Test - public void shouldDispatchEvent() { - broker.fireEventForUnrestrictedListeners(event); - verify(listenerMock).onEvent(event); - } - - @Test - public void shouldNotDispatchForwardedEvents() { - Context.setForwardedEvent(); - try { - broker.fireEventForUnrestrictedListeners(event); - } finally { - Context.unsetForwardedEvent(); - } - verifyZeroInteractions(listenerMock); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutorProviderTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutorProviderTest.java deleted file mode 100644 index faec7d1..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventExecutorProviderTest.java +++ /dev/null
@@ -1,61 +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.syncevents; - -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 SyncEventExecutorProviderTest { - @Mock - private WorkQueue.Executor executorMock; - private SyncEventExecutorProvider syncEventsExecutorProvider; - - @Before - public void setUp() throws Exception { - WorkQueue workQueueMock = mock(WorkQueue.class); - when(workQueueMock.createQueue(4, "Sync stream events [SyncEvents plugin]")) - .thenReturn(executorMock); - Configuration configMock = mock(Configuration.class); - when(configMock.getThreadPoolSize()).thenReturn(4); - - syncEventsExecutorProvider = - new SyncEventExecutorProvider(workQueueMock, "SyncEvents", configMock); - } - - @Test - public void shouldReturnExecutor() throws Exception { - assertThat(syncEventsExecutorProvider.get()).isEqualTo(executorMock); - } - - @Test - public void testStop() throws Exception { - syncEventsExecutorProvider.start(); - assertThat(syncEventsExecutorProvider.get()).isEqualTo(executorMock); - syncEventsExecutorProvider.stop(); - verify(executorMock).shutdown(); - assertThat(syncEventsExecutorProvider.get()).isNull(); - } -}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsResponseHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsResponseHandlerTest.java deleted file mode 100644 index e17e283..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsResponseHandlerTest.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.syncevents; - -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.syncevents.SyncEventsResponseHandler.SyncResult; - -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 SyncEventsResponseHandlerTest { - 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 SyncEventsResponseHandler handler; - - @Before - public void setUp() throws Exception { - handler = new SyncEventsResponseHandler(); - } - - @Test - public void testIsSuccessful() throws Exception { - HttpResponse response = setupMocks(OK, EMPTY_ENTITY); - SyncResult result = handler.handleResponse(response); - assertThat(result.isSuccessful()).isTrue(); - assertThat(result.getMessage()).isEmpty(); - } - - @Test - public void testIsNotSuccessful() throws Exception { - HttpResponse response = setupMocks(ERROR, ERROR_ENTITY); - SyncResult 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/syncevents/SyncEventsRestApiServletTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsRestApiServletTest.java deleted file mode 100644 index 5c318c8..0000000 --- a/src/test/java/com/ericsson/gerrit/plugins/syncevents/SyncEventsRestApiServletTest.java +++ /dev/null
@@ -1,147 +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.syncevents; - -import static com.google.common.net.MediaType.JSON_UTF_8; -import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; -import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; -import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; -import static javax.servlet.http.HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.common.net.MediaType; -import com.google.gerrit.common.EventDispatcher; -import com.google.gerrit.reviewdb.client.Project; -import com.google.gerrit.server.events.EventTypes; -import com.google.gerrit.server.events.RefEvent; -import com.google.gwtorm.client.KeyUtil; -import com.google.gwtorm.server.OrmException; -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.BufferedReader; -import java.io.IOException; -import java.io.StringReader; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@RunWith(MockitoJUnitRunner.class) -public class SyncEventsRestApiServletTest { - private static final String ERR_MSG = "some Error"; - - @Mock - private EventDispatcher dispatcher; - @Mock - private HttpServletRequest req; - @Mock - private HttpServletResponse rsp; - private SyncEventsRestApiServlet syncEventsRestApiServlet; - - @BeforeClass - public static void setup() { - EventTypes.register(RefReplicationDoneEvent.TYPE, - RefReplicationDoneEvent.class); - KeyUtil.setEncoderImpl(new StandardKeyEncoder()); - } - - @Before - public void createSyncEventsRestApiServlet() throws Exception { - syncEventsRestApiServlet = new SyncEventsRestApiServlet(dispatcher); - when(req.getContentType()).thenReturn(MediaType.JSON_UTF_8.toString()); - } - - @Test - public void testDoPostRefReplicationDoneEvent() throws Exception { - String event = "{\"project\":\"gerrit/test-sync-index\",\"ref\":" - + "\"refs/changes/76/669676/2\",\"nodesCount\":1,\"type\":" - + "\"ref-replication-done\",\"eventCreatedOn\":1451415011}"; - when(req.getReader()) - .thenReturn(new BufferedReader(new StringReader(event))); - dispatcher.postEvent(any(RefReplicationDoneEvent.class)); - syncEventsRestApiServlet.doPost(req, rsp); - verify(rsp).setStatus(SC_NO_CONTENT); - } - - @Test - public void testDoPostDispatcherFailure() throws Exception { - String event = "{\"project\":\"gerrit/test-sync-index\",\"ref\":" - + "\"refs/changes/76/669676/2\",\"nodesCount\":1,\"type\":" - + "\"ref-replication-done\",\"eventCreatedOn\":1451415011}"; - when(req.getReader()) - .thenReturn(new BufferedReader(new StringReader(event))); - doThrow(new OrmException(ERR_MSG)).when(dispatcher) - .postEvent(any(RefReplicationDoneEvent.class)); - syncEventsRestApiServlet.doPost(req, rsp); - verify(rsp).sendError(SC_NOT_FOUND, "Change not found\n"); - } - - @Test - public void testDoPostBadRequest() throws Exception { - doThrow(new IOException(ERR_MSG)).when(req).getReader(); - syncEventsRestApiServlet.doPost(req, rsp); - verify(rsp).sendError(SC_BAD_REQUEST, ERR_MSG); - } - - @Test - public void testDoPostWrongMediaType() throws Exception { - when(req.getContentType()) - .thenReturn(MediaType.APPLICATION_XML_UTF_8.toString()); - syncEventsRestApiServlet.doPost(req, rsp); - verify(rsp).sendError(SC_UNSUPPORTED_MEDIA_TYPE, - "Expecting " + JSON_UTF_8.toString() + " content type"); - } - - @Test - public void testDoPostErrorWhileSendingErrorMessage() throws Exception { - doThrow(new IOException(ERR_MSG)).when(req).getReader(); - doThrow(new IOException("someOtherError")).when(rsp) - .sendError(SC_BAD_REQUEST, ERR_MSG); - syncEventsRestApiServlet.doPost(req, rsp); - } - - static class RefReplicationDoneEvent extends RefEvent { - public static final String TYPE = "ref-replication-done"; - public final String project; - public final String ref; - public final int nodesCount; - - public RefReplicationDoneEvent(String project, String ref, int nodesCount) { - super(TYPE); - this.project = project; - this.ref = ref; - this.nodesCount = nodesCount; - } - - @Override - public Project.NameKey getProjectNameKey() { - return new Project.NameKey(project); - } - - @Override - public String getRefName() { - return ref; - } - } -}