You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ss...@apache.org on 2024/12/12 15:00:03 UTC
(sling-org-apache-sling-discovery-oak) branch feature/SLING-12559-parent-62 created (now a7ce46f)
This is an automated email from the ASF dual-hosted git repository.
sseifert pushed a change to branch feature/SLING-12559-parent-62
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git
at a7ce46f SLING-12559 apply spotless formatting
This branch includes the following new commits:
new 0e7eb0e SLING-12559 Update to parent 62
new a7ce46f SLING-12559 apply spotless formatting
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(sling-org-apache-sling-discovery-oak) 02/02: SLING-12559 apply spotless formatting
Posted by ss...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sseifert pushed a commit to branch feature/SLING-12559-parent-62
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git
commit a7ce46f002e5e4f8c5a57ffabfdeb20f0b1fcaa7
Author: Stefan Seifert <st...@users.noreply.github.com>
AuthorDate: Thu Dec 12 15:59:52 2024 +0100
SLING-12559 apply spotless formatting
---
pom.xml | 294 ++++++++--------
.../org/apache/sling/discovery/oak/Config.java | 65 ++--
.../oak/DiscoveryServiceCentralConfig.java | 18 +-
.../apache/sling/discovery/oak/JoinerDelay.java | 29 +-
.../sling/discovery/oak/OakDiscoveryService.java | 91 ++---
.../sling/discovery/oak/SlingIdCleanupTask.java | 149 ++++----
.../oak/SynchronizedClocksHealthCheck.java | 75 ++--
.../discovery/oak/TopologyWebConsolePlugin.java | 383 ++++++++++-----------
.../sling/discovery/oak/cluster/ClusterReader.java | 33 +-
.../sling/discovery/oak/cluster/InstanceInfo.java | 3 +-
.../oak/cluster/OakClusterViewService.java | 130 +++----
.../sling/discovery/oak/pinger/OakViewChecker.java | 69 ++--
.../base/commons/OakViewCheckerFactory.java | 6 +-
.../org/apache/sling/discovery/oak/ConfigTest.java | 16 +-
.../sling/discovery/oak/JoinerDelayTest.java | 72 ++--
.../sling/discovery/oak/Log4jErrorCatcher.java | 7 +-
.../discovery/oak/OakDiscoveryServiceTest.java | 245 +++++++------
.../sling/discovery/oak/PartialStartupTest.java | 113 +++---
.../discovery/oak/TestSlingIdCleanupTask.java | 228 ++++++------
.../oak/TopologyWebConsolePluginTest.java | 14 +-
.../oak/cluster/OakClusterViewServiceTest.java | 119 ++++---
.../discovery/oak/its/OakClusterLoadTest.java | 1 -
.../sling/discovery/oak/its/OakClusterTest.java | 1 -
.../discovery/oak/its/OakDiscoveryServiceTest.java | 28 +-
.../discovery/oak/its/OakSingleInstanceTest.java | 1 -
.../discovery/oak/its/OakTopologyEventTest.java | 5 +-
.../discovery/oak/its/setup/OakTestConfig.java | 14 +-
.../oak/its/setup/OakVirtualInstanceBuilder.java | 60 ++--
.../discovery/oak/its/setup/SimulatedLease.java | 12 +-
.../oak/its/setup/SimulatedLeaseCollection.java | 52 +--
30 files changed, 1230 insertions(+), 1103 deletions(-)
diff --git a/pom.xml b/pom.xml
index c5a573f..2abad65 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
+<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@@ -33,6 +33,13 @@
<name>Apache Sling Oak-Based Discovery Service</name>
<description>Implementation of Apache Sling Discovery based on Jackrabbit Oak using its discovery-lite descriptor for in-cluster view detection and a TopologyView through HTTP POST heartbeats announcing sub-topologies to each other.</description>
+ <scm>
+ <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git</connection>
+ <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git</developerConnection>
+ <tag>HEAD</tag>
+ <url>https://github.com/apache/sling-org-apache-sling-discovery-oak.git</url>
+ </scm>
+
<properties>
<sling.java.version>8</sling.java.version>
<jackrabbit.version>2.14.3</jackrabbit.version>
@@ -40,60 +47,6 @@
<!-- by default Slow tests are excluded - use -PincludeSlowTests to include them -->
<sling.excluded.surefire.groups>org.apache.sling.commons.testing.junit.categories.Slow</sling.excluded.surefire.groups>
</properties>
-
- <scm>
- <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git</connection>
- <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git</developerConnection>
- <url>https://github.com/apache/sling-org-apache-sling-discovery-oak.git</url>
- <tag>HEAD</tag>
- </scm>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>prepare-agent</id>
- <configuration>
- <propertyName>jacoco.command</propertyName>
- </configuration>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </execution>
- <execution>
- <id>report</id>
- <phase>post-integration-test</phase>
- <goals>
- <goal>report</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <redirectTestOutputToFile>true</redirectTestOutputToFile>
- <argLine>${jacoco.command} -Xmx2048m</argLine>
- <excludedGroups>${sling.excluded.surefire.groups}</excludedGroups>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <profiles>
- <profile>
- <!-- when -PincludeSlowTests is set, the Slow tests should also be executed,
- hence unsetting the category excludes 'sling.excluded.surefire.groups' to
- achieve that. -->
- <id>includeSlowTests</id>
- <properties>
- <sling.excluded.surefire.groups />
- </properties>
- </profile>
- </profiles>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
@@ -132,96 +85,96 @@
<version>1.0.9</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.jcr.api</artifactId>
- <version>2.1.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.jcr</groupId>
- <artifactId>jcr</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.jackrabbit</groupId>
- <artifactId>jackrabbit-api</artifactId>
- <version>${jackrabbit.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.settings</artifactId>
- <version>1.2.2</version>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.jcr.api</artifactId>
+ <version>2.1.0</version>
<scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.discovery.api</artifactId>
- <version>1.0.0</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.jcr</groupId>
+ <artifactId>jcr</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-api</artifactId>
+ <version>${jackrabbit.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.settings</artifactId>
+ <version>1.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.discovery.api</artifactId>
+ <version>1.0.0</version>
<scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.discovery.commons</artifactId>
- <version>1.0.26</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.discovery.commons</artifactId>
+ <version>1.0.26</version>
<scope>provided</scope>
- </dependency>
+ </dependency>
<!-- besides including discovery.commons' normal jar above,
for testing a few test helper classes are also reused.
- in order to achieve that, also adding a test/test-jar dependency: -->
+ in order to achieve that, also adding a test/test-jar dependency: -->
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.discovery.commons</artifactId>
<version>1.0.26</version>
- <scope>test</scope>
<type>test-jar</type>
+ <scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.discovery.base</artifactId>
- <version>2.0.14</version>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.discovery.base</artifactId>
+ <version>2.0.14</version>
<scope>provided</scope>
- </dependency>
+ </dependency>
<!-- besides including discovery.base' normal jar above,
for testing a few test helper classes are also reused.
- in order to achieve that, also adding a test/test-jar dependency: -->
+ in order to achieve that, also adding a test/test-jar dependency: -->
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.discovery.base</artifactId>
<version>2.0.14</version>
- <scope>test</scope>
<type>test-jar</type>
+ <scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.api</artifactId>
- <version>2.11.0</version>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.api</artifactId>
+ <version>2.11.0</version>
<scope>provided</scope>
- </dependency>
+ </dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.commons.scheduler</artifactId>
<version>2.5.0</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.webconsole</artifactId>
- <version>3.0.0</version>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.webconsole</artifactId>
+ <version>3.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient-osgi</artifactId>
+ <version>4.3.5</version>
<scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient-osgi</artifactId>
- <version>4.3.5</version>
- <scope>provided</scope>
- </dependency>
+ </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@@ -235,9 +188,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.healthcheck.api</artifactId>
- <version>2.0.0</version>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.healthcheck.api</artifactId>
+ <version>2.0.0</version>
<scope>provided</scope>
<exclusions>
<exclusion>
@@ -247,7 +200,7 @@
</exclusions>
</dependency>
- <!-- Testing -->
+ <!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@@ -278,10 +231,10 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.commons.testing</artifactId>
- <version>2.1.2</version>
- <scope>test</scope>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.commons.testing</artifactId>
+ <version>2.1.2</version>
+ <scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.apache.jackrabbit</groupId>
@@ -299,31 +252,31 @@
</exclusion>
</exclusions>
</dependency>
-
+
<!-- using log4j under slf4j to allow fine-grained logging config (see src/test/resources/log4j.properties) -->
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.5</version>
- <scope>test</scope>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>1.7.5</version>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.jcr.resource</artifactId>
- <version>2.3.8</version>
- <scope>test</scope>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.jcr.resource</artifactId>
+ <version>2.3.8</version>
+ <scope>test</scope>
</dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.13</version>
- <scope>test</scope>
- </dependency>
<dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.commons.threads</artifactId>
- <version>3.1.0</version>
- <scope>test</scope>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.13</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.commons.threads</artifactId>
+ <version>3.1.0</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
@@ -338,10 +291,10 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.jackrabbit</groupId>
- <artifactId>jackrabbit-jcr-commons</artifactId>
- <version>${jackrabbit.version}</version>
- <scope>test</scope>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-jcr-commons</artifactId>
+ <version>${jackrabbit.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
@@ -362,4 +315,51 @@
<scope>test</scope>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>prepare-agent</id>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ <configuration>
+ <propertyName>jacoco.command</propertyName>
+ </configuration>
+ </execution>
+ <execution>
+ <id>report</id>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ <phase>post-integration-test</phase>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <redirectTestOutputToFile>true</redirectTestOutputToFile>
+ <argLine>${jacoco.command} -Xmx2048m</argLine>
+ <excludedGroups>${sling.excluded.surefire.groups}</excludedGroups>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <profiles>
+ <profile>
+ <!-- when -PincludeSlowTests is set, the Slow tests should also be executed,
+ hence unsetting the category excludes 'sling.excluded.surefire.groups' to
+ achieve that. -->
+ <id>includeSlowTests</id>
+ <properties>
+ <sling.excluded.surefire.groups />
+ </properties>
+ </profile>
+ </profiles>
</project>
diff --git a/src/main/java/org/apache/sling/discovery/oak/Config.java b/src/main/java/org/apache/sling/discovery/oak/Config.java
index a00994d..99a8603 100644
--- a/src/main/java/org/apache/sling/discovery/oak/Config.java
+++ b/src/main/java/org/apache/sling/discovery/oak/Config.java
@@ -52,8 +52,8 @@ import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAU
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.JOINER_DELAY_ENABLED_SYSTEM_PROPERTY_NAME;
-
import static org.osgi.util.converter.Converters.standardConverter;
+
/**
* Configuration object used as a central config point for the discovery service
* implementation
@@ -162,25 +162,37 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
}
protected void configure(final DiscoveryServiceCentralConfig config) {
- this.connectorPingTimeout = guardLong(c -> config.connectorPingTimeout(), "connectorPingTimeout", DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT);
+ this.connectorPingTimeout = guardLong(
+ c -> config.connectorPingTimeout(), "connectorPingTimeout", DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT);
logger.debug("configure: connectorPingTimeout='{}'", this.connectorPingTimeout);
- this.connectorPingInterval = guardLong(c -> config.connectorPingInterval(), "connectorPingInterval", DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL);
+ this.connectorPingInterval = guardLong(
+ c -> config.connectorPingInterval(), "connectorPingInterval", DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL);
logger.debug("configure: connectorPingInterval='{}'", this.connectorPingInterval);
- this.discoveryLiteCheckInterval = guardLong(c -> config.discoveryLiteCheckInterval(), "discoveryLiteCheckInterval", DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL);
+ this.discoveryLiteCheckInterval = guardLong(
+ c -> config.discoveryLiteCheckInterval(),
+ "discoveryLiteCheckInterval",
+ DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL);
logger.debug("configure: discoveryLiteCheckInterval='{}'", this.discoveryLiteCheckInterval);
- this.clusterSyncServiceTimeout = guardLong(c -> config.clusterSyncServiceTimeout(), "clusterSyncServiceTimeout", DEFAULT_CLUSTER_SYNC_SERVICE_TIMEOUT);
+ this.clusterSyncServiceTimeout = guardLong(
+ c -> config.clusterSyncServiceTimeout(),
+ "clusterSyncServiceTimeout",
+ DEFAULT_CLUSTER_SYNC_SERVICE_TIMEOUT);
logger.debug("configure: clusterSyncServiceTimeout='{}'", this.clusterSyncServiceTimeout);
- this.clusterSyncServiceInterval = guardLong(c -> config.clusterSyncServiceInterval(), "clusterSyncServiceInterval", DEFAULT_CLUSTER_SYNC_SERVICE_INTERVAL);
+ this.clusterSyncServiceInterval = guardLong(
+ c -> config.clusterSyncServiceInterval(),
+ "clusterSyncServiceInterval",
+ DEFAULT_CLUSTER_SYNC_SERVICE_INTERVAL);
logger.debug("configure: clusterSyncServiceInterval='{}'", this.clusterSyncServiceInterval);
this.minEventDelay = guardInt(c -> config.minEventDelay(), "minEventDelay", DEFAULT_MIN_EVENT_DELAY);
logger.debug("configure: minEventDelay='{}'", this.minEventDelay);
- this.socketConnectTimeout = guardInt(c -> config.socketConnectTimeout(), "socketConnectTimeout", DEFAULT_SOCKET_CONNECT_TIMEOUT);
+ this.socketConnectTimeout =
+ guardInt(c -> config.socketConnectTimeout(), "socketConnectTimeout", DEFAULT_SOCKET_CONNECT_TIMEOUT);
logger.debug("configure: socketConnectTimeout='{}'", this.socketConnectTimeout);
this.soTimeout = guardInt(c -> config.soTimeout(), "soTimeout", DEFAULT_SO_TIMEOUT);
@@ -194,19 +206,16 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
try {
if (anUrlStr != null && anUrlStr.length() > 0) {
URL url = new URL(anUrlStr);
- logger.debug("configure: a topologyConnectorbUrl='{}'",
- url);
+ logger.debug("configure: a topologyConnectorbUrl='{}'", url);
urls.add(url);
}
} catch (MalformedURLException e) {
- logger.error("configure: could not set a topologyConnectorUrl: " + e,
- e);
+ logger.error("configure: could not set a topologyConnectorUrl: " + e, e);
}
}
if (urls.size() > 0) {
this.topologyConnectorUrls = urls.toArray(new URL[urls.size()]);
- logger.debug("configure: number of topologyConnectorUrls='{}''",
- urls.size());
+ logger.debug("configure: number of topologyConnectorUrls='{}''", urls.size());
} else {
this.topologyConnectorUrls = null;
logger.debug("configure: no (valid) topologyConnectorUrls configured");
@@ -220,7 +229,8 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
this.discoveryResourcePath = config.discoveryResourcePath();
while (this.discoveryResourcePath.endsWith("/")) {
- this.discoveryResourcePath = this.discoveryResourcePath.substring(0, this.discoveryResourcePath.length() - 1);
+ this.discoveryResourcePath =
+ this.discoveryResourcePath.substring(0, this.discoveryResourcePath.length() - 1);
}
this.discoveryResourcePath = this.discoveryResourcePath + "/";
if (this.discoveryResourcePath == null || this.discoveryResourcePath.length() <= 1) {
@@ -237,29 +247,35 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
sharedKey = config.sharedKey();
keyInterval = config.hmacSharedKeyTTL();
- backoffStandbyFactor = guardInt(c -> config.backoffStandbyFactor(), "backoffStandbyFactor", DEFAULT_BACKOFF_STANDBY_FACTOR);
- backoffStableFactor = guardInt(c -> config.backoffStableFactor(), "backoffStableFactor", DEFAULT_BACKOFF_STABLE_FACTOR);
+ backoffStandbyFactor =
+ guardInt(c -> config.backoffStandbyFactor(), "backoffStandbyFactor", DEFAULT_BACKOFF_STANDBY_FACTOR);
+ backoffStableFactor =
+ guardInt(c -> config.backoffStableFactor(), "backoffStableFactor", DEFAULT_BACKOFF_STABLE_FACTOR);
this.invertLeaderElectionPrefixOrder = config.invertLeaderElectionPrefixOrder();
logger.debug("configure: invertLeaderElectionPrefixOrder='{}'", this.invertLeaderElectionPrefixOrder);
this.leaderElectionPrefix = config.leaderElectionPrefix();
- logger.debug("configure: leaderElectionPrefix='{}'", this.leaderElectionPrefix);
+ logger.debug("configure: leaderElectionPrefix='{}'", this.leaderElectionPrefix);
this.suppressPartiallyStartedInstance = config.suppressPartiallyStartedInstance();
logger.debug("configure: suppressPartiallyStartedInstance='{}'", this.suppressPartiallyStartedInstance);
- this.suppressionTimeoutSeconds = guardLong(c -> config.suppressionTimeoutSeconds(), "suppressionTimeoutSeconds", DEFAULT_SUPPRESSION_TIMEOUT_SECONDS);
+ this.suppressionTimeoutSeconds = guardLong(
+ c -> config.suppressionTimeoutSeconds(),
+ "suppressionTimeoutSeconds",
+ DEFAULT_SUPPRESSION_TIMEOUT_SECONDS);
logger.debug("configure: suppressionTimeoutSeconds='{}'", this.suppressionTimeoutSeconds);
- this.joinerDelaySeconds = guardLong(c -> config.joinerDelaySeconds(), "joinerDelaySeconds", DEFAULT_JOINER_DELAY_SECONDS);
+ this.joinerDelaySeconds =
+ guardLong(c -> config.joinerDelaySeconds(), "joinerDelaySeconds", DEFAULT_JOINER_DELAY_SECONDS);
logger.debug("configure: joinerDelaySeconds='{}'", this.joinerDelaySeconds);
}
private Integer guardInt(ToIntFunction<Void> injectedConfig, String key, int def) {
try {
return injectedConfig.applyAsInt(null);
- } catch(RuntimeException re) {
+ } catch (RuntimeException re) {
logger.info("configure: got RuntimeException for {} , using default: {}", key, re.getMessage());
return def;
}
@@ -268,7 +284,7 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
private Long guardLong(ToLongFunction<Void> injectedConfig, String key, long def) {
try {
return injectedConfig.applyAsLong(null);
- } catch(RuntimeException re) {
+ } catch (RuntimeException re) {
logger.info("configure: got RuntimeException for {} , using default: {}", key, re.getMessage());
return def;
}
@@ -471,7 +487,10 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
return joinerDelayOverwrite;
}
final String systemPropertyValue = System.getProperty(JOINER_DELAY_ENABLED_SYSTEM_PROPERTY_NAME);
- final boolean newJoinerDelayOverwrite = standardConverter().convert(systemPropertyValue).defaultValue(configValue).to(Boolean.class);
+ final boolean newJoinerDelayOverwrite = standardConverter()
+ .convert(systemPropertyValue)
+ .defaultValue(configValue)
+ .to(Boolean.class);
if (joinerDelayOverwriteNextCheck == 0) {
logger.info("applyJoinerDelayOverwrite : initialization."
+ " system property '" + JOINER_DELAY_ENABLED_SYSTEM_PROPERTY_NAME + "' = " + systemPropertyValue
@@ -484,7 +503,7 @@ public class Config implements BaseConfig, DiscoveryLiteConfig {
+ ", resulting value = " + newJoinerDelayOverwrite);
}
joinerDelayOverwrite = newJoinerDelayOverwrite;
- joinerDelayOverwriteNextCheck = now + 300000; //re-check every 300sec, should be fast and slow enough
+ joinerDelayOverwriteNextCheck = now + 300000; // re-check every 300sec, should be fast and slow enough
return joinerDelayOverwrite;
}
diff --git a/src/main/java/org/apache/sling/discovery/oak/DiscoveryServiceCentralConfig.java b/src/main/java/org/apache/sling/discovery/oak/DiscoveryServiceCentralConfig.java
index fc36513..5a53751 100644
--- a/src/main/java/org/apache/sling/discovery/oak/DiscoveryServiceCentralConfig.java
+++ b/src/main/java/org/apache/sling/discovery/oak/DiscoveryServiceCentralConfig.java
@@ -18,8 +18,8 @@
*/
package org.apache.sling.discovery.oak;
-import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@SuppressWarnings("java:S100")
@ObjectClassDefinition(
@@ -64,13 +64,19 @@ public @interface DiscoveryServiceCentralConfig {
@AttributeDefinition(name = "%connectorPingInterval.name", description = "%connectorPingInterval.description")
long connectorPingInterval() default DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL;
- @AttributeDefinition(name = "%discoveryLiteCheckInterval.name", description = "%discoveryLiteCheckInterval.description")
+ @AttributeDefinition(
+ name = "%discoveryLiteCheckInterval.name",
+ description = "%discoveryLiteCheckInterval.description")
long discoveryLiteCheckInterval() default DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL;
- @AttributeDefinition(name = "%clusterSyncServiceTimeout.name", description = "%clusterSyncServiceTimeout.description")
+ @AttributeDefinition(
+ name = "%clusterSyncServiceTimeout.name",
+ description = "%clusterSyncServiceTimeout.description")
long clusterSyncServiceTimeout() default DEFAULT_CLUSTER_SYNC_SERVICE_TIMEOUT;
- @AttributeDefinition(name = "%clusterSyncServiceInterval.name", description = "%clusterSyncServiceInterval.description")
+ @AttributeDefinition(
+ name = "%clusterSyncServiceInterval.name",
+ description = "%clusterSyncServiceInterval.description")
long clusterSyncServiceInterval() default DEFAULT_CLUSTER_SYNC_SERVICE_INTERVAL;
/**
@@ -101,13 +107,13 @@ public @interface DiscoveryServiceCentralConfig {
/**
* URLs where to join a topology, eg http://localhost:4502/libs/sling/topology/connector
*/
- @AttributeDefinition (cardinality = 1024)
+ @AttributeDefinition(cardinality = 1024)
String[] topologyConnectorUrls() default {};
/**
* list of ips and/or hostnames which are allowed to connect to /libs/sling/topology/connector
*/
- @AttributeDefinition (cardinality = 1024)
+ @AttributeDefinition(cardinality = 1024)
String[] topologyConnectorWhitelist() default {"localhost", "127.0.0.1"};
/**
diff --git a/src/main/java/org/apache/sling/discovery/oak/JoinerDelay.java b/src/main/java/org/apache/sling/discovery/oak/JoinerDelay.java
index 822d1ef..ab0c7e4 100644
--- a/src/main/java/org/apache/sling/discovery/oak/JoinerDelay.java
+++ b/src/main/java/org/apache/sling/discovery/oak/JoinerDelay.java
@@ -130,13 +130,17 @@ public class JoinerDelay implements ClusterSyncService {
if (clusterView instanceof LocalClusterView) {
final LocalClusterView localClusterView = (LocalClusterView) clusterView;
if (localClusterView.hasPartiallyStartedInstances()) {
- logSilencer.infoOrDebug("joinerConditionApplies", "joinerConditionApplies : local cluster has partially started instances - delaying");
+ logSilencer.infoOrDebug(
+ "joinerConditionApplies",
+ "joinerConditionApplies : local cluster has partially started instances - delaying");
return true;
}
}
return false;
- } catch(Exception e) {
- logger.error("joinerConditionApplies : got Exception, ignoring JoinerDelay (log level debug shows stacktrace): " + e);
+ } catch (Exception e) {
+ logger.error(
+ "joinerConditionApplies : got Exception, ignoring JoinerDelay (log level debug shows stacktrace): "
+ + e);
logger.debug("joinerConditionApplies : got Exception, ignoring JoinerDelay : " + e, e);
// false disables the JoinerDelay - so lets do that on error
return false;
@@ -145,8 +149,9 @@ public class JoinerDelay implements ClusterSyncService {
private final void assertCorrectThreadPool() {
if (!Thread.currentThread().getName().contains("sling-discovery")) {
- logger.warn("assertCorrectThreadPool : not running as part of 'discovery' thread pool."
- + " Check configuration and ensure 'discovery' is in 'allowedPoolNames' of 'org.apache.sling.commons.scheduler'");
+ logger.warn(
+ "assertCorrectThreadPool : not running as part of 'discovery' thread pool."
+ + " Check configuration and ensure 'discovery' is in 'allowedPoolNames' of 'org.apache.sling.commons.scheduler'");
}
}
@@ -160,7 +165,7 @@ public class JoinerDelay implements ClusterSyncService {
}
// here we can be in any phase (IDLE, DELAYING, DONE)
final boolean isPhaseDone;
- synchronized(this) {
+ synchronized (this) {
if (phase == Phase.IDLE) {
if (joinerConditionApplies(view)) {
markDelaying();
@@ -191,13 +196,12 @@ public class JoinerDelay implements ClusterSyncService {
// invoke callback (outside synchronization)
callback.run();
}
-
};
if (absoluteTimeout.compareTo(new Date()) < 0) {
// invoke callback (outside synchronization)
doContinue.execute(null);
- } else if (!scheduler.schedule(doContinue,
- scheduler.AT(absoluteTimeout).name(NAME).threadPoolName("discovery"))) {
+ } else if (!scheduler.schedule(
+ doContinue, scheduler.AT(absoluteTimeout).name(NAME).threadPoolName("discovery"))) {
// then let's do it anyway
logger.error("sync : schedule failed - ignoring JoinerDelay");
// invoke callback (outside synchronization)
@@ -209,7 +213,7 @@ public class JoinerDelay implements ClusterSyncService {
public void cancelSync() {
try {
scheduler.unschedule(NAME);
- } catch(Exception e) {
+ } catch (Exception e) {
logger.warn("cancelSync: got Exception (log level debug shows stacktrace): " + e);
logger.debug("cancelSync: got Exception : " + e, e);
}
@@ -224,10 +228,9 @@ public class JoinerDelay implements ClusterSyncService {
// might be called within or without synchronzied(this), so we do it ourselves
private final void markDone() {
- synchronized(this) {
+ synchronized (this) {
if (absoluteTimeout == null && phase == Phase.DONE) {
- logger.warn("markDone : already marked done: absoluteTimeout = {}, phase = {}",
- absoluteTimeout, phase);
+ logger.warn("markDone : already marked done: absoluteTimeout = {}, phase = {}", absoluteTimeout, phase);
}
absoluteTimeout = null;
phase = Phase.DONE;
diff --git a/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java b/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java
index d98e1b2..437aba5 100644
--- a/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java
+++ b/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java
@@ -81,10 +81,12 @@ import org.slf4j.LoggerFactory;
* implementation for detecting changes in a cluster and only supports one
* cluster (of which this instance is part of).
*/
-@Component(immediate = true, service = {DiscoveryService.class, OakDiscoveryService.class})
+@Component(
+ immediate = true,
+ service = {DiscoveryService.class, OakDiscoveryService.class})
public class OakDiscoveryService extends BaseDiscoveryService {
- private final static Logger logger = LoggerFactory.getLogger(OakDiscoveryService.class);
+ private static final Logger logger = LoggerFactory.getLogger(OakDiscoveryService.class);
@Reference
private SlingSettingsService settingsService;
@@ -153,25 +155,28 @@ public class OakDiscoveryService extends BaseDiscoveryService {
@Override
public void handleTopologyEvent(TopologyEvent event) {
OakViewChecker checker = oakViewChecker;
- if (activated && checker != null
+ if (activated
+ && checker != null
&& (event.getType() == Type.TOPOLOGY_CHANGED || event.getType() == Type.PROPERTIES_CHANGED)) {
- logger.debug("changePropagationListener.handleTopologyEvent: topology changed - propagate through connectors");
+ logger.debug(
+ "changePropagationListener.handleTopologyEvent: topology changed - propagate through connectors");
checker.triggerAsyncConnectorPing();
}
}
};
- public static OakDiscoveryService testConstructor(SlingSettingsService settingsService,
- AnnouncementRegistry announcementRegistry,
- ConnectorRegistry connectorRegistry,
- ClusterViewService clusterViewService,
- Config config,
- OakViewChecker connectorPinger,
- Scheduler scheduler,
- IdMapService idMapService,
- OakBacklogClusterSyncService oakBacklogClusterSyncService,
- SyncTokenService syncTokenService,
- ResourceResolverFactory factory) {
+ public static OakDiscoveryService testConstructor(
+ SlingSettingsService settingsService,
+ AnnouncementRegistry announcementRegistry,
+ ConnectorRegistry connectorRegistry,
+ ClusterViewService clusterViewService,
+ Config config,
+ OakViewChecker connectorPinger,
+ Scheduler scheduler,
+ IdMapService idMapService,
+ OakBacklogClusterSyncService oakBacklogClusterSyncService,
+ SyncTokenService syncTokenService,
+ ResourceResolverFactory factory) {
OakDiscoveryService discoService = new OakDiscoveryService();
discoService.settingsService = settingsService;
discoService.announcementRegistry = announcementRegistry;
@@ -196,13 +201,14 @@ public class OakDiscoveryService extends BaseDiscoveryService {
// (which will in turn take effect on the next round of
// voting, or also double-checked when the local instance votes)
//
- //TODO:
+ // TODO:
// Note that when the local instance doesn't notice
// an 'ISOLATED_FROM_TOPOLOGY' case, then the leaderElectionId
// will not be reset. Which means that it then could potentially
// regain leadership.
if (oakViewChecker.resetLeaderElectionId()) {
- logger.info("getTopology: reset leaderElectionId to force this instance to the end of the instance order (thus incl not to remain leader)");
+ logger.info(
+ "getTopology: reset leaderElectionId to force this instance to the end of the instance order (thus incl not to remain leader)");
}
}
}
@@ -225,15 +231,15 @@ public class OakDiscoveryService extends BaseDiscoveryService {
ClusterSyncService consistencyService;
if (config.getSyncTokenEnabled()) {
- //TODO: ConsistencyHistory is implemented a little bit hacky ..
+ // TODO: ConsistencyHistory is implemented a little bit hacky ..
ClusterSyncHistory consistencyHistory = new ClusterSyncHistory();
oakBacklogClusterSyncService.setConsistencyHistory(consistencyHistory);
syncTokenService.setConsistencyHistory(consistencyHistory);
JoinerDelay joinerDelay = new JoinerDelay(config.getJoinerDelayMillis(), scheduler);
- consistencyService = new ClusterSyncServiceChain(oakBacklogClusterSyncService, syncTokenService, joinerDelay);
+ consistencyService =
+ new ClusterSyncServiceChain(oakBacklogClusterSyncService, syncTokenService, joinerDelay);
} else {
consistencyService = oakBacklogClusterSyncService;
-
}
viewStateManager = ViewStateManagerFactory.newViewStateManager(viewStateManagerLock, consistencyService);
@@ -277,7 +283,8 @@ public class OakDiscoveryService extends BaseDiscoveryService {
viewStateManager.handleNewView(newView);
} else {
// SLING-3750: just issue a log.info about the delaying
- logger.info("activate: this instance is in isolated mode and must yet finish voting before it can send out TOPOLOGY_INIT.");
+ logger.info(
+ "activate: this instance is in isolated mode and must yet finish voting before it can send out TOPOLOGY_INIT.");
}
activated = true;
setOldView(newView);
@@ -345,11 +352,13 @@ public class OakDiscoveryService extends BaseDiscoveryService {
/**
* bind a topology event listener
*/
- @Reference(name = "eventListeners",
+ @Reference(
+ name = "eventListeners",
service = TopologyEventListener.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
- bind = "bindTopologyEventListener", unbind = "bindTopologyEventListener")
+ bind = "bindTopologyEventListener",
+ unbind = "bindTopologyEventListener")
protected void bindTopologyEventListener(final TopologyEventListener eventListener) {
viewStateManagerLock.lock();
try {
@@ -386,11 +395,14 @@ public class OakDiscoveryService extends BaseDiscoveryService {
/**
* Bind a new property provider.
*/
- @Reference(name = "providerInfos",
+ @Reference(
+ name = "providerInfos",
service = PropertyProvider.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
- bind = "bindPropertyProvider", unbind = "unbindPropertyProvider", updated = "updatedPropertyProvider")
+ bind = "bindPropertyProvider",
+ unbind = "unbindPropertyProvider",
+ updated = "updatedPropertyProvider")
protected void bindPropertyProvider(final PropertyProvider propertyProvider, final Map<String, Object> props) {
logger.debug("bindPropertyProvider: Binding PropertyProvider {}", propertyProvider);
@@ -399,7 +411,8 @@ public class OakDiscoveryService extends BaseDiscoveryService {
this.bindPropertyProviderInteral(propertyProvider, props);
} catch (RuntimeException re) {
// SLING-10204 : catch and instead log less noisy as this can legitimately happen
- logger.warn("bindPropertyProvider: got RuntimeException (enable debug logging to see stacktrace) : " + re);
+ logger.warn(
+ "bindPropertyProvider: got RuntimeException (enable debug logging to see stacktrace) : " + re);
logger.debug("bindPropertyProvider: RuntimeException stacktrace", re);
}
}
@@ -430,7 +443,8 @@ public class OakDiscoveryService extends BaseDiscoveryService {
this.bindPropertyProviderInteral(propertyProvider, props);
} catch (RuntimeException re) {
// SLING-10204 : catch and instead log less noisy as this can legitimately happen
- logger.warn("updatePropertyProvider: got RuntimeException (enable debug logging to see stacktrace) : " + re);
+ logger.warn("updatePropertyProvider: got RuntimeException (enable debug logging to see stacktrace) : "
+ + re);
logger.debug("updatePropertyProvider: RuntimeException stacktrace", re);
}
}
@@ -446,7 +460,8 @@ public class OakDiscoveryService extends BaseDiscoveryService {
this.unbindPropertyProviderInternal(propertyProvider, props, true);
} catch (RuntimeException re) {
// SLING-10204 : catch and instead log less noisy as this can legitimately happen
- logger.warn("unbindPropertyProvider: got RuntimeException (enable debug logging to see stacktrace) : " + re);
+ logger.warn("unbindPropertyProvider: got RuntimeException (enable debug logging to see stacktrace) : "
+ + re);
logger.debug("unbindPropertyProvider: RuntimeException stacktrace", re);
}
}
@@ -456,8 +471,7 @@ public class OakDiscoveryService extends BaseDiscoveryService {
* Unbind a property provider
*/
private void unbindPropertyProviderInternal(
- final PropertyProvider propertyProvider,
- final Map<String, Object> props, final boolean update) {
+ final PropertyProvider propertyProvider, final Map<String, Object> props, final boolean update) {
final ProviderInfo info = new ProviderInfo(propertyProvider, props);
if (this.providerInfos.remove(info) && update) {
@@ -489,9 +503,10 @@ public class OakDiscoveryService extends BaseDiscoveryService {
final String sid = slingId;
if (rrf == null || c == null || sid == null) {
// cannot update the properties then..
- logger.debug("doUpdateProperties: too early to update the properties. "
+ logger.debug(
+ "doUpdateProperties: too early to update the properties. "
+ "resourceResolverFactory ({}), config ({}) or slingId ({}) not yet set.",
- new Object[]{rrf, c, sid});
+ new Object[] {rrf, c, sid});
return;
} else {
logger.debug("doUpdateProperties: updating properties now..");
@@ -507,8 +522,8 @@ public class OakDiscoveryService extends BaseDiscoveryService {
try {
resourceResolver = rrf.getServiceResourceResolver(null);
- Resource myInstance = ResourceHelper
- .getOrCreateResource(resourceResolver, c.getClusterInstancesPath() + "/" + sid + "/properties");
+ Resource myInstance = ResourceHelper.getOrCreateResource(
+ resourceResolver, c.getClusterInstancesPath() + "/" + sid + "/properties");
// SLING-2879 - revert/refresh resourceResolver here to work
// around a potential issue with jackrabbit in a clustered environment
resourceResolver.revert();
@@ -554,7 +569,7 @@ public class OakDiscoveryService extends BaseDiscoveryService {
throw new RuntimeException("Could not log in to repository (" + e + ")", e);
} catch (PersistenceException e) {
logger.error("handleEvent: got a PersistenceException: " + e, e);
- throw new RuntimeException( "Exception while talking to repository (" + e + ")", e);
+ throw new RuntimeException("Exception while talking to repository (" + e + ")", e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
@@ -584,7 +599,7 @@ public class OakDiscoveryService extends BaseDiscoveryService {
/**
* Internal class caching some provider infos like service id and ranking.
*/
- private final static class ProviderInfo implements Comparable<ProviderInfo> {
+ private static final class ProviderInfo implements Comparable<ProviderInfo> {
public final PropertyProvider provider;
public final Object propertyProperties;
@@ -592,8 +607,7 @@ public class OakDiscoveryService extends BaseDiscoveryService {
public final long serviceId;
public final Map<String, String> properties = new HashMap<String, String>();
- public ProviderInfo(final PropertyProvider provider,
- final Map<String, Object> serviceProps) {
+ public ProviderInfo(final PropertyProvider provider, final Map<String, Object> serviceProps) {
this.provider = provider;
this.propertyProperties = serviceProps.get(PropertyProvider.PROPERTY_PROPERTIES);
final Object sr = serviceProps.get(Constants.SERVICE_RANKING);
@@ -715,5 +729,4 @@ public class OakDiscoveryService extends BaseDiscoveryService {
public ViewStateManager getViewStateManager() {
return viewStateManager;
}
-
}
diff --git a/src/main/java/org/apache/sling/discovery/oak/SlingIdCleanupTask.java b/src/main/java/org/apache/sling/discovery/oak/SlingIdCleanupTask.java
index fb51070..bd10b4a 100644
--- a/src/main/java/org/apache/sling/discovery/oak/SlingIdCleanupTask.java
+++ b/src/main/java/org/apache/sling/discovery/oak/SlingIdCleanupTask.java
@@ -18,8 +18,6 @@
*/
package org.apache.sling.discovery.oak;
-import static org.osgi.util.converter.Converters.standardConverter;
-
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
@@ -54,6 +52,8 @@ import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.osgi.util.converter.Converters.standardConverter;
+
/**
* A background task that cleans up garbage slingIds after topology changes.
* <p>
@@ -97,10 +97,11 @@ import org.slf4j.LoggerFactory;
@Designate(ocd = SlingIdCleanupTask.Conf.class)
public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
- final static String SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME = "org.apache.sling.discovery.oak.slingidcleanup.enabled";
+ static final String SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME =
+ "org.apache.sling.discovery.oak.slingidcleanup.enabled";
/** default minimal cleanup delay at 13h, to intraday load balance */
- final static long MIN_CLEANUP_DELAY_MILLIS = 46800000;
+ static final long MIN_CLEANUP_DELAY_MILLIS = 46800000;
/**
* default age is 1 week : an instance that is not in the current topology,
@@ -198,28 +199,44 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
*/
private Set<String> seenInstances = new CopyOnWriteArraySet<>();
- @ObjectClassDefinition(name = "Apache Sling Discovery Oak SlingId Cleanup Task", description = "This task is in charge of cleaning up old SlingIds from the repository.")
+ @ObjectClassDefinition(
+ name = "Apache Sling Discovery Oak SlingId Cleanup Task",
+ description = "This task is in charge of cleaning up old SlingIds from the repository.")
public @interface Conf {
- @AttributeDefinition(name = "Cleanup initial delay milliseconds", description = "Number of milliseconds to initially wait for the first cleanup")
+ @AttributeDefinition(
+ name = "Cleanup initial delay milliseconds",
+ description = "Number of milliseconds to initially wait for the first cleanup")
int slingid_cleanup_initial_delay() default DEFAULT_CLEANUP_INITIAL_DELAY;
- @AttributeDefinition(name = "Cleanup interval milliseconds", description = "Number of milliseconds after which to do another batch of cleaning up (if necessary)")
+ @AttributeDefinition(
+ name = "Cleanup interval milliseconds",
+ description = "Number of milliseconds after which to do another batch of cleaning up (if necessary)")
int slingid_cleanup_interval() default DEFAULT_CLEANUP_INTERVAL;
- @AttributeDefinition(name = "Cleanup batch size", description = "Maximum number of slingIds to cleanup in one batch.")
+ @AttributeDefinition(
+ name = "Cleanup batch size",
+ description = "Maximum number of slingIds to cleanup in one batch.")
int slingid_cleanup_batchsize() default DEFAULT_CLEANUP_BATCH_SIZE;
- @AttributeDefinition(name = "Cleanup minimum creation age", description = "Minimum number of milliseconds since the slingId was created.")
+ @AttributeDefinition(
+ name = "Cleanup minimum creation age",
+ description = "Minimum number of milliseconds since the slingId was created.")
long slingid_cleanup_min_creation_age() default DEFAULT_MIN_CREATION_AGE_MILLIS;
}
/**
* Test constructor
*/
- static SlingIdCleanupTask create(Scheduler scheduler, ResourceResolverFactory factory,
- Config config, int initialDelayMillis, int intervalMillis, int batchSize,
- long minCreationAgeMillis, long minCleanupDelayMillis) {
+ static SlingIdCleanupTask create(
+ Scheduler scheduler,
+ ResourceResolverFactory factory,
+ Config config,
+ int initialDelayMillis,
+ int intervalMillis,
+ int batchSize,
+ long minCreationAgeMillis,
+ long minCleanupDelayMillis) {
final SlingIdCleanupTask s = new SlingIdCleanupTask();
s.scheduler = scheduler;
s.resourceResolverFactory = factory;
@@ -239,7 +256,9 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
if (config == null) {
return;
}
- config(config.slingid_cleanup_initial_delay(), config.slingid_cleanup_interval(),
+ config(
+ config.slingid_cleanup_initial_delay(),
+ config.slingid_cleanup_interval(),
config.slingid_cleanup_batchsize(),
config.slingid_cleanup_min_creation_age());
}
@@ -250,15 +269,17 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
hasTopology = false;
}
- private void config(int initialDelayMillis, int intervalMillis, int batchSize,
- long minCreationAgeMillis) {
+ private void config(int initialDelayMillis, int intervalMillis, int batchSize, long minCreationAgeMillis) {
this.initialDelayMillis = initialDelayMillis;
this.intervalMillis = intervalMillis;
this.batchSize = batchSize;
this.minCreationAgeMillis = minCreationAgeMillis;
logger.info(
"config: enabled = {}, initial delay milliseconds = {}, interval milliseconds = {}, batch size = {}, min creation age milliseconds = {}",
- isEnabled(), initialDelayMillis, intervalMillis, batchSize,
+ isEnabled(),
+ initialDelayMillis,
+ intervalMillis,
+ batchSize,
minCreationAgeMillis);
}
@@ -318,9 +339,10 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
* Reads the system property that enables or disabled this tasks
*/
private static boolean isEnabled() {
- final String systemPropertyValue = System
- .getProperty(SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME);
- return standardConverter().convert(systemPropertyValue).defaultValue(false)
+ final String systemPropertyValue = System.getProperty(SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME);
+ return standardConverter()
+ .convert(systemPropertyValue)
+ .defaultValue(false)
.to(Boolean.class);
}
@@ -350,7 +372,8 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
final Date scheduledDate = cal.getTime();
logger.info(
"recreateSchedule: scheduling a cleanup in {} milliseconds from now, which is: {}",
- delayMillis, scheduledDate);
+ delayMillis,
+ scheduledDate);
ScheduleOptions options = localScheduler.AT(scheduledDate);
options.name(SCHEDULE_NAME);
options.canRunConcurrently(false); // should not concurrently execute
@@ -364,8 +387,7 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
*/
@Override
public void run() {
- if (lastSuccessfulRun > 0 && System.currentTimeMillis()
- - lastSuccessfulRun < minCleanupDelayMillis) {
+ if (lastSuccessfulRun > 0 && System.currentTimeMillis() - lastSuccessfulRun < minCleanupDelayMillis) {
logger.debug(
"run: last cleanup was {} millis ago, which is less than {} millis, therefore not cleaning up yet.",
System.currentTimeMillis() - lastSuccessfulRun,
@@ -392,14 +414,16 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
// log successful cleanup done, yes, on info
logger.info(
"run: slingId cleanup done, run counter = {}, delete counter = {}, completion counter = {}",
- getRunCount(), getDeleteCount(), getCompletionCount());
+ getRunCount(),
+ getDeleteCount(),
+ getCompletionCount());
lastSuccessfulRun = System.currentTimeMillis();
}
/**
* Do the actual cleanup of garbage slingIds and report back with true if there
* might be more or false if we're at the end.
- *
+ *
* @return true if there might be more garbage or false if we're at the end
*/
private boolean cleanup() {
@@ -414,33 +438,30 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
final ResourceResolverFactory localFactory = resourceResolverFactory;
final Config localConfig = config;
if (localFactory == null || localConfig == null) {
- logger.warn("cleanup: cannot cleanup due to rrf={} or c={}", localFactory,
- localConfig);
+ logger.warn("cleanup: cannot cleanup due to rrf={} or c={}", localFactory, localConfig);
return true;
}
final TopologyView localCurrentView = currentView;
if (localCurrentView == null || !localCurrentView.isCurrent()) {
- logger.debug("cleanup : cannot cleanup as topology recently changed : {}",
- localCurrentView);
+ logger.debug("cleanup : cannot cleanup as topology recently changed : {}", localCurrentView);
return true;
}
final Set<String> activeSlingIds = getActiveSlingIds(localCurrentView);
try (ResourceResolver resolver = localFactory.getServiceResourceResolver(null)) {
- final Resource clusterInstances = resolver
- .getResource(localConfig.getClusterInstancesPath());
+ final Resource clusterInstances = resolver.getResource(localConfig.getClusterInstancesPath());
final Resource idMap = resolver.getResource(localConfig.getIdMapPath());
- final Resource syncTokens = resolver
- .getResource(localConfig.getSyncTokenPath());
+ final Resource syncTokens = resolver.getResource(localConfig.getSyncTokenPath());
if (clusterInstances == null || idMap == null || syncTokens == null) {
- logger.warn("cleanup: no resource found at {}, {} or {}, stopping.",
- localConfig.getClusterInstancesPath(), localConfig.getIdMapPath(),
+ logger.warn(
+ "cleanup: no resource found at {}, {} or {}, stopping.",
+ localConfig.getClusterInstancesPath(),
+ localConfig.getIdMapPath(),
localConfig.getSyncTokenPath());
return false;
}
resolver.refresh();
final ValueMap idMapMap = idMap.adaptTo(ValueMap.class);
- final ModifiableValueMap syncTokenMap = syncTokens
- .adaptTo(ModifiableValueMap.class);
+ final ModifiableValueMap syncTokenMap = syncTokens.adaptTo(ModifiableValueMap.class);
final Calendar now = Calendar.getInstance();
int removed = 0;
boolean mightHaveMore = false;
@@ -451,8 +472,8 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
return true;
}
final String slingId = resource.getName();
- if (deleteIfOldSlingId(resource, slingId, syncTokenMap, idMapMap,
- activeSlingIds, now, localMinCreationAgeMillis)) {
+ if (deleteIfOldSlingId(
+ resource, slingId, syncTokenMap, idMapMap, activeSlingIds, now, localMinCreationAgeMillis)) {
if (++removed >= localBatchSize) {
// we need to stop
mightHaveMore = true;
@@ -473,8 +494,14 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
return true;
}
Resource resourceOrNull = clusterInstances.getChild(slingId);
- if (deleteIfOldSlingId(resourceOrNull, slingId, syncTokenMap,
- idMapMap, activeSlingIds, now, localMinCreationAgeMillis)) {
+ if (deleteIfOldSlingId(
+ resourceOrNull,
+ slingId,
+ syncTokenMap,
+ idMapMap,
+ activeSlingIds,
+ now,
+ localMinCreationAgeMillis)) {
if (++removed >= localBatchSize) {
// we need to stop
mightHaveMore = true;
@@ -491,7 +518,9 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
resolver.commit();
logger.info(
"cleanup : removed {} old slingIds (batch size : {}), potentially has more: {}",
- removed, localBatchSize, mightHaveMore);
+ removed,
+ localBatchSize,
+ mightHaveMore);
deleteCount.addAndGet(removed);
}
firstRun = false;
@@ -502,22 +531,20 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
throw new RuntimeException("Could not log in to repository (" + e + ")", e);
} catch (PersistenceException e) {
logger.error("cleanup: got a PersistenceException: " + e, e);
- throw new RuntimeException(
- "Exception while talking to repository (" + e + ")", e);
+ throw new RuntimeException("Exception while talking to repository (" + e + ")", e);
} finally {
logger.debug("cleanup: done.");
}
}
private Set<String> getActiveSlingIds(final TopologyView localCurrentView) {
- return localCurrentView.getLocalInstance().getClusterView().getInstances()
- .stream().map(InstanceDescription::getSlingId)
+ return localCurrentView.getLocalInstance().getClusterView().getInstances().stream()
+ .map(InstanceDescription::getSlingId)
.collect(Collectors.toSet());
}
private boolean topologyChanged(TopologyView localCurrentView) {
- if (!hasTopology || currentView != localCurrentView
- || !localCurrentView.isCurrent()) {
+ if (!hasTopology || currentView != localCurrentView || !localCurrentView.isCurrent()) {
// we got interrupted during cleanup
// let's not commit at all then
logger.debug(
@@ -543,18 +570,21 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
return -1;
}
- private boolean deleteIfOldSlingId(Resource resourceOrNull, String slingId,
- ModifiableValueMap syncTokenMap, ValueMap idMapMap,
- Set<String> activeSlingIds, Calendar now, long localMinCreationAgeMillis)
+ private boolean deleteIfOldSlingId(
+ Resource resourceOrNull,
+ String slingId,
+ ModifiableValueMap syncTokenMap,
+ ValueMap idMapMap,
+ Set<String> activeSlingIds,
+ Calendar now,
+ long localMinCreationAgeMillis)
throws PersistenceException {
logger.trace("deleteIfOldSlingId : handling slingId = {}", slingId);
if (activeSlingIds.contains(slingId)) {
- logger.trace("deleteIfOldSlingId : slingId is currently active : {}",
- slingId);
+ logger.trace("deleteIfOldSlingId : slingId is currently active : {}", slingId);
return false;
} else if (seenInstances.contains(slingId)) {
- logger.trace("deleteIfOldSlingId : slingId seen active previously : {}",
- slingId);
+ logger.trace("deleteIfOldSlingId : slingId seen active previously : {}", slingId);
return false;
}
// only check in idmap and for leaderElectionId details if the clusterInstance
@@ -562,11 +592,9 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
if (resourceOrNull != null) {
Object clusterNodeId = idMapMap.get(slingId);
if (clusterNodeId == null) {
- logger.trace("deleteIfOldSlingId : slingId {} not recently in use",
- slingId);
+ logger.trace("deleteIfOldSlingId : slingId {} not recently in use", slingId);
} else {
- logger.trace("deleteIfOldSlingId : slingId {} WAS recently in use : {}",
- slingId, clusterNodeId);
+ logger.trace("deleteIfOldSlingId : slingId {} WAS recently in use : {}", slingId, clusterNodeId);
return false;
}
Object o = resourceOrNull.getValueMap().get("leaderElectionIdCreatedAt");
@@ -575,7 +603,8 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
// skip
logger.trace(
"deleteIfOldSlingId: resource ({}) has no or wrongly typed leaderElectionIdCreatedAt : {}",
- resourceOrNull, o);
+ resourceOrNull,
+ o);
return false;
}
final long diffMillis = now.getTimeInMillis() - leaderElectionIdCreatedAt;
@@ -603,4 +632,4 @@ public class SlingIdCleanupTask implements TopologyEventListener, Runnable {
int getCompletionCount() {
return completionCount.get();
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/discovery/oak/SynchronizedClocksHealthCheck.java b/src/main/java/org/apache/sling/discovery/oak/SynchronizedClocksHealthCheck.java
index e6d8e2a..8dc6453 100644
--- a/src/main/java/org/apache/sling/discovery/oak/SynchronizedClocksHealthCheck.java
+++ b/src/main/java/org/apache/sling/discovery/oak/SynchronizedClocksHealthCheck.java
@@ -18,18 +18,18 @@
*/
package org.apache.sling.discovery.oak;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
import java.lang.management.ManagementFactory;
import java.util.Collection;
import java.util.Set;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-import org.apache.sling.discovery.base.connectors.announcement.Announcement;
-import org.apache.sling.discovery.base.connectors.announcement.AnnouncementRegistry;
+import org.apache.felix.hc.api.FormattingResultLog;
import org.apache.felix.hc.api.HealthCheck;
import org.apache.felix.hc.api.Result;
-import org.apache.felix.hc.api.FormattingResultLog;
+import org.apache.sling.discovery.base.connectors.announcement.Announcement;
+import org.apache.sling.discovery.base.connectors.announcement.AnnouncementRegistry;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@@ -54,8 +54,8 @@ import org.slf4j.LoggerFactory;
immediate = true,
service = HealthCheck.class,
property = {
- HealthCheck.NAME + "=Synchronized Clocks",
- HealthCheck.MBEAN_NAME + "=slingDiscoveryOakSynchronizedClocks"
+ HealthCheck.NAME + "=Synchronized Clocks",
+ HealthCheck.MBEAN_NAME + "=slingDiscoveryOakSynchronizedClocks"
})
public class SynchronizedClocksHealthCheck implements HealthCheck {
@@ -90,7 +90,7 @@ public class SynchronizedClocksHealthCheck implements HealthCheck {
} else {
ObjectName firstName = names.iterator().next();
final Object value = jmxServer.invoke(firstName, TIME_DIFF_METHOD_NAME, new Object[0], new String[0]);
- logger.debug("{} returns {}", new Object[] { firstName, TIME_DIFF_METHOD_NAME, value });
+ logger.debug("{} returns {}", new Object[] {firstName, TIME_DIFF_METHOD_NAME, value});
resultLog.debug("{} returns {}", firstName, TIME_DIFF_METHOD_NAME, value);
if (value != null && (value instanceof Long)) {
Long diffMillis = (Long) value;
@@ -98,42 +98,54 @@ public class SynchronizedClocksHealthCheck implements HealthCheck {
logger.warn(
"execute: clocks in local cluster out of sync by {}ms "
+ "which is equal or higher than the high-water mark of {}ms.",
- diffMillis, INTRA_CLUSTER_HIGH_WATER_MARK);
+ diffMillis,
+ INTRA_CLUSTER_HIGH_WATER_MARK);
resultLog.critical(
"Clocks heavily out of sync in local cluster: "
+ "time difference of this VM with DocumentStore server: "
+ "{}ms is equal or larger than high-water mark of {}ms",
- diffMillis, INTRA_CLUSTER_HIGH_WATER_MARK);
+ diffMillis,
+ INTRA_CLUSTER_HIGH_WATER_MARK);
} else if (Math.abs(diffMillis) >= INTRA_CLUSTER_LOW_WATER_MARK) {
logger.warn(
"execute: clocks in local cluster out of sync by {}ms"
+ "ms which is equal or higher than the low-water mark of {}ms.",
- diffMillis, INTRA_CLUSTER_LOW_WATER_MARK);
+ diffMillis,
+ INTRA_CLUSTER_LOW_WATER_MARK);
resultLog.warn(
"Clocks noticeably out of sync in local cluster: "
+ "time difference of this VM with DocumentStore server: "
+ "{}ms is equal or larger than low-water mark of {}ms",
- diffMillis, INTRA_CLUSTER_LOW_WATER_MARK);
+ diffMillis,
+ INTRA_CLUSTER_LOW_WATER_MARK);
} else {
- logger.debug("execute: clocks in local cluster in sync. diff is {}ms"
- + "ms which is within low-water mark of {}ms.", diffMillis, INTRA_CLUSTER_LOW_WATER_MARK);
- resultLog.info("Clocks in sync in local cluster: time difference of this VM with DocumentStore server: "
- + "{}ms is within low-water mark of {}ms", diffMillis, INTRA_CLUSTER_LOW_WATER_MARK);
+ logger.debug(
+ "execute: clocks in local cluster in sync. diff is {}ms"
+ + "ms which is within low-water mark of {}ms.",
+ diffMillis,
+ INTRA_CLUSTER_LOW_WATER_MARK);
+ resultLog.info(
+ "Clocks in sync in local cluster: time difference of this VM with DocumentStore server: "
+ + "{}ms is within low-water mark of {}ms",
+ diffMillis,
+ INTRA_CLUSTER_LOW_WATER_MARK);
}
}
}
} catch (final Exception e) {
- logger.warn("execute: {}, JMX method {} invocation failed: {}",
- new Object[] { DOCUMENT_NODE_STORE_MBEAN, TIME_DIFF_METHOD_NAME, e });
- resultLog.healthCheckError("{}, JMX method {} invocation failed: {}", DOCUMENT_NODE_STORE_MBEAN, TIME_DIFF_METHOD_NAME,
- e);
+ logger.warn(
+ "execute: {}, JMX method {} invocation failed: {}",
+ new Object[] {DOCUMENT_NODE_STORE_MBEAN, TIME_DIFF_METHOD_NAME, e});
+ resultLog.healthCheckError(
+ "{}, JMX method {} invocation failed: {}", DOCUMENT_NODE_STORE_MBEAN, TIME_DIFF_METHOD_NAME, e);
}
final String slingId = settingsService == null ? "n/a" : settingsService.getSlingId();
if (announcementRegistry == null) {
logger.warn("execute: no announcementRegistry ({}) set", announcementRegistry);
- resultLog.warn("Cannot determine topology clocks since no announcementRegistry ({}) set", announcementRegistry);
+ resultLog.warn(
+ "Cannot determine topology clocks since no announcementRegistry ({}) set", announcementRegistry);
} else {
final Collection<Announcement> localAnnouncements = announcementRegistry.listLocalAnnouncements();
if (localAnnouncements.isEmpty()) {
@@ -149,34 +161,33 @@ public class SynchronizedClocksHealthCheck implements HealthCheck {
logger.warn(
"execute: clocks between local instance (slingId: {}) and remote instance (slingId: {}) out of sync by {}ms"
+ "ms which is equal or higher than the high-water mark of {}ms.",
- new Object[] { slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK });
+ new Object[] {slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK});
resultLog.critical(
"Clocks heavily out of sync between local instance (slingId: {}) and remote instance (slingId: {}): "
+ "by {}ms which is equal or larger than high-water mark of {}ms",
- new Object[] { slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK });
+ new Object[] {slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK});
} else if (Math.abs(diffMillis) >= INTER_CLUSTER_LOW_WATER_MARK) {
logger.warn(
"execute: clocks out of sync between local instance (slingId: {}) and remote instance (slingId: {}) by {}ms "
+ "ms which is equal or higher than the low-water mark of {}ms.",
- new Object[] { slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK });
+ new Object[] {slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK});
resultLog.warn(
"Clocks noticeably out of sync between local instance (slingId: {}) and remote instance (slingId: {}): "
- + "by {}ms which is equal or larger than low-water mark of {}ms",
- new Object[] { slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK });
+ + "by {}ms which is equal or larger than low-water mark of {}ms",
+ new Object[] {slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK});
} else {
logger.debug(
"execute: clocks in sync between local instance (slingId: {}) and remote instance (slingId: {}). "
- + "diff is {}ms which is within low-water mark of {}ms.",
- new Object[] { slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK });
+ + "diff is {}ms which is within low-water mark of {}ms.",
+ new Object[] {slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK});
resultLog.info(
"Clocks in sync between local instance (slingId: {}) and remote instance (slingId: {}): "
- + "diff is {}ms which is within low-water mark of {}ms",
- new Object[] { slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK });
+ + "diff is {}ms which is within low-water mark of {}ms",
+ new Object[] {slingId, peerSlingId, diffMillis, INTER_CLUSTER_HIGH_WATER_MARK});
}
}
}
return new Result(resultLog);
}
-
}
diff --git a/src/main/java/org/apache/sling/discovery/oak/TopologyWebConsolePlugin.java b/src/main/java/org/apache/sling/discovery/oak/TopologyWebConsolePlugin.java
index d6f3fa9..9698690 100644
--- a/src/main/java/org/apache/sling/discovery/oak/TopologyWebConsolePlugin.java
+++ b/src/main/java/org/apache/sling/discovery/oak/TopologyWebConsolePlugin.java
@@ -18,6 +18,11 @@
*/
package org.apache.sling.discovery.oak;
+import javax.servlet.Servlet;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
@@ -33,11 +38,6 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
-import javax.servlet.Servlet;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.felix.webconsole.AbstractWebConsolePlugin;
import org.apache.felix.webconsole.WebConsoleConstants;
import org.apache.sling.api.resource.LoginException;
@@ -72,12 +72,13 @@ import org.slf4j.LoggerFactory;
* Simple webconsole which gives an overview of the topology visible by the
* discovery service
*/
-@Component(service = { TopologyEventListener.class, Servlet.class },
+@Component(
+ service = {TopologyEventListener.class, Servlet.class},
property = {
- WebConsoleConstants.PLUGIN_LABEL+"="+TopologyWebConsolePlugin.LABEL,
- WebConsoleConstants.PLUGIN_TITLE+"="+TopologyWebConsolePlugin.TITLE,
- "felix.webconsole.category=Sling",
- "felix.webconsole.configprinter.modes={zip}"
+ WebConsoleConstants.PLUGIN_LABEL + "=" + TopologyWebConsolePlugin.LABEL,
+ WebConsoleConstants.PLUGIN_TITLE + "=" + TopologyWebConsolePlugin.TITLE,
+ "felix.webconsole.category=Sling",
+ "felix.webconsole.configprinter.modes={zip}"
})
@ServiceDescription("Apache Sling Web Console Plugin to display Background servlets and ExecutionEngine status")
@SuppressWarnings("serial")
@@ -149,8 +150,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
throws ServletException, IOException {
Object rawRoot = req.getAttribute(WebConsoleConstants.ATTR_PLUGIN_ROOT);
if (!(rawRoot instanceof String)) {
- throw new ServletException("Illegal attr: "
- + WebConsoleConstants.ATTR_PLUGIN_ROOT);
+ throw new ServletException("Illegal attr: " + WebConsoleConstants.ATTR_PLUGIN_ROOT);
}
String root = rawRoot.toString();
@@ -159,8 +159,8 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
final PrintWriter pw = res.getWriter();
if (pathInfo.equals("")) {
- if ( this.currentView != null ) {
- renderOverview(pw, currentView);
+ if (this.currentView != null) {
+ renderOverview(pw, currentView);
} else {
pw.println("<p class=\"statline ui-state-highlight\">No view available</p>");
pw.println("<br/>");
@@ -177,21 +177,21 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
* Render the properties page of a particular instance
*/
private void renderProperties(final PrintWriter pw, final String contextPath, final String nodeId) {
- if (logger.isDebugEnabled()) {
- logger.debug("renderProperties: nodeId=" + nodeId);
- }
+ if (logger.isDebugEnabled()) {
+ logger.debug("renderProperties: nodeId=" + nodeId);
+ }
final TopologyView tv = this.currentView;
@SuppressWarnings("unchecked")
- Set<InstanceDescription> instances = ( tv == null ? (Set<InstanceDescription>)Collections.EMPTY_SET :
-
- tv.findInstances(new InstanceFilter() {
+ Set<InstanceDescription> instances = (tv == null
+ ? (Set<InstanceDescription>) Collections.EMPTY_SET
+ : tv.findInstances(new InstanceFilter() {
@Override
public boolean accept(InstanceDescription instance) {
String slingId = instance.getSlingId();
- if (logger.isDebugEnabled()) {
- logger.debug("renderProperties/picks: slingId={}", slingId);
- }
+ if (logger.isDebugEnabled()) {
+ logger.debug("renderProperties/picks: slingId={}", slingId);
+ }
return (slingId.equals(nodeId));
}
}));
@@ -209,8 +209,9 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println("</thead>");
pw.println("<tbody>");
boolean odd = true;
- for (Iterator<Entry<String, String>> it = instance.getProperties()
- .entrySet().iterator(); it.hasNext();) {
+ for (Iterator<Entry<String, String>> it =
+ instance.getProperties().entrySet().iterator();
+ it.hasNext(); ) {
Entry<String, String> entry = it.next();
String oddEven = odd ? "odd" : "even";
odd = !odd;
@@ -236,16 +237,17 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
private void renderOverview(final PrintWriter pw, final TopologyView topology) {
pw.println("<p class=\"statline ui-state-highlight\">Configuration</p>");
pw.println("<br/>");
- pw.print("<a href=\"${appRoot}/configMgr/org.apache.sling.discovery.oak.Config\">Configure Discovery.Oak Service</a>");
+ pw.print(
+ "<a href=\"${appRoot}/configMgr/org.apache.sling.discovery.oak.Config\">Configure Discovery.Oak Service</a>");
pw.println("<br/>");
pw.println("<br/>");
final String changing;
if (!topology.isCurrent()) {
- changing = " <b><i>CHANGING!</i> (the view is no longer current!)</b>";
+ changing = " <b><i>CHANGING!</i> (the view is no longer current!)</b>";
} else {
- changing = "";
+ changing = "";
}
- pw.println("<p class=\"statline ui-state-highlight\">Topology"+changing+"</p>");
+ pw.println("<p class=\"statline ui-state-highlight\">Topology" + changing + "</p>");
pw.println("<div class=\"ui-widget-header ui-corner-top buttonGroup\" style=\"height: 15px;\">");
pw.println("<span style=\"float: left; margin-left: 1em;\">Instances in the topology</span>");
pw.println("</div>");
@@ -267,7 +269,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
boolean odd = true;
renderCluster(pw, myCluster, myCluster, odd, topology.isCurrent());
- for (Iterator<ClusterView> it = clusters.iterator(); it.hasNext();) {
+ for (Iterator<ClusterView> it = clusters.iterator(); it.hasNext(); ) {
ClusterView clusterView = it.next();
if (clusterView.equals(myCluster)) {
// skip - I already rendered that
@@ -289,8 +291,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println("<p class=\"statline ui-state-highlight\">Topology Change History</p>");
pw.println("<pre>");
- for (Iterator<String> it = topologyLog
- .iterator(); it.hasNext();) {
+ for (Iterator<String> it = topologyLog.iterator(); it.hasNext(); ) {
String aLogEntry = it.next();
pw.println(aLogEntry);
}
@@ -298,8 +299,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println("<br/>");
pw.println("<p class=\"statline ui-state-highlight\">Property Change History</p>");
pw.println("<pre>");
- for (Iterator<String> it = propertyChangeLog
- .iterator(); it.hasNext();) {
+ for (Iterator<String> it = propertyChangeLog.iterator(); it.hasNext(); ) {
String aLogEntry = it.next();
pw.println(aLogEntry);
}
@@ -327,22 +327,26 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
/**
* Render a particular cluster (into table rows)
*/
- private void renderCluster(final PrintWriter pw, final ClusterView renderCluster, final ClusterView localCluster, final boolean odd, final boolean current) {
- final Collection<Announcement> announcements = announcementRegistry.listAnnouncementsInSameCluster(localCluster);
-
- for (Iterator<InstanceDescription> it = renderCluster.getInstances()
- .iterator(); it.hasNext();) {
+ private void renderCluster(
+ final PrintWriter pw,
+ final ClusterView renderCluster,
+ final ClusterView localCluster,
+ final boolean odd,
+ final boolean current) {
+ final Collection<Announcement> announcements =
+ announcementRegistry.listAnnouncementsInSameCluster(localCluster);
+
+ for (Iterator<InstanceDescription> it = renderCluster.getInstances().iterator(); it.hasNext(); ) {
final InstanceDescription instanceDescription = it.next();
final boolean inLocalCluster = renderCluster == localCluster;
Announcement parentAnnouncement = null;
- for (Iterator<Announcement> it2 = announcements.iterator(); it2
- .hasNext();) {
+ for (Iterator<Announcement> it2 = announcements.iterator(); it2.hasNext(); ) {
Announcement announcement = it2.next();
- for (Iterator<InstanceDescription> it3 = announcement
- .listInstances().iterator(); it3.hasNext();) {
+ for (Iterator<InstanceDescription> it3 =
+ announcement.listInstances().iterator();
+ it3.hasNext(); ) {
InstanceDescription announcedInstance = it3.next();
- if (announcedInstance.getSlingId().equals(
- instanceDescription.getSlingId())) {
+ if (announcedInstance.getSlingId().equals(instanceDescription.getSlingId())) {
parentAnnouncement = announcement;
break;
}
@@ -351,7 +355,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
final String oddEven = odd ? "odd" : "even";
- if (current && (inLocalCluster || (parentAnnouncement!=null))) {
+ if (current && (inLocalCluster || (parentAnnouncement != null))) {
pw.println("<tr class=\"" + oddEven + " ui-state-default\">");
} else {
pw.println("<tr class=\"" + oddEven + " ui-state-error\">");
@@ -359,7 +363,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
final boolean isLocal = instanceDescription.isLocal();
final String slingId = instanceDescription.getSlingId();
pw.print("<td>");
- if ( isLocal) {
+ if (isLocal) {
pw.print("<b>");
}
pw.print("<a href=\"");
@@ -369,33 +373,30 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.print("\">");
pw.print(slingId);
pw.print("</a>");
- if ( isLocal) {
+ if (isLocal) {
pw.print("</b>");
}
pw.println("</td>");
pw.println("<td>"
- + (instanceDescription.getClusterView() == null ? "null"
+ + (instanceDescription.getClusterView() == null
+ ? "null"
: instanceDescription.getClusterView().getId())
+ "</td>");
pw.println("<td>" + (isLocal ? "<b>true</b>" : "false") + "</td>");
- pw.println("<td>"
- + (instanceDescription.isLeader() ? "<b>true</b>" : "false")
- + "</td>");
+ pw.println("<td>" + (instanceDescription.isLeader() ? "<b>true</b>" : "false") + "</td>");
if (inLocalCluster) {
pw.println("<td>local</td>");
pw.println("<td>n/a</td>");
} else {
pw.println("<td>remote</td>");
if (parentAnnouncement != null) {
- pw.println("<td>" + parentAnnouncement.getOwnerId()
- + "</td>");
+ pw.println("<td>" + parentAnnouncement.getOwnerId() + "</td>");
} else {
pw.println("<td><b>(changing)</b></td>");
}
}
pw.println("</tr>");
}
-
}
/**
@@ -421,12 +422,9 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println("</thead>");
pw.println("<tbody>");
- Collection<TopologyConnectorClientInformation> outgoingConnections = connectorRegistry
- .listOutgoingConnectors();
- for (Iterator<TopologyConnectorClientInformation> it = outgoingConnections
- .iterator(); it.hasNext();) {
- TopologyConnectorClientInformation topologyConnectorClient = it
- .next();
+ Collection<TopologyConnectorClientInformation> outgoingConnections = connectorRegistry.listOutgoingConnectors();
+ for (Iterator<TopologyConnectorClientInformation> it = outgoingConnections.iterator(); it.hasNext(); ) {
+ TopologyConnectorClientInformation topologyConnectorClient = it.next();
final String oddEven = odd ? "odd" : "even";
odd = !odd;
final String remoteSlingId = topologyConnectorClient.getRemoteSlingId();
@@ -438,12 +436,10 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
} else {
pw.println("<tr class=\"" + oddEven + " ui-state-error\">");
}
- pw.println("<td>"
- + topologyConnectorClient.getConnectorUrl().toString()
- + "</td>");
+ pw.println("<td>" + topologyConnectorClient.getConnectorUrl().toString() + "</td>");
if (autoStopped) {
- pw.println("<td><b>auto-stopped</b></td>");
- pw.println("<td><b>auto-stopped due to local-loop</b></td>");
+ pw.println("<td><b>auto-stopped</b></td>");
+ pw.println("<td><b>auto-stopped due to local-loop</b></td>");
} else if (isConnected && !representsLoop) {
pw.println("<td>" + remoteSlingId + "</td>");
pw.println("<td>ok, in use</td>");
@@ -454,29 +450,30 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
final int statusCode = topologyConnectorClient.getStatusCode();
final String statusDetails = topologyConnectorClient.getStatusDetails();
final String tooltipText;
- switch(statusCode) {
- case HttpServletResponse.SC_UNAUTHORIZED:
- tooltipText = HttpServletResponse.SC_UNAUTHORIZED +
- ": possible setup issue of discovery.oak on target instance, or wrong URL";
- break;
- case HttpServletResponse.SC_NOT_FOUND:
- tooltipText = HttpServletResponse.SC_NOT_FOUND +
- ": possible white list rejection by target instance";
- break;
- case -1:
- tooltipText = "-1: check error log. possible connection refused.";
- break;
- default:
- tooltipText = null;
+ switch (statusCode) {
+ case HttpServletResponse.SC_UNAUTHORIZED:
+ tooltipText = HttpServletResponse.SC_UNAUTHORIZED
+ + ": possible setup issue of discovery.oak on target instance, or wrong URL";
+ break;
+ case HttpServletResponse.SC_NOT_FOUND:
+ tooltipText =
+ HttpServletResponse.SC_NOT_FOUND + ": possible white list rejection by target instance";
+ break;
+ case -1:
+ tooltipText = "-1: check error log. possible connection refused.";
+ break;
+ default:
+ tooltipText = null;
}
- final String tooltip = tooltipText==null ? "" : (" title=\""+tooltipText+"\"");
+ final String tooltip = tooltipText == null ? "" : (" title=\"" + tooltipText + "\"");
pw.println("<td><b>not connected</b></td>");
- pw.println("<td"+tooltip+"><b>not ok (HTTP Status-Code: "+statusCode+", "+statusDetails+")</b></td>");
+ pw.println("<td" + tooltip + "><b>not ok (HTTP Status-Code: " + statusCode + ", " + statusDetails
+ + ")</b></td>");
}
- pw.println("<td>"+beautifiedTimeDiff(topologyConnectorClient.getLastPingSent())+"</td>");
- pw.println("<td>"+beautifiedDueTime(topologyConnectorClient.getNextPingDue())+"</td>");
- pw.println("<td>"+topologyConnectorClient.getLastRequestEncoding()+"</td>");
- pw.println("<td>"+topologyConnectorClient.getLastResponseEncoding()+"</td>");
+ pw.println("<td>" + beautifiedTimeDiff(topologyConnectorClient.getLastPingSent()) + "</td>");
+ pw.println("<td>" + beautifiedDueTime(topologyConnectorClient.getNextPingDue()) + "</td>");
+ pw.println("<td>" + topologyConnectorClient.getLastRequestEncoding() + "</td>");
+ pw.println("<td>" + topologyConnectorClient.getLastResponseEncoding() + "</td>");
// //TODO fallback urls are not yet implemented!
// String fallbackConnectorUrls;
// List<String> urls = topologyConnectorClient
@@ -499,37 +496,37 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
}
private String beautifiedDueTime(long secondsDue) {
- if (secondsDue<-1) {
+ if (secondsDue < -1) {
return "overdue";
- } else if (secondsDue<=0) {
+ } else if (secondsDue <= 0) {
return "now-ish";
- } else if (secondsDue==1) {
+ } else if (secondsDue == 1) {
return "in 1 second";
} else {
int minsDue = (int) (secondsDue / 60);
- if (minsDue<5) {
- return "in "+secondsDue+" seconds";
+ if (minsDue < 5) {
+ return "in " + secondsDue + " seconds";
} else {
- return "in "+minsDue+" minutes";
+ return "in " + minsDue + " minutes";
}
}
}
private String beautifiedTimeDiff(long heartbeatTime) {
final long diff = System.currentTimeMillis() - heartbeatTime;
- long seconds = (diff/1000);
- if (heartbeatTime<=0) {
+ long seconds = (diff / 1000);
+ if (heartbeatTime <= 0) {
return "n/a";
- } else if (seconds==0) {
- return diff+" millis ago";
- } else if (seconds==1) {
+ } else if (seconds == 0) {
+ return diff + " millis ago";
+ } else if (seconds == 1) {
return "1 second ago";
- } else if (seconds<300) {
+ } else if (seconds < 300) {
// then print seconds
- return seconds+" seconds ago";
+ return seconds + " seconds ago";
} else {
// then print seconds
- return (seconds/60)+" minute ago";
+ return (seconds / 60) + " minute ago";
}
}
@@ -553,8 +550,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println("<tbody>");
Collection<CachedAnnouncement> incomingConnections = announcementRegistry.listLocalIncomingAnnouncements();
- for (Iterator<CachedAnnouncement> it = incomingConnections.iterator(); it
- .hasNext();) {
+ for (Iterator<CachedAnnouncement> it = incomingConnections.iterator(); it.hasNext(); ) {
CachedAnnouncement incomingCachedAnnouncement = it.next();
Announcement incomingAnnouncement = incomingCachedAnnouncement.getAnnouncement();
String oddEven = odd ? "odd" : "even";
@@ -563,13 +559,12 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println("<tr class=\"" + oddEven + " ui-state-default\">");
pw.println("<td>" + incomingAnnouncement.getOwnerId() + "</td>");
if (incomingAnnouncement.getServerInfo() != null) {
- pw.println("<td>" + incomingAnnouncement.getServerInfo()
- + "</td>");
+ pw.println("<td>" + incomingAnnouncement.getServerInfo() + "</td>");
} else {
pw.println("<td><i>n/a</i></td>");
}
- pw.println("<td>"+beautifiedTimeDiff(incomingCachedAnnouncement.getLastPing())+"</td>");
- pw.println("<td>"+beautifiedDueTime(incomingCachedAnnouncement.getSecondsUntilTimeout())+"</td>");
+ pw.println("<td>" + beautifiedTimeDiff(incomingCachedAnnouncement.getLastPing()) + "</td>");
+ pw.println("<td>" + beautifiedDueTime(incomingCachedAnnouncement.getSecondsUntilTimeout()) + "</td>");
pw.println("</tr>");
}
@@ -617,13 +612,11 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
sb.append(".");
}
- Set<InstanceDescription> newInstances = event.getNewView()
- .getInstances();
- for (Iterator<InstanceDescription> it = newInstances.iterator(); it
- .hasNext();) {
+ Set<InstanceDescription> newInstances = event.getNewView().getInstances();
+ for (Iterator<InstanceDescription> it = newInstances.iterator(); it.hasNext(); ) {
final InstanceDescription newInstanceDescription = it.next();
- InstanceDescription oldInstanceDescription = findInstance(
- event.getOldView(), newInstanceDescription.getSlingId());
+ InstanceDescription oldInstanceDescription =
+ findInstance(event.getOldView(), newInstanceDescription.getSlingId());
if (oldInstanceDescription == null) {
logger.error("handleTopologyEvent: got a property changed but did not find instance "
+ newInstanceDescription
@@ -633,27 +626,27 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
continue;
}
- Map<String, String> oldProps = oldInstanceDescription
- .getProperties();
- Map<String, String> newProps = newInstanceDescription
- .getProperties();
+ Map<String, String> oldProps = oldInstanceDescription.getProperties();
+ Map<String, String> newProps = newInstanceDescription.getProperties();
StringBuilder diff = diff(oldProps, newProps);
if (diff.length() > 0) {
if (sb.length() != 0) {
sb.append(", ");
}
sb.append("on instance "
- + newInstanceDescription.getSlingId() + (newInstanceDescription.isLeader() ? " [isLeader]" : "")
+ + newInstanceDescription.getSlingId()
+ + (newInstanceDescription.isLeader() ? " [isLeader]" : "")
+ ": " + diff + ". ");
}
}
- addEventLog(event.getType(), "details: "+sb.toString());
+ addEventLog(event.getType(), "details: " + sb.toString());
} else if (event.getType() == Type.TOPOLOGY_INIT) {
this.currentView = event.getNewView();
StringBuilder details = new StringBuilder();
- for (Iterator<InstanceDescription> it = event.getNewView()
- .getInstances().iterator(); it.hasNext();) {
+ for (Iterator<InstanceDescription> it =
+ event.getNewView().getInstances().iterator();
+ it.hasNext(); ) {
InstanceDescription newInstance = it.next();
if (details.length() != 0) {
details.append(", ");
@@ -663,36 +656,32 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
details.append(" [isLeader]");
}
}
- addEventLog(event.getType(),
- "view: " + shortViewInfo(event.getNewView()) + ". "
- + details);
+ addEventLog(event.getType(), "view: " + shortViewInfo(event.getNewView()) + ". " + details);
} else if (event.getType() == Type.TOPOLOGY_CHANGING) {
this.currentView = event.getOldView();
- addEventLog(event.getType(),
- "old view: " + shortViewInfo(event.getOldView()));
+ addEventLog(event.getType(), "old view: " + shortViewInfo(event.getOldView()));
} else {
this.currentView = event.getNewView();
if (event.getOldView() == null) {
- addEventLog(event.getType(),
- "new view: " + shortViewInfo(event.getNewView()));
+ addEventLog(event.getType(), "new view: " + shortViewInfo(event.getNewView()));
} else {
StringBuilder details = new StringBuilder();
- for (Iterator<InstanceDescription> it = event.getNewView()
- .getInstances().iterator(); it.hasNext();) {
+ for (Iterator<InstanceDescription> it =
+ event.getNewView().getInstances().iterator();
+ it.hasNext(); ) {
InstanceDescription newInstance = it.next();
- if (findInstance(event.getOldView(),
- newInstance.getSlingId()) == null) {
+ if (findInstance(event.getOldView(), newInstance.getSlingId()) == null) {
if (details.length() != 0) {
details.append(", ");
}
details.append(newInstance.getSlingId() + " joined");
}
}
- for (Iterator<InstanceDescription> it = event.getOldView()
- .getInstances().iterator(); it.hasNext();) {
+ for (Iterator<InstanceDescription> it =
+ event.getOldView().getInstances().iterator();
+ it.hasNext(); ) {
InstanceDescription oldInstance = it.next();
- if (findInstance(event.getNewView(),
- oldInstance.getSlingId()) == null) {
+ if (findInstance(event.getNewView(), oldInstance.getSlingId()) == null) {
if (details.length() != 0) {
details.append(", ");
}
@@ -700,15 +689,15 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
}
}
final InstanceDescription li = event.getNewView().getLocalInstance();
- if (li!=null) {
+ if (li != null) {
ClusterView clusterView = li.getClusterView();
- if (clusterView!=null) {
+ if (clusterView != null) {
final InstanceDescription leader = clusterView.getLeader();
- if (leader!=null) {
- if (details.length() !=0) {
+ if (leader != null) {
+ if (details.length() != 0) {
details.append(", ");
}
- details.append("[isLeader: "+leader.getSlingId()+"]");
+ details.append("[isLeader: " + leader.getSlingId() + "]");
}
}
}
@@ -727,16 +716,14 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
/**
* find a particular instance in the topology
*/
- private InstanceDescription findInstance(final TopologyView view,
- final String slingId) {
- Set<InstanceDescription> foundInstances = view
- .findInstances(new InstanceFilter() {
+ private InstanceDescription findInstance(final TopologyView view, final String slingId) {
+ Set<InstanceDescription> foundInstances = view.findInstances(new InstanceFilter() {
- @Override
- public boolean accept(InstanceDescription instance) {
- return instance.getSlingId().equals(slingId);
- }
- });
+ @Override
+ public boolean accept(InstanceDescription instance) {
+ return instance.getSlingId().equals(slingId);
+ }
+ });
if (foundInstances.size() == 1) {
return foundInstances.iterator().next();
} else {
@@ -761,7 +748,6 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
topologyLog.remove(0);
}
}
-
}
/**
@@ -769,18 +755,17 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
*/
private synchronized void updateDiscoveryLiteHistory() {
ResourceResolver resourceResolver = null;
- try{
+ try {
resourceResolver = getResourceResolver();
- } catch(Exception e) {
- logger.error("addDiscoveryLiteHistoryEntry: Exception: "+e, e);
+ } catch (Exception e) {
+ logger.error("addDiscoveryLiteHistoryEntry: Exception: " + e, e);
return;
}
try {
- DiscoveryLiteDescriptor descriptor =
- DiscoveryLiteDescriptor.getDescriptorFrom(resourceResolver);
+ DiscoveryLiteDescriptor descriptor = DiscoveryLiteDescriptor.getDescriptorFrom(resourceResolver);
- if (lastDiscoveryLiteDescriptor!=null &&
- descriptor.getDescriptorStr().equals(lastDiscoveryLiteDescriptor.getDescriptorStr())) {
+ if (lastDiscoveryLiteDescriptor != null
+ && descriptor.getDescriptorStr().equals(lastDiscoveryLiteDescriptor.getDescriptorStr())) {
// de-duplication - then there's nothing to update
return;
}
@@ -790,7 +775,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
while (discoveryLiteHistory.size() > 12) {
discoveryLiteHistory.remove(0);
}
- } catch(Exception e) {
+ } catch (Exception e) {
// SLING-10204 : log less noisy as this can legitimately happen
logger.warn("addDiscoveryLiteHistoryEntry: got Exception (enable debug logging to see stacktrace) : " + e);
logger.debug("addDiscoveryLiteHistoryEntry: Exception stacktrace", e);
@@ -799,7 +784,6 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
resourceResolver.close();
}
}
-
}
/**
@@ -816,14 +800,13 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
/**
* calculate the difference between two sets of properties
*/
- private StringBuilder diff(final Map<String, String> oldProps,
- final Map<String, String> newProps) {
+ private StringBuilder diff(final Map<String, String> oldProps, final Map<String, String> newProps) {
final Set<String> oldKeys = new HashSet<String>(oldProps.keySet());
final Set<String> newKeys = new HashSet<String>(newProps.keySet());
StringBuilder sb = new StringBuilder();
- for (Iterator<String> it = oldKeys.iterator(); it.hasNext();) {
+ for (Iterator<String> it = oldKeys.iterator(); it.hasNext(); ) {
String oldKey = it.next();
if (newKeys.contains(oldKey)) {
if (oldProps.get(oldKey).equals(newProps.get(oldKey))) {
@@ -839,7 +822,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
}
it.remove();
}
- for (Iterator<String> it = newKeys.iterator(); it.hasNext();) {
+ for (Iterator<String> it = newKeys.iterator(); it.hasNext(); ) {
String newKey = it.next();
sb.append("(" + newKey + " was added)");
}
@@ -847,13 +830,13 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
return sb;
}
- public void printConfiguration( final PrintWriter pw ) {
+ public void printConfiguration(final PrintWriter pw) {
final TopologyView topology = this.currentView;
pw.println(TITLE);
pw.println("---------------------------------------");
pw.println();
- if ( topology == null ) {
+ if (topology == null) {
pw.println("No topology available yet!");
return;
}
@@ -868,7 +851,7 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
final ClusterView myCluster = topology.getLocalInstance().getClusterView();
printCluster(pw, myCluster, myCluster);
- for (Iterator<ClusterView> it = clusters.iterator(); it.hasNext();) {
+ for (Iterator<ClusterView> it = clusters.iterator(); it.hasNext(); ) {
ClusterView clusterView = it.next();
if (clusterView.equals(myCluster)) {
// skip - I already rendered that
@@ -880,12 +863,13 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println();
pw.println();
- final Collection<CachedAnnouncement> incomingConnections = announcementRegistry.listLocalIncomingAnnouncements();
- if ( incomingConnections.size() > 0 ) {
+ final Collection<CachedAnnouncement> incomingConnections =
+ announcementRegistry.listLocalIncomingAnnouncements();
+ if (incomingConnections.size() > 0) {
pw.println("Incoming topology connectors");
pw.println("---------------------------------------");
- for(final CachedAnnouncement incomingCachedAnnouncement : incomingConnections) {
+ for (final CachedAnnouncement incomingCachedAnnouncement : incomingConnections) {
Announcement incomingAnnouncement = incomingCachedAnnouncement.getAnnouncement();
pw.print("Owner Sling Id : ");
pw.print(incomingAnnouncement.getOwnerId());
@@ -895,8 +879,8 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.print(incomingAnnouncement.getServerInfo());
pw.println();
}
- pw.println("Last heartbeat received : "+beautifiedTimeDiff(incomingCachedAnnouncement.getLastPing()));
- pw.println("Timeout : "+beautifiedDueTime(incomingCachedAnnouncement.getSecondsUntilTimeout()));
+ pw.println("Last heartbeat received : " + beautifiedTimeDiff(incomingCachedAnnouncement.getLastPing()));
+ pw.println("Timeout : " + beautifiedDueTime(incomingCachedAnnouncement.getSecondsUntilTimeout()));
pw.println();
}
@@ -904,12 +888,13 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println();
}
- final Collection<TopologyConnectorClientInformation> outgoingConnections = connectorRegistry.listOutgoingConnectors();
- if ( outgoingConnections.size() > 0 ) {
+ final Collection<TopologyConnectorClientInformation> outgoingConnections =
+ connectorRegistry.listOutgoingConnectors();
+ if (outgoingConnections.size() > 0) {
pw.println("Outgoing topology connectors");
pw.println("---------------------------------------");
- for(final TopologyConnectorClientInformation topologyConnectorClient : outgoingConnections) {
+ for (final TopologyConnectorClientInformation topologyConnectorClient : outgoingConnections) {
final String remoteSlingId = topologyConnectorClient.getRemoteSlingId();
final boolean autoStopped = topologyConnectorClient.isAutoStopped();
final boolean isConnected = topologyConnectorClient.isConnected() && remoteSlingId != null;
@@ -932,14 +917,14 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
final int statusCode = topologyConnectorClient.getStatusCode();
final String statusDetails = topologyConnectorClient.getStatusDetails();
final String tooltipText;
- switch(statusCode) {
+ switch (statusCode) {
case HttpServletResponse.SC_UNAUTHORIZED:
- tooltipText = HttpServletResponse.SC_UNAUTHORIZED +
- ": possible setup issue of discovery.oak on target instance, or wrong URL";
+ tooltipText = HttpServletResponse.SC_UNAUTHORIZED
+ + ": possible setup issue of discovery.oak on target instance, or wrong URL";
break;
case HttpServletResponse.SC_NOT_FOUND:
- tooltipText = HttpServletResponse.SC_NOT_FOUND +
- ": possible white list rejection by target instance";
+ tooltipText = HttpServletResponse.SC_NOT_FOUND
+ + ": possible white list rejection by target instance";
break;
case -1:
tooltipText = "-1: check error log. possible connection refused.";
@@ -949,15 +934,16 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
}
pw.println("Connected to Sling Id : not connected");
pw.print("Connector status : not ok");
- if ( tooltipText != null ) {
+ if (tooltipText != null) {
pw.print(" (");
pw.print(tooltipText);
pw.print(")");
}
- pw.print(" (HTTP StatusCode: "+statusCode+", "+statusDetails+")");
+ pw.print(" (HTTP StatusCode: " + statusCode + ", " + statusDetails + ")");
pw.println();
- pw.println("Last heartbeat sent : "+beautifiedTimeDiff(topologyConnectorClient.getLastPingSent()));
- pw.println("Next heartbeat due : "+beautifiedDueTime(topologyConnectorClient.getNextPingDue()));
+ pw.println(
+ "Last heartbeat sent : " + beautifiedTimeDiff(topologyConnectorClient.getLastPingSent()));
+ pw.println("Next heartbeat due : " + beautifiedDueTime(topologyConnectorClient.getNextPingDue()));
}
pw.println();
}
@@ -965,20 +951,20 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println();
}
- if ( topologyLog.size() > 0 ) {
+ if (topologyLog.size() > 0) {
pw.println("Topology Change History");
pw.println("---------------------------------------");
- for(final String aLogEntry : topologyLog) {
+ for (final String aLogEntry : topologyLog) {
pw.println(aLogEntry);
}
pw.println();
pw.println();
}
- if ( propertyChangeLog.size() > 0 ) {
+ if (propertyChangeLog.size() > 0) {
pw.println("Property Change History");
pw.println("---------------------------------------");
- for(final String aLogEntry : propertyChangeLog) {
+ for (final String aLogEntry : propertyChangeLog) {
pw.println(aLogEntry);
}
pw.println();
@@ -1010,19 +996,19 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
* Render a particular cluster
*/
private void printCluster(final PrintWriter pw, final ClusterView renderCluster, final ClusterView localCluster) {
- final Collection<Announcement> announcements = announcementRegistry.listAnnouncementsInSameCluster(localCluster);
+ final Collection<Announcement> announcements =
+ announcementRegistry.listAnnouncementsInSameCluster(localCluster);
- for(final InstanceDescription instanceDescription : renderCluster.getInstances() ) {
+ for (final InstanceDescription instanceDescription : renderCluster.getInstances()) {
final boolean inLocalCluster = renderCluster == localCluster;
Announcement parentAnnouncement = null;
- for (Iterator<Announcement> it2 = announcements.iterator(); it2
- .hasNext();) {
+ for (Iterator<Announcement> it2 = announcements.iterator(); it2.hasNext(); ) {
Announcement announcement = it2.next();
- for (Iterator<InstanceDescription> it3 = announcement
- .listInstances().iterator(); it3.hasNext();) {
+ for (Iterator<InstanceDescription> it3 =
+ announcement.listInstances().iterator();
+ it3.hasNext(); ) {
InstanceDescription announcedInstance = it3.next();
- if (announcedInstance.getSlingId().equals(
- instanceDescription.getSlingId())) {
+ if (announcedInstance.getSlingId().equals(instanceDescription.getSlingId())) {
parentAnnouncement = announcement;
break;
}
@@ -1036,7 +1022,9 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.print(slingId);
pw.println();
pw.print("Cluster View ID : ");
- pw.print(instanceDescription.getClusterView() == null ? "null"
+ pw.print(
+ instanceDescription.getClusterView() == null
+ ? "null"
: instanceDescription.getClusterView().getId());
pw.println();
pw.print("Local instance : ");
@@ -1065,7 +1053,8 @@ public class TopologyWebConsolePlugin extends AbstractWebConsolePlugin implement
pw.println();
pw.println("Properties:");
- for(final Map.Entry<String, String> entry : instanceDescription.getProperties().entrySet()) {
+ for (final Map.Entry<String, String> entry :
+ instanceDescription.getProperties().entrySet()) {
pw.print("- ");
pw.print(entry.getKey());
pw.print(" : ");
diff --git a/src/main/java/org/apache/sling/discovery/oak/cluster/ClusterReader.java b/src/main/java/org/apache/sling/discovery/oak/cluster/ClusterReader.java
index eb7f26a..8c29d02 100644
--- a/src/main/java/org/apache/sling/discovery/oak/cluster/ClusterReader.java
+++ b/src/main/java/org/apache/sling/discovery/oak/cluster/ClusterReader.java
@@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory;
/**
* Helper class to detect instances that are only partially started.
* Partially in this context means that they have updated their
- * Oak lease but have not written the required data on the Sling
+ * Oak lease but have not written the required data on the Sling
* level (which includes the idmap, the synctoken and the leaderElectionid).
*/
public class ClusterReader {
@@ -48,7 +48,11 @@ public class ClusterReader {
private final Map<Integer, InstanceInfo> seenLocalInstances;
- public ClusterReader(ResourceResolver resourceResolver, Config config, IdMapService idMapService, Map<Integer, InstanceInfo> seenLocalInstances) {
+ public ClusterReader(
+ ResourceResolver resourceResolver,
+ Config config,
+ IdMapService idMapService,
+ Map<Integer, InstanceInfo> seenLocalInstances) {
this.resourceResolver = resourceResolver;
this.config = config;
this.idMapService = idMapService;
@@ -59,8 +63,7 @@ public class ClusterReader {
if (slingId == null) {
throw new IllegalStateException("slingId must not be null");
}
- final Resource syncTokenNode = resourceResolver
- .getResource(config.getSyncTokenPath());
+ final Resource syncTokenNode = resourceResolver.getResource(config.getSyncTokenPath());
if (syncTokenNode == null) {
return -1;
}
@@ -75,17 +78,16 @@ public class ClusterReader {
try {
return Long.parseLong(syncTokenStr);
} catch (NumberFormatException nfe) {
- logger.warn(
- "readSyncToken: unparsable (non long) syncToken: {}", syncTokenStr);
+ logger.warn("readSyncToken: unparsable (non long) syncToken: {}", syncTokenStr);
return -1;
}
}
private String readLeaderElectionId(String slingId) {
- if (slingId==null) {
+ if (slingId == null) {
throw new IllegalStateException("slingId must not be null");
}
- final String myClusterNodePath = config.getClusterInstancesPath()+"/"+slingId;
+ final String myClusterNodePath = config.getClusterInstancesPath() + "/" + slingId;
// SLING-6924 case 1 : /var/discovery/oak/clusterInstances/<slingId> can be non existant == null
final Resource myClusterNode = resourceResolver.getResource(myClusterNodePath);
if (myClusterNode == null) {
@@ -110,9 +112,10 @@ public class ClusterReader {
* @param clusterNodeId the clusterNodeId to be read
* @return the instance if it is has all required data stored (which does not
* necessarily mean it has completely started - syncToken is not checked at this stage yet)
- * @throws PersistenceException
+ * @throws PersistenceException
*/
- public InstanceReadResult readInstance(int clusterNodeId, boolean failOnMissingSyncToken, long seqNum) throws PersistenceException {
+ public InstanceReadResult readInstance(int clusterNodeId, boolean failOnMissingSyncToken, long seqNum)
+ throws PersistenceException {
final String slingId = idMapService.toSlingId(clusterNodeId, resourceResolver);
if (slingId == null) {
idMapService.clearCache();
@@ -126,19 +129,19 @@ public class ClusterReader {
final long syncToken = readSyncToken(slingId);
if (failOnMissingSyncToken && !hasSeenLocalInstance) {
if (syncToken == -1 || (seqNum != -1 && syncToken < seqNum)) {
- return InstanceReadResult.fromErrorMsg("no valid syncToken available yet for slingId=" + slingId + ", syncToken=" + syncToken);
+ return InstanceReadResult.fromErrorMsg(
+ "no valid syncToken available yet for slingId=" + slingId + ", syncToken=" + syncToken);
}
}
return InstanceReadResult.fromInstance(new InstanceInfo(clusterNodeId, slingId, syncToken, leaderElectionId));
}
- private boolean hasSeenLocalInstance(int clusterNodeId, String slingId,
- String leaderElectionId) {
+ private boolean hasSeenLocalInstance(int clusterNodeId, String slingId, String leaderElectionId) {
InstanceInfo instance = seenLocalInstances.get(clusterNodeId);
if (instance == null) {
return false;
}
- return instance.getSlingId().equals(slingId) &&
- instance.getLeaderElectionId().equals(leaderElectionId);
+ return instance.getSlingId().equals(slingId)
+ && instance.getLeaderElectionId().equals(leaderElectionId);
}
}
diff --git a/src/main/java/org/apache/sling/discovery/oak/cluster/InstanceInfo.java b/src/main/java/org/apache/sling/discovery/oak/cluster/InstanceInfo.java
index a8c6aca..c39e885 100644
--- a/src/main/java/org/apache/sling/discovery/oak/cluster/InstanceInfo.java
+++ b/src/main/java/org/apache/sling/discovery/oak/cluster/InstanceInfo.java
@@ -57,6 +57,7 @@ public class InstanceInfo {
@Override
public String toString() {
- return "an Instance[clusterNodeId = " + clusterNodeId + ", slingId = " + slingId + ", leaderElectionId = " + leaderElectionId + ", syncToken = " + syncToken + "]";
+ return "an Instance[clusterNodeId = " + clusterNodeId + ", slingId = " + slingId + ", leaderElectionId = "
+ + leaderElectionId + ", syncToken = " + syncToken + "]";
}
}
diff --git a/src/main/java/org/apache/sling/discovery/oak/cluster/OakClusterViewService.java b/src/main/java/org/apache/sling/discovery/oak/cluster/OakClusterViewService.java
index ac0e7d2..94894e8 100644
--- a/src/main/java/org/apache/sling/discovery/oak/cluster/OakClusterViewService.java
+++ b/src/main/java/org/apache/sling/discovery/oak/cluster/OakClusterViewService.java
@@ -60,9 +60,9 @@ import org.slf4j.LoggerFactory;
/**
* Oak-based implementation of the ClusterViewService interface.
*/
-@Component (service = ClusterViewService.class)
+@Component(service = ClusterViewService.class)
public class OakClusterViewService implements ClusterViewService {
-
+
private static final String PROPERTY_CLUSTER_ID = "clusterId";
private static final String PROPERTY_CLUSTER_ID_DEFINED_AT = "clusterIdDefinedAt";
private static final String PROPERTY_CLUSTER_ID_DEFINED_BY = "clusterIdDefinedBy";
@@ -94,11 +94,12 @@ public class OakClusterViewService implements ClusterViewService {
* Keeps track of which id existed in the local cluster - to avoid suppressing those.
* Note that discovery clusters aren't usually terribly big - so this map shouldn't grow too large ever.
**/
- private Map<Integer,InstanceInfo> seenLocalInstances = new HashMap<>();
+ private Map<Integer, InstanceInfo> seenLocalInstances = new HashMap<>();
private final LogSilencer logSilencer = new LogSilencer(logger);
- public static OakClusterViewService testConstructor(SlingSettingsService settingsService,
+ public static OakClusterViewService testConstructor(
+ SlingSettingsService settingsService,
ResourceResolverFactory resourceResolverFactory,
IdMapService idMapService,
Config config) {
@@ -113,15 +114,16 @@ public class OakClusterViewService implements ClusterViewService {
@Activate
public void activate() {
- final String suppressPartiallyStartedInstances = config == null ? "unknown" : String.valueOf(config.getSuppressPartiallyStartedInstances());
+ final String suppressPartiallyStartedInstances =
+ config == null ? "unknown" : String.valueOf(config.getSuppressPartiallyStartedInstances());
logger.info("activate: suppressPartiallyStartedInstances = " + suppressPartiallyStartedInstances);
}
@Override
public String getSlingId() {
- if (settingsService==null) {
- return null;
- }
+ if (settingsService == null) {
+ return null;
+ }
return settingsService.getSlingId();
}
@@ -135,30 +137,32 @@ public class OakClusterViewService implements ClusterViewService {
ResourceResolver resourceResolver = null;
try {
DiscoveryLiteDescriptor descriptor = null;
- try{
+ try {
resourceResolver = getResourceResolver();
descriptor = DiscoveryLiteDescriptor.getDescriptorFrom(resourceResolver);
} catch (Exception e) {
// SLING-10204 : log less noisy as this can legitimately happen
logger.warn("getLocalClusterView: got Exception (enable debug logging to see stacktrace) : " + e);
logger.debug("getLocalClusterView: Exception stacktrace", e);
- throw new UndefinedClusterViewException(Reason.REPOSITORY_EXCEPTION, "Exception while processing descriptor: "+e);
+ throw new UndefinedClusterViewException(
+ Reason.REPOSITORY_EXCEPTION, "Exception while processing descriptor: " + e);
}
- if (lastSeqNum!=descriptor.getSeqNum()) {
+ if (lastSeqNum != descriptor.getSeqNum()) {
logger.info("getLocalClusterView: sequence number change detected - clearing idmap cache");
idMapService.clearCache();
lastSeqNum = descriptor.getSeqNum();
}
return asClusterView(descriptor, resourceResolver);
} catch (UndefinedClusterViewException e) {
- logger.info("getLocalClusterView: undefined clusterView: "+e.getReason()+" - "+e.getMessage());
+ logger.info("getLocalClusterView: undefined clusterView: " + e.getReason() + " - " + e.getMessage());
throw e;
} catch (Exception e) {
- logger.error("getLocalClusterView: repository exception: "+e, e);
- throw new UndefinedClusterViewException(Reason.REPOSITORY_EXCEPTION, "Exception while processing descriptor: "+e);
+ logger.error("getLocalClusterView: repository exception: " + e, e);
+ throw new UndefinedClusterViewException(
+ Reason.REPOSITORY_EXCEPTION, "Exception while processing descriptor: " + e);
} finally {
logger.trace("getLocalClusterView: end");
- if (resourceResolver!=null) {
+ if (resourceResolver != null) {
resourceResolver.close();
}
}
@@ -172,11 +176,12 @@ public class OakClusterViewService implements ClusterViewService {
return config != null && config.getSuppressPartiallyStartedInstances();
}
- private LocalClusterView asClusterView(DiscoveryLiteDescriptor descriptor, ResourceResolver resourceResolver) throws Exception {
+ private LocalClusterView asClusterView(DiscoveryLiteDescriptor descriptor, ResourceResolver resourceResolver)
+ throws Exception {
if (descriptor == null) {
throw new IllegalArgumentException("descriptor must not be null");
}
- if (resourceResolver==null) {
+ if (resourceResolver == null) {
throw new IllegalArgumentException("resourceResolver must not be null");
}
logger.trace("asClusterView: start");
@@ -186,25 +191,27 @@ public class OakClusterViewService implements ClusterViewService {
clusterViewId = readOrDefineClusterId(resourceResolver);
}
final long seqNum = descriptor.getSeqNum();
- String localClusterSyncTokenId = /*descriptor.getViewId()+"_"+*/String.valueOf(seqNum);
+ String localClusterSyncTokenId = /*descriptor.getViewId()+"_"+*/ String.valueOf(seqNum);
if (!descriptor.isFinal()) {
- throw new UndefinedClusterViewException(Reason.NO_ESTABLISHED_VIEW, "descriptor is not yet final: "+descriptor);
+ throw new UndefinedClusterViewException(
+ Reason.NO_ESTABLISHED_VIEW, "descriptor is not yet final: " + descriptor);
}
LocalClusterView cluster = new LocalClusterView(clusterViewId, localClusterSyncTokenId);
int me = descriptor.getMyId();
int[] activeIds = descriptor.getActiveIds();
- if (activeIds==null || activeIds.length==0) {
- throw new UndefinedClusterViewException(Reason.NO_ESTABLISHED_VIEW, "Descriptor contained no active ids: "+descriptor.getDescriptorStr());
+ if (activeIds == null || activeIds.length == 0) {
+ throw new UndefinedClusterViewException(
+ Reason.NO_ESTABLISHED_VIEW, "Descriptor contained no active ids: " + descriptor.getDescriptorStr());
}
- final List<Integer> activeIdsList = Arrays.stream( activeIds ).boxed().collect( Collectors.toList() );
+ final List<Integer> activeIdsList = Arrays.stream(activeIds).boxed().collect(Collectors.toList());
// step 1: sort activeIds by their leaderElectionId
// serves two purposes: pos[0] is then leader
// and the rest are properly sorted within the cluster
final ClusterReader reader = new ClusterReader(resourceResolver, config, idMapService, seenLocalInstances);
- final Map<Integer,InstanceInfo> regularInstances = new HashMap<>();
+ final Map<Integer, InstanceInfo> regularInstances = new HashMap<>();
final Set<Integer> partiallyStartedClusterNodeIds = new HashSet<>();
boolean suppressionEnabled = isSyncTokenEnabled() && isPartialSuppressionEnabled();
@@ -214,8 +221,7 @@ public class OakClusterViewService implements ClusterViewService {
throw new UndefinedClusterViewException(Reason.NO_ESTABLISHED_VIEW, myInstanceResult.getErrorMsg());
}
- if (partialStartupSuppressingTimeout > 0
- && partialStartupSuppressingTimeout < System.currentTimeMillis()) {
+ if (partialStartupSuppressingTimeout > 0 && partialStartupSuppressingTimeout < System.currentTimeMillis()) {
// if partial suppression timeout is set and it has passed, then don't suppress
suppressionEnabled = false;
}
@@ -267,21 +273,21 @@ public class OakClusterViewService implements ClusterViewService {
final List<Integer> sortedIds = leaderElectionSort(regularInstances);
if (sortedIds.size() != activeIdsList.size()) {
- logger.error("asClusterView : list size mismatch : sorted = " + sortedIds.size()
- + ", active = " + activeIdsList.size() + " (partial = " + partiallyStartedClusterNodeIds.size() + ")");
+ logger.error("asClusterView : list size mismatch : sorted = " + sortedIds.size() + ", active = "
+ + activeIdsList.size() + " (partial = " + partiallyStartedClusterNodeIds.size() + ")");
}
boolean seenAllSyncTokens = true;
- for(int i=0; i<sortedIds.size(); i++) {
+ for (int i = 0; i < sortedIds.size(); i++) {
int id = sortedIds.get(i);
- boolean isLeader = i==0; // thx to sorting above [0] is leader indeed
- boolean isOwn = id==me;
+ boolean isLeader = i == 0; // thx to sorting above [0] is leader indeed
+ boolean isOwn = id == me;
InstanceInfo in = regularInstances.get(id);
String slingId = in == null ? null : in.getSlingId();
if (slingId == null) {
idMapService.clearCache();
logger.info("asClusterView: cannot resolve oak-clusterNodeId {} to a slingId", id);
- throw new Exception("Cannot resolve oak-clusterNodeId "+id+" to a slingId");
+ throw new Exception("Cannot resolve oak-clusterNodeId " + id + " to a slingId");
}
if (!in.isSyncTokenNewerOrEqual(seqNum)) {
logSilencer.infoOrDebug("Not seen syncToken (" + seqNum + ") of this instance yet : " + in);
@@ -299,8 +305,8 @@ public class OakClusterViewService implements ClusterViewService {
idMapService.clearCache();
}
if (!partiallyStartedClusterNodeIds.isEmpty()) {
- logSilencer.infoOrDebug("asClusterView : adding as partially started slingIds: clusterNodeIds = " +
- partiallyStartedClusterNodeIds);
+ logSilencer.infoOrDebug("asClusterView : adding as partially started slingIds: clusterNodeIds = "
+ + partiallyStartedClusterNodeIds);
cluster.setPartiallyStartedClusterNodeIds(partiallyStartedClusterNodeIds);
} else {
logSilencer.reset();
@@ -309,12 +315,14 @@ public class OakClusterViewService implements ClusterViewService {
logger.trace("asClusterView: returning {}", cluster);
InstanceDescription local = cluster.getLocalInstance();
if (local == null) {
- logger.info("getClusterView: the local instance ("+getSlingId()+") is currently not included in the existing established view! "
- + "This is normal at startup. At other times is pseudo-network-partitioning is an indicator for repository/network-delays or clocks-out-of-sync (SLING-3432). "
- + "(increasing the heartbeatTimeout can help as a workaround too) "
- + "The local instance will stay in TOPOLOGY_CHANGING or pre _INIT mode until a new vote was successful.");
- throw new UndefinedClusterViewException(Reason.ISOLATED_FROM_TOPOLOGY,
- "established view does not include local instance - isolated");
+ logger.info(
+ "getClusterView: the local instance (" + getSlingId()
+ + ") is currently not included in the existing established view! "
+ + "This is normal at startup. At other times is pseudo-network-partitioning is an indicator for repository/network-delays or clocks-out-of-sync (SLING-3432). "
+ + "(increasing the heartbeatTimeout can help as a workaround too) "
+ + "The local instance will stay in TOPOLOGY_CHANGING or pre _INIT mode until a new vote was successful.");
+ throw new UndefinedClusterViewException(
+ Reason.ISOLATED_FROM_TOPOLOGY, "established view does not include local instance - isolated");
}
if (lowestSeqNum == -1) {
// this starts partialStartup suppression (if all other conditions met)
@@ -345,8 +353,7 @@ public class OakClusterViewService implements ClusterViewService {
if (suppressionTimeoutSeconds <= 0) {
partialStartupSuppressingTimeout = 0;
} else {
- partialStartupSuppressingTimeout = System.currentTimeMillis()
- + (suppressionTimeoutSeconds * 1000);
+ partialStartupSuppressingTimeout = System.currentTimeMillis() + (suppressionTimeoutSeconds * 1000);
}
}
}
@@ -368,16 +375,16 @@ public class OakClusterViewService implements ClusterViewService {
if (config.isInvertLeaderElectionPrefixOrder()) {
// SLING-7830 : inverted leaderElectionPrefix sorting
comparator = new Comparator<Integer>() {
-
+
private long prefixOf(String leaderElectionId) {
final int underScore = leaderElectionId.indexOf("_");
if (underScore == -1) {
return -1;
}
final String prefixStr = leaderElectionId.substring(0, underScore);
- try{
+ try {
return Long.parseLong(prefixStr);
- } catch(Exception e) {
+ } catch (Exception e) {
return -1;
}
}
@@ -401,22 +408,19 @@ public class OakClusterViewService implements ClusterViewService {
// _0000001534409616936_374019fc-68bd-4c8d-a4cf-8ee8b07c63bc
// notALong_0000001534409616936_374019fc-68bd-4c8d-a4cf-8ee8b07c63bc
// so all of the above three get compared the classic way
- return leaderElectionId0
- .compareTo(leaderElectionId1);
+ return leaderElectionId0.compareTo(leaderElectionId1);
} else {
// inverted order comparison:
return Long.valueOf(prefix1).compareTo(prefix0);
}
}
-
};
} else {
comparator = new Comparator<Integer>() {
-
+
@Override
public int compare(Integer arg0, Integer arg1) {
- return leaderElectionIds.get(arg0)
- .compareTo(leaderElectionIds.get(arg1));
+ return leaderElectionIds.get(arg0).compareTo(leaderElectionIds.get(arg1));
}
};
}
@@ -434,7 +438,7 @@ public class OakClusterViewService implements ClusterViewService {
* under /var/discovery/oak (and to account for odd/edgy cases we'll do a
* retry when storing the id, in case we'd run into conflicts, even though
* they should not occur in singleVM cases)
- *
+ *
* @param resourceResolver the ResourceResolver with which to read or write
* the clusterId properties under /var/discovery/oak
* @return the clusterId to be used - either the one read or defined
@@ -443,23 +447,23 @@ public class OakClusterViewService implements ClusterViewService {
* accessed or auto-created
*/
private String readOrDefineClusterId(ResourceResolver resourceResolver) throws PersistenceException {
- //TODO: if Config gets a specific, public getDiscoveryResourcePath, this can be simplified:
+ // TODO: if Config gets a specific, public getDiscoveryResourcePath, this can be simplified:
final String clusterInstancesPath = config.getClusterInstancesPath();
- final String discoveryResourcePath = clusterInstancesPath.substring(0,
- clusterInstancesPath.lastIndexOf("/", clusterInstancesPath.length()-2));
+ final String discoveryResourcePath = clusterInstancesPath.substring(
+ 0, clusterInstancesPath.lastIndexOf("/", clusterInstancesPath.length() - 2));
final int MAX_RETRIES = 5;
- for(int retryCnt=0; retryCnt<MAX_RETRIES; retryCnt++) {
+ for (int retryCnt = 0; retryCnt < MAX_RETRIES; retryCnt++) {
Resource varDiscoveryOak = resourceResolver.getResource(discoveryResourcePath);
if (varDiscoveryOak == null) {
varDiscoveryOak = ResourceHelper.getOrCreateResource(resourceResolver, discoveryResourcePath);
}
if (varDiscoveryOak == null) {
- logger.error("readOrDefinedClusterId: Could not create: "+discoveryResourcePath);
+ logger.error("readOrDefinedClusterId: Could not create: " + discoveryResourcePath);
throw new RuntimeException("could not create " + discoveryResourcePath);
}
ModifiableValueMap props = varDiscoveryOak.adaptTo(ModifiableValueMap.class);
if (props == null) {
- logger.error("readOrDefineClusterId: Could not adaptTo ModifiableValueMap: "+varDiscoveryOak);
+ logger.error("readOrDefineClusterId: Could not adaptTo ModifiableValueMap: " + varDiscoveryOak);
throw new RuntimeException("could not adaptTo ModifiableValueMap: " + varDiscoveryOak);
}
Object clusterIdObj = props.get(PROPERTY_CLUSTER_ID);
@@ -479,12 +483,14 @@ public class OakClusterViewService implements ClusterViewService {
resourceResolver.commit();
return newClusterId;
} catch (PersistenceException e) {
- logger.warn("readOrDefineClusterId: could not persist clusterId "
- + "(retrying in 1 sec max " + (MAX_RETRIES - retryCnt - 1) + " more times: " + e, e);
+ logger.warn(
+ "readOrDefineClusterId: could not persist clusterId " + "(retrying in 1 sec max "
+ + (MAX_RETRIES - retryCnt - 1) + " more times: " + e,
+ e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
- logger.warn("readOrDefineClusterId: got interrupted: "+e1, e1);
+ logger.warn("readOrDefineClusterId: got interrupted: " + e1, e1);
}
logger.info("readOrDefineClusterId: retrying now.");
}
@@ -500,8 +506,7 @@ public class OakClusterViewService implements ClusterViewService {
if (propertiesChild != null) {
final ValueMap properties = propertiesChild.adaptTo(ValueMap.class);
if (properties != null) {
- for (Iterator<String> it = properties.keySet().iterator(); it
- .hasNext();) {
+ for (Iterator<String> it = properties.keySet().iterator(); it.hasNext(); ) {
String key = it.next();
if (!key.equals("jcr:primaryType")) {
props.put(key, properties.get(key, String.class));
@@ -512,5 +517,4 @@ public class OakClusterViewService implements ClusterViewService {
}
return props;
}
-
}
diff --git a/src/main/java/org/apache/sling/discovery/oak/pinger/OakViewChecker.java b/src/main/java/org/apache/sling/discovery/oak/pinger/OakViewChecker.java
index f7bbe1c..416000e 100644
--- a/src/main/java/org/apache/sling/discovery/oak/pinger/OakViewChecker.java
+++ b/src/main/java/org/apache/sling/discovery/oak/pinger/OakViewChecker.java
@@ -53,12 +53,14 @@ import org.osgi.service.http.HttpService;
* Remote heartbeats are POSTs to remote TopologyConnectorServlets using
* discovery.base
*/
-@Component(service = OakViewChecker.class,
+@Component(
+ service = OakViewChecker.class,
reference = {
- @Reference(name = "HttpService",
- service = HttpService.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ name = "HttpService",
+ service = HttpService.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
})
public class OakViewChecker extends BaseViewChecker {
@@ -162,8 +164,8 @@ public class OakViewChecker extends BaseViewChecker {
*/
public void initialize(final OakDiscoveryService discoveryService) {
logger.info("initialize: initializing.");
- synchronized(lock) {
- this.discoveryService = discoveryService;
+ synchronized (lock) {
+ this.discoveryService = discoveryService;
issueHeartbeat();
}
@@ -171,8 +173,9 @@ public class OakViewChecker extends BaseViewChecker {
// connector pings and checks the connector/topology view
try {
final long interval = config.getConnectorPingInterval();
- logger.info("initialize: starting periodic connectorPing job for "+slingId+" with interval "+interval+" sec.");
- periodicPingJob = new PeriodicBackgroundJob(interval, NAME+".connectorPinger", this);
+ logger.info("initialize: starting periodic connectorPing job for " + slingId + " with interval " + interval
+ + " sec.");
+ periodicPingJob = new PeriodicBackgroundJob(interval, NAME + ".connectorPinger", this);
} catch (Exception e) {
logger.error("activate: Could not start heartbeat runner: " + e, e);
}
@@ -184,16 +187,16 @@ public class OakViewChecker extends BaseViewChecker {
// the value and only updates it on change, so reading is very cheap)
// and because doing this more frequently means that the
// reaction time is faster
- try{
+ try {
final long interval = config.getDiscoveryLiteCheckInterval();
- logger.info("initialize: starting periodic discoveryLiteCheck job for "+slingId+" with interval "+interval+" sec.");
- periodicCheckViewJob = new PeriodicBackgroundJob(interval, NAME+".discoveryLiteCheck", new Runnable() {
+ logger.info("initialize: starting periodic discoveryLiteCheck job for " + slingId + " with interval "
+ + interval + " sec.");
+ periodicCheckViewJob = new PeriodicBackgroundJob(interval, NAME + ".discoveryLiteCheck", new Runnable() {
@Override
public void run() {
discoveryLiteCheck();
}
-
});
} catch (Exception e) {
logger.error("activate: Could not start heartbeat runner: " + e, e);
@@ -201,8 +204,8 @@ public class OakViewChecker extends BaseViewChecker {
}
private void discoveryLiteCheck() {
- logger.debug("discoveryLiteCheck: start. [for slingId="+slingId+"]");
- synchronized(lock) {
+ logger.debug("discoveryLiteCheck: start. [for slingId=" + slingId + "]");
+ synchronized (lock) {
if (!activated) {
// SLING:2895: avoid checks if not activated
logger.debug("discoveryLiteCheck: not activated yet");
@@ -217,7 +220,7 @@ public class OakViewChecker extends BaseViewChecker {
// filter out the 99.99% of unchanged cases.
discoveryService.checkForTopologyChange();
}
- logger.debug("discoveryLiteCheck: end. [for slingId="+slingId+"]");
+ logger.debug("discoveryLiteCheck: end. [for slingId=" + slingId + "]");
}
/** Get or create a ResourceResolver **/
@@ -243,17 +246,17 @@ public class OakViewChecker extends BaseViewChecker {
*/
public boolean resetLeaderElectionId() {
ResourceResolver resourceResolver = null;
- try{
+ try {
final String myClusterNodePath = getLocalClusterNodePath();
resourceResolver = getResourceResolver();
- if (resourceResolver==null) {
- logger.warn("resetLeaderElectionId: could not login, new leaderElectionId will be calculated upon next heartbeat only!");
+ if (resourceResolver == null) {
+ logger.warn(
+ "resetLeaderElectionId: could not login, new leaderElectionId will be calculated upon next heartbeat only!");
return false;
}
String newLeaderElectionId = newLeaderElectionId();
- final Resource resource = ResourceHelper.getOrCreateResource(
- resourceResolver, myClusterNodePath);
+ final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, myClusterNodePath);
final ModifiableValueMap resourceMap = resource.adaptTo(ModifiableValueMap.class);
resourceMap.put(PROPERTY_ID_RUNTIME, runtimeId);
@@ -270,15 +273,18 @@ public class OakViewChecker extends BaseViewChecker {
resourceMap.put("leaderElectionId", newLeaderElectionId);
resourceMap.put("leaderElectionIdCreatedAt", leaderElectionCreatedAt);
- logger.info("resetLeaderElectionId: storing my runtimeId: {}, endpoints: {}, sling home path: {}, new leaderElectionId: {}, created at: {}",
- new Object[]{runtimeId, endpointsAsString, slingHomePath, newLeaderElectionId, leaderElectionCreatedAt});
+ logger.info(
+ "resetLeaderElectionId: storing my runtimeId: {}, endpoints: {}, sling home path: {}, new leaderElectionId: {}, created at: {}",
+ new Object[] {
+ runtimeId, endpointsAsString, slingHomePath, newLeaderElectionId, leaderElectionCreatedAt
+ });
resourceResolver.commit();
} catch (LoginException e) {
- logger.error("resetLeaderElectionid: could not login: "+e, e);
+ logger.error("resetLeaderElectionid: could not login: " + e, e);
} catch (PersistenceException e) {
- logger.error("resetLeaderElectionid: got PersistenceException: "+e, e);
+ logger.error("resetLeaderElectionid: got PersistenceException: " + e, e);
} finally {
- if (resourceResolver!=null) {
+ if (resourceResolver != null) {
resourceResolver.close();
}
}
@@ -290,13 +296,11 @@ public class OakViewChecker extends BaseViewChecker {
*/
private String newLeaderElectionId() {
int maxLongLength = String.valueOf(Long.MAX_VALUE).length();
- String currentTimeMillisStr = String.format("%0"
- + maxLongLength + "d", System.currentTimeMillis());
+ String currentTimeMillisStr = String.format("%0" + maxLongLength + "d", System.currentTimeMillis());
String prefix = String.valueOf(config.getLeaderElectionPrefix());
- final String newLeaderElectionId = prefix + "_"
- + currentTimeMillisStr + "_" + slingId;
+ final String newLeaderElectionId = prefix + "_" + currentTimeMillisStr + "_" + slingId;
return newLeaderElectionId;
}
@@ -317,11 +321,12 @@ public class OakViewChecker extends BaseViewChecker {
if (discoveryService == null) {
// SLING-6065: it's legitimate that updateProperties()
// (which comes from BaseViewChecker.issueHeartbeat())
- // is called while discoveryService is not yet set. That's
+ // is called while discoveryService is not yet set. That's
// due to the fact that discoveryService is set in initialize()
// which is called once the OakDiscoveryService is activated
// and that can come at a later point.
} else {
discoveryService.updateProperties();
}
- }}
+ }
+}
diff --git a/src/test/java/org/apache/sling/discovery/base/commons/OakViewCheckerFactory.java b/src/test/java/org/apache/sling/discovery/base/commons/OakViewCheckerFactory.java
index 2a962ea..e38ae12 100644
--- a/src/test/java/org/apache/sling/discovery/base/commons/OakViewCheckerFactory.java
+++ b/src/test/java/org/apache/sling/discovery/base/commons/OakViewCheckerFactory.java
@@ -25,8 +25,10 @@ import org.apache.sling.settings.SlingSettingsService;
public class OakViewCheckerFactory {
- public static OakViewChecker createOakViewChecker(SlingSettingsService settingsService, ResourceResolverFactory resourceResolverFactory, Config config) {
- OakViewChecker viewChecker = OakViewChecker.testConstructor(settingsService, resourceResolverFactory, null, null, null, config);
+ public static OakViewChecker createOakViewChecker(
+ SlingSettingsService settingsService, ResourceResolverFactory resourceResolverFactory, Config config) {
+ OakViewChecker viewChecker =
+ OakViewChecker.testConstructor(settingsService, resourceResolverFactory, null, null, null, config);
viewChecker.activate(null);
return viewChecker;
}
diff --git a/src/test/java/org/apache/sling/discovery/oak/ConfigTest.java b/src/test/java/org/apache/sling/discovery/oak/ConfigTest.java
index f3f1d39..bd59ae2 100644
--- a/src/test/java/org/apache/sling/discovery/oak/ConfigTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/ConfigTest.java
@@ -18,26 +18,26 @@
*/
package org.apache.sling.discovery.oak;
+import java.util.Dictionary;
+import java.util.Hashtable;
+
import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import java.util.Dictionary;
-import java.util.Hashtable;
-
+import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_BACKOFF_STABLE_FACTOR;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_BACKOFF_STANDBY_FACTOR;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_CLUSTER_SYNC_SERVICE_INTERVAL;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_CLUSTER_SYNC_SERVICE_TIMEOUT;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL;
-import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL;
-import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT;
-import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_BACKOFF_STABLE_FACTOR;
+import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_JOINER_DELAY_SECONDS;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_MIN_EVENT_DELAY;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_SOCKET_CONNECT_TIMEOUT;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_SO_TIMEOUT;
import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_SUPPRESSION_TIMEOUT_SECONDS;
-import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_JOINER_DELAY_SECONDS;
+import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL;
+import static org.apache.sling.discovery.oak.DiscoveryServiceCentralConfig.DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -145,4 +145,4 @@ public class ConfigTest {
config = context.registerInjectActivateService(new Config(), properties);
assertEquals(17 * 1000, config.getJoinerDelayMillis());
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/discovery/oak/JoinerDelayTest.java b/src/test/java/org/apache/sling/discovery/oak/JoinerDelayTest.java
index e355310..248ee18 100644
--- a/src/test/java/org/apache/sling/discovery/oak/JoinerDelayTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/JoinerDelayTest.java
@@ -18,10 +18,6 @@
*/
package org.apache.sling.discovery.oak;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
@@ -34,6 +30,8 @@ import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
+import com.google.common.io.Closer;
+import junitx.util.PrivateAccessor;
import org.apache.sling.commons.scheduler.Scheduler;
import org.apache.sling.commons.scheduler.impl.QuartzScheduler;
import org.apache.sling.commons.scheduler.impl.SchedulerServiceFactory;
@@ -53,15 +51,16 @@ import org.junit.runners.Parameterized;
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
-import com.google.common.io.Closer;
-
-import junitx.util.PrivateAccessor;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class JoinerDelayTest {
private static enum SchedulerType {
- REAL, DUMMY
+ REAL,
+ DUMMY
}
private final SchedulerType schedulerType;
@@ -75,11 +74,13 @@ public class JoinerDelayTest {
private Scheduler createRealScheduler() throws Throwable {
final BundleContext ctx = Mockito.mock(BundleContext.class);
final Map<String, Object> props = new HashMap<>();
- final DefaultThreadPoolManager threadPoolManager = new DefaultThreadPoolManager(ctx, new Hashtable<String, Object>());
+ final DefaultThreadPoolManager threadPoolManager =
+ new DefaultThreadPoolManager(ctx, new Hashtable<String, Object>());
final QuartzScheduler qScheduler = new QuartzScheduler();
Scheduler scheduler = new SchedulerServiceFactory();
PrivateAccessor.setField(qScheduler, "threadPoolManager", threadPoolManager);
- PrivateAccessor.invoke(qScheduler, "activate", new Class[] {BundleContext.class, Map.class}, new Object[] {ctx, props});
+ PrivateAccessor.invoke(
+ qScheduler, "activate", new Class[] {BundleContext.class, Map.class}, new Object[] {ctx, props});
PrivateAccessor.setField(scheduler, "scheduler", qScheduler);
closer.register(new Closeable() {
@@ -87,12 +88,12 @@ public class JoinerDelayTest {
@Override
public void close() throws IOException {
try {
- PrivateAccessor.invoke(qScheduler, "deactivate", new Class[] {BundleContext.class}, new Object[] {ctx});
+ PrivateAccessor.invoke(
+ qScheduler, "deactivate", new Class[] {BundleContext.class}, new Object[] {ctx});
} catch (Throwable e) {
throw new IOException(e);
}
}
-
});
return scheduler;
@@ -102,7 +103,7 @@ public class JoinerDelayTest {
return new DummyScheduler(true);
}
- @Parameterized.Parameters(name="{0}")
+ @Parameterized.Parameters(name = "{0}")
public static Collection<SchedulerType> schedulerTypes() {
Collection<SchedulerType> result = new ArrayList<>();
result.add(SchedulerType.REAL);
@@ -117,18 +118,18 @@ public class JoinerDelayTest {
@Before
public void setup() throws Throwable {
closer = Closer.create();
- switch(schedulerType) {
- case REAL : {
- scheduler = createRealScheduler();
- break;
- }
- case DUMMY : {
- scheduler = createDummyScheduler();
- break;
- }
- default: {
- fail("unknown schedulerType : " + schedulerType);
- }
+ switch (schedulerType) {
+ case REAL: {
+ scheduler = createRealScheduler();
+ break;
+ }
+ case DUMMY: {
+ scheduler = createDummyScheduler();
+ break;
+ }
+ default: {
+ fail("unknown schedulerType : " + schedulerType);
+ }
}
DefaultClusterView cluster = new DefaultClusterView(UUID.randomUUID().toString());
view = new DummyTopologyView()
@@ -141,7 +142,6 @@ public class JoinerDelayTest {
public void run() {
callbackSemaphore.release();
}
-
};
}
@@ -163,14 +163,14 @@ public class JoinerDelayTest {
try {
joinerDelay.sync(null, null);
fail("should fail");
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
joinerDelay = new JoinerDelay(1, scheduler);
try {
joinerDelay.sync(view, null);
fail("should fail");
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
joinerDelay = new JoinerDelay(1, scheduler);
@@ -178,7 +178,7 @@ public class JoinerDelayTest {
try {
joinerDelay.sync(null, callback);
fail("should fail");
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
@@ -186,14 +186,14 @@ public class JoinerDelayTest {
try {
joinerDelay.sync(null, null);
fail("should fail");
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
joinerDelay = new JoinerDelay(-1, scheduler);
try {
joinerDelay.sync(view, null);
fail("should fail");
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
joinerDelay = new JoinerDelay(-1, scheduler);
@@ -201,7 +201,7 @@ public class JoinerDelayTest {
try {
joinerDelay.sync(null, callback);
fail("should fail");
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
}
@@ -260,7 +260,7 @@ public class JoinerDelayTest {
public void doTestSync_withDelayAndReSync(int repeats, boolean cancels) throws Exception {
JoinerDelay joinerDelay = new JoinerDelay(1000, scheduler);
- for(int i=0; i<repeats; i++) {
+ for (int i = 0; i < repeats; i++) {
if (cancels) {
joinerDelay.cancelSync();
}
@@ -288,8 +288,7 @@ public class JoinerDelayTest {
@Test
public void testSingleStartup() throws Exception {
DefaultClusterView cluster = new DefaultClusterView(UUID.randomUUID().toString());
- view = new DummyTopologyView()
- .addInstance(UUID.randomUUID().toString(), cluster, true, true);
+ view = new DummyTopologyView().addInstance(UUID.randomUUID().toString(), cluster, true, true);
JoinerDelay joinerDelay = new JoinerDelay(2000, scheduler);
joinerDelay.sync(view, callback);
assertTrue(callbackSemaphore.tryAcquire());
@@ -298,8 +297,7 @@ public class JoinerDelayTest {
@Test
public void testPartialJoin() throws Exception {
final LocalClusterView cluster = new LocalClusterView(UUID.randomUUID().toString(), "any");
- view = new DummyTopologyView()
- .addInstance(UUID.randomUUID().toString(), cluster, true, true);
+ view = new DummyTopologyView().addInstance(UUID.randomUUID().toString(), cluster, true, true);
cluster.setPartiallyStartedClusterNodeIds(Arrays.asList(2));
JoinerDelay joinerDelay = new JoinerDelay(2000, scheduler);
diff --git a/src/test/java/org/apache/sling/discovery/oak/Log4jErrorCatcher.java b/src/test/java/org/apache/sling/discovery/oak/Log4jErrorCatcher.java
index 8b4aa51..e4bd508 100644
--- a/src/test/java/org/apache/sling/discovery/oak/Log4jErrorCatcher.java
+++ b/src/test/java/org/apache/sling/discovery/oak/Log4jErrorCatcher.java
@@ -38,7 +38,6 @@ public class Log4jErrorCatcher extends AppenderSkeleton {
final Log4jErrorCatcher catcher = new Log4jErrorCatcher(className);
LogManager.getLogger(className).addAppender(catcher);
return catcher;
-
}
private final AtomicReference<String> lastErrorMsg = new AtomicReference<>();
@@ -49,9 +48,7 @@ public class Log4jErrorCatcher extends AppenderSkeleton {
}
@Override
- public void close() {
-
- }
+ public void close() {}
@Override
protected void append(LoggingEvent event) {
@@ -72,4 +69,4 @@ public class Log4jErrorCatcher extends AppenderSkeleton {
public void uninstall() {
LogManager.getLogger(className).removeAppender(this);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/discovery/oak/OakDiscoveryServiceTest.java b/src/test/java/org/apache/sling/discovery/oak/OakDiscoveryServiceTest.java
index d6ebfeb..4031b7b 100644
--- a/src/test/java/org/apache/sling/discovery/oak/OakDiscoveryServiceTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/OakDiscoveryServiceTest.java
@@ -18,13 +18,6 @@
*/
package org.apache.sling.discovery.oak;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -56,7 +49,6 @@ import org.apache.sling.discovery.oak.its.setup.OakTestConfig;
import org.apache.sling.discovery.oak.its.setup.OakVirtualInstanceBuilder;
import org.apache.sling.discovery.oak.its.setup.SimulatedLease;
import org.apache.sling.discovery.oak.its.setup.SimulatedLeaseCollection;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -64,6 +56,13 @@ import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
public class OakDiscoveryServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -98,7 +97,6 @@ public class OakDiscoveryServiceTest {
public long getClusterSyncServiceIntervalMillis() {
return bgIntervalMillis;
}
-
}
@Before
@@ -120,24 +118,25 @@ public class OakDiscoveryServiceTest {
@Test
public void testBindBeforeActivate() throws Exception {
- OakVirtualInstanceBuilder builder =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
- .setDebugName("test")
- .newRepository("/foo/bar", true);
- String slingId = UUID.randomUUID().toString();;
+ OakVirtualInstanceBuilder builder = (OakVirtualInstanceBuilder)
+ new OakVirtualInstanceBuilder().setDebugName("test").newRepository("/foo/bar", true);
+ String slingId = UUID.randomUUID().toString();
+ ;
DiscoveryLiteDescriptorBuilder discoBuilder = new DiscoveryLiteDescriptorBuilder();
discoBuilder.id("id").me(1).activeIds(1);
// make sure the discovery-lite descriptor is marked as not final
// such that the view is not already set before we want it to be
discoBuilder.setFinal(false);
- DescriptorHelper.setDiscoveryLiteDescriptor(builder.getResourceResolverFactory(),
- discoBuilder);
- IdMapService idMapService = IdMapService.testConstructor(new SimpleCommonsConfig(1000, -1), new DummySlingSettingsService(slingId), builder.getResourceResolverFactory());
+ DescriptorHelper.setDiscoveryLiteDescriptor(builder.getResourceResolverFactory(), discoBuilder);
+ IdMapService idMapService = IdMapService.testConstructor(
+ new SimpleCommonsConfig(1000, -1),
+ new DummySlingSettingsService(slingId),
+ builder.getResourceResolverFactory());
assertTrue(idMapService.waitForInit(2000));
OakDiscoveryService discoveryService = (OakDiscoveryService) builder.getDiscoverService();
assertNotNull(discoveryService);
DummyListener listener = new DummyListener();
- for(int i=0; i<100; i++) {
+ for (int i = 0; i < 100; i++) {
discoveryService.bindTopologyEventListener(listener);
discoveryService.unbindTopologyEventListener(listener);
}
@@ -152,8 +151,7 @@ public class OakDiscoveryServiceTest {
// will actually detect a valid new, different view and send out an event -
// exactly as we want to
discoBuilder.setFinal(true);
- DescriptorHelper.setDiscoveryLiteDescriptor(builder.getResourceResolverFactory(),
- discoBuilder);
+ DescriptorHelper.setDiscoveryLiteDescriptor(builder.getResourceResolverFactory(), discoBuilder);
// SLING-6924 : need to simulate a OakViewChecker.activate to trigger resetLeaderElectionId
// otherwise no TOPOLOGY_INIT will be generated as without a leaderElectionId we now
// consider a view as NO_ESTABLISHED_VIEW
@@ -171,17 +169,15 @@ public class OakDiscoveryServiceTest {
@Test
public void testDescriptorSeqNumChange() throws Exception {
logger.info("testDescriptorSeqNumChange: start");
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barry/foo/", true)
.setConnectorPingInterval(999)
.setConnectorPingTimeout(999);
builder1.getConfig().setSuppressPartiallyStartedInstance(true);
-;
+ ;
VirtualInstance instance1 = builder1.build();
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingInterval(999)
@@ -198,7 +194,8 @@ public class OakDiscoveryServiceTest {
assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
assertEquals(0, listener.countEvents());
- logger.info("testDescriptorSeqNumChange: issuing 2 heartbeats with each instance should let the topology get established");
+ logger.info(
+ "testDescriptorSeqNumChange: issuing 2 heartbeats with each instance should let the topology get established");
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
@@ -220,23 +217,25 @@ public class OakDiscoveryServiceTest {
// while we were sleeping
SimulatedLeaseCollection c = builder1.getSimulatedLeaseCollection();
c.incSeqNum(2);
- logger.info("testDescriptorSeqNumChange: incremented seqnum by 2 - issuing another heartbeat should trigger a topology change");
+ logger.info(
+ "testDescriptorSeqNumChange: incremented seqnum by 2 - issuing another heartbeat should trigger a topology change");
instance1.heartbeatsAndCheckView();
- // due to the nature of the syncService/minEventDelay we now explicitly first sleep 2sec before waiting for async events for another 2sec
+ // due to the nature of the syncService/minEventDelay we now explicitly first sleep 2sec before waiting for
+ // async events for another 2sec
logger.info("testDescriptorSeqNumChange: sleeping 2sec for topology change to happen");
Thread.sleep(2000);
logger.info("testDescriptorSeqNumChange: ensuring no async events are still in the pipe - for another 2sec");
assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
- logger.info("testDescriptorSeqNumChange: now listener should have received 3 events, it got: "+listener.countEvents());
+ logger.info("testDescriptorSeqNumChange: now listener should have received 3 events, it got: "
+ + listener.countEvents());
assertEquals(3, listener.countEvents());
}
@Test
public void testNotYetInitializedLeaderElectionid() throws Exception {
logger.info("testNotYetInitializedLeaderElectionid: start");
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance")
.newRepository("/foo/barrx/foo/", true)
.setConnectorPingInterval(999)
@@ -253,26 +252,30 @@ public class OakDiscoveryServiceTest {
assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
assertEquals(0, listener.countEvents());
- logger.info("testNotYetInitializedLeaderElectionid: issuing 2 heartbeats with each instance should let the topology get established");
+ logger.info(
+ "testNotYetInitializedLeaderElectionid: issuing 2 heartbeats with each instance should let the topology get established");
instance1.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
- logger.info("testNotYetInitializedLeaderElectionid: listener should get an event within 2sec from now at latest");
+ logger.info(
+ "testNotYetInitializedLeaderElectionid: listener should get an event within 2sec from now at latest");
assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
assertEquals(1, listener.countEvents());
SimulatedLeaseCollection c = builder1.getSimulatedLeaseCollection();
String secondSlingId = UUID.randomUUID().toString();
- final SimulatedLease newIncomingInstance = new SimulatedLease(instance1.getResourceResolverFactory(), c, secondSlingId);
+ final SimulatedLease newIncomingInstance =
+ new SimulatedLease(instance1.getResourceResolverFactory(), c, secondSlingId);
c.hooked(newIncomingInstance);
c.incSeqNum(1);
newIncomingInstance.updateLeaseAndDescriptor(new OakTestConfig());
-
+
logger.info("testNotYetInitializedLeaderElectionid: issuing another 2 heartbeats");
instance1.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
-
- // there are different properties that an instance must set in the repository such that it finally becomes visible.
+
+ // there are different properties that an instance must set in the repository such that it finally becomes
+ // visible.
// these include:
// 1) idmap : it must map the oak id to sling id
// 2) node named after its own slingId under /var/discovery/oak/clusterInstances/<slingId>
@@ -280,45 +283,50 @@ public class OakDiscoveryServiceTest {
// in all 3 cases the code must work fine if that node/property doesn't exist
// and that's exactly what we're testing here.
-
// initially not even the idmap is updated, so we're stuck with TOPOLOGY_CHANGING
- // due to the nature of the syncService/minEventDelay we now explicitly first sleep 2sec before waiting for async events for another 2sec
+ // due to the nature of the syncService/minEventDelay we now explicitly first sleep 2sec before waiting for
+ // async events for another 2sec
logger.info("testNotYetInitializedLeaderElectionid: sleeping 2sec for topology change to happen");
Thread.sleep(2000);
- logger.info("testNotYetInitializedLeaderElectionid: ensuring no async events are still in the pipe - for another 2sec");
+ logger.info(
+ "testNotYetInitializedLeaderElectionid: ensuring no async events are still in the pipe - for another 2sec");
assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
- logger.info("testNotYetInitializedLeaderElectionid: now listener should have received 2 events, INIT and CHANGING, it got: "+listener.countEvents());
+ logger.info(
+ "testNotYetInitializedLeaderElectionid: now listener should have received 2 events, INIT and CHANGING, it got: "
+ + listener.countEvents());
assertEquals(2, listener.countEvents());
List<TopologyEvent> events = listener.getEvents();
assertEquals(TopologyEvent.Type.TOPOLOGY_INIT, events.get(0).getType());
assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGING, events.get(1).getType());
-
+
// let's update the idmap first then
DummyResourceResolverFactory factory1 = (DummyResourceResolverFactory) instance1.getResourceResolverFactory();
ResourceResolverFactory factory2 = MockFactory.mockResourceResolverFactory(factory1.getSlingRepository());
ResourceResolver resourceResolver = getResourceResolver(instance1.getResourceResolverFactory());
- DiscoveryLiteDescriptor descriptor =
- DiscoveryLiteDescriptor.getDescriptorFrom(resourceResolver);
+ DiscoveryLiteDescriptor descriptor = DiscoveryLiteDescriptor.getDescriptorFrom(resourceResolver);
resourceResolver.close();
-
+
DiscoveryLiteDescriptorBuilder dlb = prefill(descriptor);
dlb.me(2);
DescriptorHelper.setDiscoveryLiteDescriptor(factory2, dlb);
@SuppressWarnings("unused")
- IdMapService secondIdMapService = IdMapService.testConstructor((DiscoveryLiteConfig) builder1.getConnectorConfig(), new DummySlingSettingsService(secondSlingId), factory2);
-
+ IdMapService secondIdMapService = IdMapService.testConstructor(
+ (DiscoveryLiteConfig) builder1.getConnectorConfig(),
+ new DummySlingSettingsService(secondSlingId),
+ factory2);
+
instance1.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
Thread.sleep(2000);
assertEquals(2, listener.countEvents());
-
-
+
// now let's add the /var/discovery/oak/clusterInstances/<slingId> node
resourceResolver = getResourceResolver(factory2);
- Resource clusterInstancesRes = resourceResolver.getResource(builder1.getConnectorConfig().getClusterInstancesPath());
+ Resource clusterInstancesRes =
+ resourceResolver.getResource(builder1.getConnectorConfig().getClusterInstancesPath());
assertNull(clusterInstancesRes.getChild(secondSlingId));
resourceResolver.create(clusterInstancesRes, secondSlingId, null);
resourceResolver.commit();
@@ -332,12 +340,13 @@ public class OakDiscoveryServiceTest {
// now let's add the leaderElectionId
resourceResolver = getResourceResolver(factory2);
- Resource instanceResource = resourceResolver.getResource(builder1.getConnectorConfig().getClusterInstancesPath() + "/" + secondSlingId);
+ Resource instanceResource = resourceResolver.getResource(
+ builder1.getConnectorConfig().getClusterInstancesPath() + "/" + secondSlingId);
assertNotNull(instanceResource);
instanceResource.adaptTo(ModifiableValueMap.class).put("leaderElectionId", "0");
resourceResolver.commit();
resourceResolver.close();
-
+
instance1.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
Thread.sleep(2000);
@@ -358,10 +367,11 @@ public class OakDiscoveryServiceTest {
}
private Integer[] box(final int[] ids) {
- return Arrays.stream( ids ).boxed().collect( Collectors.toList() ).toArray(new Integer[ids.length]);
+ return Arrays.stream(ids).boxed().collect(Collectors.toList()).toArray(new Integer[ids.length]);
}
-
- private ResourceResolver getResourceResolver(ResourceResolverFactory resourceResolverFactory) throws LoginException {
+
+ private ResourceResolver getResourceResolver(ResourceResolverFactory resourceResolverFactory)
+ throws LoginException {
return resourceResolverFactory.getServiceResourceResolver(null);
}
@@ -385,10 +395,9 @@ public class OakDiscoveryServiceTest {
assertTrue(lastView.getLocalInstance().isLeader());
}
- private BaseTopologyView doTestInvertedLeaderElectionOrder(final int instance1Prefix, final int instance2Prefix, boolean syncTokenEnabled)
- throws Exception {
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ private BaseTopologyView doTestInvertedLeaderElectionOrder(
+ final int instance1Prefix, final int instance2Prefix, boolean syncTokenEnabled) throws Exception {
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barrio/foo/", true)
.setConnectorPingInterval(999)
@@ -399,8 +408,7 @@ public class OakDiscoveryServiceTest {
builder1.getConfig().setJoinerDelaySeconds(0);
builder1.getConfig().setSuppressPartiallyStartedInstance(true);
VirtualInstance instance1 = builder1.build();
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingInterval(999)
@@ -411,16 +419,16 @@ public class OakDiscoveryServiceTest {
builder2.getConfig().setJoinerDelaySeconds(0);
builder2.getConfig().setSuppressPartiallyStartedInstance(true);
VirtualInstance instance2 = builder2.build();
-
+
DummyListener listener = new DummyListener();
OakDiscoveryService discoveryService = (OakDiscoveryService) instance1.getDiscoveryService();
discoveryService.bindTopologyEventListener(listener);
-
+
instance2.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
-
+
assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
assertEquals(1, listener.countEvents());
instance1.stop();
@@ -429,9 +437,8 @@ public class OakDiscoveryServiceTest {
}
@Test
- public void testPropertyProviderRegistrations() throws Exception{
- OakVirtualInstanceBuilder builder =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ public void testPropertyProviderRegistrations() throws Exception {
+ OakVirtualInstanceBuilder builder = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barrio/foo/", true)
.setConnectorPingInterval(999)
@@ -467,7 +474,7 @@ public class OakDiscoveryServiceTest {
private boolean waitForEquals(DummyListener listener, int expected, long maxWait) {
final long timeout = System.currentTimeMillis() + maxWait;
- while(System.currentTimeMillis() < timeout) {
+ while (System.currentTimeMillis() < timeout) {
if (listener.countEvents() == expected) {
return true;
}
@@ -487,8 +494,7 @@ public class OakDiscoveryServiceTest {
}
private void doSimpleNewJoinerTest(int joinerDelaySeconds) throws Exception {
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barrio/foo/", true)
.setConnectorPingInterval(999)
@@ -508,8 +514,7 @@ public class OakDiscoveryServiceTest {
Thread.sleep(1000);
assertEquals(1, listener1.countEvents());
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingInterval(999)
@@ -545,8 +550,7 @@ public class OakDiscoveryServiceTest {
waitForEquals(listener1, 3, 1000);
waitForEquals(listener2, 1, 3000); // had a flaky failure so giving it 3 sec
- OakVirtualInstanceBuilder builder3 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder3 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance3")
.useRepositoryOf(instance1)
.setConnectorPingInterval(999)
@@ -557,7 +561,7 @@ public class OakDiscoveryServiceTest {
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
- for(int i=0; i<5; i++) {
+ for (int i = 0; i < 5; i++) {
Thread.sleep(300);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
@@ -573,7 +577,7 @@ public class OakDiscoveryServiceTest {
instance3.heartbeatsAndCheckView();
- for(int i=0; i<4; i++) {
+ for (int i = 0; i < 4; i++) {
Thread.sleep(500);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
@@ -590,8 +594,7 @@ public class OakDiscoveryServiceTest {
@Test
public void testSingleStart() throws Exception {
// 1. start instance 1 normally
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo1/barrio/foo1/", true)
.setConnectorPingInterval(999999)
@@ -619,8 +622,7 @@ public class OakDiscoveryServiceTest {
// a leader reacting slow with syncToken update risks loosing
// the leader flag. this test should ensure it's fine as long
// as it is within minEventDelay
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo1/barrio/foo1/", true)
.setConnectorPingInterval(999999)
@@ -641,8 +643,7 @@ public class OakDiscoveryServiceTest {
waitForEquals(listener1, 1, 1000);
assertEquals(1, listener1.countEvents());
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -672,7 +673,7 @@ public class OakDiscoveryServiceTest {
instance2.heartbeatsAndCheckView();
assertEquals(1, listener1.countEvents());
assertEquals(0, listener2.countEvents());
- for(int i=0; i<8; i++) {
+ for (int i = 0; i < 8; i++) {
Thread.sleep(1000);
instance2.heartbeatsAndCheckView();
assertEquals("i is " + i, 1, listener1.countEvents());
@@ -687,7 +688,7 @@ public class OakDiscoveryServiceTest {
Thread.sleep(1000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
- for(int i=0; i<4; i++) {
+ for (int i = 0; i < 4; i++) {
Thread.sleep(1000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
@@ -702,8 +703,7 @@ public class OakDiscoveryServiceTest {
// 2. start instance 2 only partially -> gets ignored by 1
// 3. start instance 3 + 4 fully -> they should wait for (4/3 and 2)
// 4. then start instance 2 fully -> 3 and 4 should get resolved
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo1/barrio/foo1/", true)
.setConnectorPingInterval(999999)
@@ -726,8 +726,7 @@ public class OakDiscoveryServiceTest {
instance1.heartbeatsAndCheckView();
assertEquals(1, listener1.countEvents());
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -740,8 +739,7 @@ public class OakDiscoveryServiceTest {
Thread.sleep(1000);
- OakVirtualInstanceBuilder builder3 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder3 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance3")
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -755,8 +753,7 @@ public class OakDiscoveryServiceTest {
OakDiscoveryService discoveryService3 = (OakDiscoveryService) instance3.getDiscoveryService();
discoveryService3.bindTopologyEventListener(listener3);
- OakVirtualInstanceBuilder builder4 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder4 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance4")
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -773,7 +770,7 @@ public class OakDiscoveryServiceTest {
instance1.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
instance4.heartbeatsAndCheckView();
- for(int i=0; i<7; i++) {
+ for (int i = 0; i < 7; i++) {
Thread.sleep(1000);
instance1.heartbeatsAndCheckView();
instance3.heartbeatsAndCheckView();
@@ -792,7 +789,7 @@ public class OakDiscoveryServiceTest {
instance4.heartbeatsAndCheckView();
assertEquals(0, listener3.countEvents());
assertEquals(0, listener4.countEvents());
- for(int i=0; i<7; i++) {
+ for (int i = 0; i < 7; i++) {
Thread.sleep(1000);
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
@@ -806,8 +803,7 @@ public class OakDiscoveryServiceTest {
@Test
public void testUpdateDuringJoinDelay() throws Exception {
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo1/barrio/foo1/", true)
.setConnectorPingInterval(999999)
@@ -829,8 +825,7 @@ public class OakDiscoveryServiceTest {
instance1.heartbeatsAndCheckView();
assertEquals(1, listener1.countEvents());
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -866,8 +861,7 @@ public class OakDiscoveryServiceTest {
assertEquals(3, listener1.countEvents());
assertEquals(0, listener2.countEvents());
- OakVirtualInstanceBuilder builder3 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder3 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance3")
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -934,7 +928,7 @@ public class OakDiscoveryServiceTest {
VirtualInstance instance1 = builder1.build();
DummyListener listener1 = createDummyListener(instance1);
- for(int i = 0; i < 3; i++) {
+ for (int i = 0; i < 3; i++) {
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
}
@@ -946,7 +940,7 @@ public class OakDiscoveryServiceTest {
// 2. start instance 2 only partially -> do not call builder2.build() but just updateLease()
builder2.updateLease();
- for(int i = 0; i < 3; i++) {
+ for (int i = 0; i < 3; i++) {
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
}
@@ -956,7 +950,7 @@ public class OakDiscoveryServiceTest {
VirtualInstance instance2 = builder2.build();
DummyListener listener2 = createDummyListener(instance2);
- for(int i = 0; i < 3; i++) {
+ for (int i = 0; i < 3; i++) {
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(1000);
@@ -964,7 +958,7 @@ public class OakDiscoveryServiceTest {
assertEquals(0, listener2.countEvents());
assertEquals(3, listener1.countEvents());
- for(int i = 0; i < 3; i++) {
+ for (int i = 0; i < 3; i++) {
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(1000);
@@ -976,7 +970,7 @@ public class OakDiscoveryServiceTest {
logger.info("reuseClusterIdTest : STOP 2");
instance2.stop();
- for(int i = 0; i < 2; i++) {
+ for (int i = 0; i < 2; i++) {
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
}
@@ -984,15 +978,14 @@ public class OakDiscoveryServiceTest {
// re-create instance2, with same clusterNodeId/slingId
logger.info("reuseClusterIdTest : creating instance2b.");
- OakVirtualInstanceBuilder builder2b = createInstanceUsingExistingRepo(builder1,
- "instance2b", 1, 5);
+ OakVirtualInstanceBuilder builder2b = createInstanceUsingExistingRepo(builder1, "instance2b", 1, 5);
builder2b.setSlingId(builder2.getSlingId());
builder2b.getLease().setClusterNodeIdHint(2);
builder2b.getSimulatedLeaseCollection().incSeqNum();
// 2. start instance 2 only partially -> do not call builder2.build() but just updateLease()
builder2b.updateLease();
- for(int i = 0; i < 2; i++) {
+ for (int i = 0; i < 2; i++) {
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
}
@@ -1003,7 +996,7 @@ public class OakDiscoveryServiceTest {
VirtualInstance instance2b = builder2b.build();
DummyListener listener2b = createDummyListener(instance2b);
- for(int i = 0; i < 3; i++) {
+ for (int i = 0; i < 3; i++) {
instance1.heartbeatsAndCheckView();
instance2b.heartbeatsAndCheckView();
Thread.sleep(1000);
@@ -1013,7 +1006,7 @@ public class OakDiscoveryServiceTest {
assertEquals(0, listener2b.countEvents());
assertEquals(7, listener1.countEvents());
- for(int i = 0; i < 4; i++) {
+ for (int i = 0; i < 4; i++) {
Thread.sleep(1000);
instance1.heartbeatsAndCheckView();
instance2b.heartbeatsAndCheckView();
@@ -1025,22 +1018,20 @@ public class OakDiscoveryServiceTest {
@Test
public void testTopologyChangeWithOneSlowMember() throws Exception {
logger.info("testTopologyChangeWithOneSlowMember : START - creating instance1.");
- OakVirtualInstanceBuilder builder1 = createInstanceWithNewRepo("instance1",
- "/foo1/barrio/foo1/", 5, 1);
+ OakVirtualInstanceBuilder builder1 = createInstanceWithNewRepo("instance1", "/foo1/barrio/foo1/", 5, 1);
// 1. start instance 1 normally -> call builder1.build()
VirtualInstance instance1 = builder1.build();
DummyListener listener1 = createDummyListener(instance1);
// instance2 normally
logger.info("testTopologyChangeWithOneSlowMember : creating instance2.");
- OakVirtualInstanceBuilder builder2 = createInstanceUsingExistingRepo(builder1,
- "instance2", 1, 1);
+ OakVirtualInstanceBuilder builder2 = createInstanceUsingExistingRepo(builder1, "instance2", 1, 1);
// 2. start instance 2 normally -> call builder2.build()
VirtualInstance instance2 = builder2.build();
DummyListener listener2 = createDummyListener(instance2);
// a bunch of heartbeats
- for(int i=0; i<7; i++) {
+ for (int i = 0; i < 7; i++) {
instance1.heartbeatsAndCheckView();
instance2.heartbeatsAndCheckView();
Thread.sleep(1000);
@@ -1059,20 +1050,22 @@ public class OakDiscoveryServiceTest {
builder1.getLease().incSeqNum();
// now let instance2 behave slow : it still has a valid lease but doesn't do the syncToken quickly
- for(int i=0; i<4; i++) {
+ for (int i = 0; i < 4; i++) {
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
}
- logger.info("testTopologyChangeWithOneSlowMember : check listener1 having gotten a TOPOLOGY_CHANGING but listener2 not yet");
+ logger.info(
+ "testTopologyChangeWithOneSlowMember : check listener1 having gotten a TOPOLOGY_CHANGING but listener2 not yet");
assertEquals(1, listener1.countEvents()); // a TOPOLOGY_CHANGING only
- assertEquals(TopologyEvent.Type.TOPOLOGY_CHANGING, listener1.getEvents().get(0).getType());
+ assertEquals(
+ TopologyEvent.Type.TOPOLOGY_CHANGING,
+ listener1.getEvents().get(0).getType());
assertEquals(0, listener2.countEvents());
}
private OakVirtualInstanceBuilder createInstanceUsingExistingRepo(
OakVirtualInstanceBuilder builder1, String debugName, int minEventDelay, int joinerDelay) throws Exception {
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName(debugName)
.useRepositoryOf(builder1)
.setConnectorPingInterval(999999)
@@ -1091,11 +1084,13 @@ public class OakDiscoveryServiceTest {
return newListener;
}
- private OakVirtualInstanceBuilder createInstanceWithNewRepo(String debugName,
- String discoveryPath, int minEventDelay, long joinerDelay) throws Exception {
+ private OakVirtualInstanceBuilder createInstanceWithNewRepo(
+ String debugName, String discoveryPath, int minEventDelay, long joinerDelay) throws Exception {
final OakVirtualInstanceBuilder builder = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
- .setDebugName(debugName).newRepository(discoveryPath, true)
- .setConnectorPingInterval(999999).setConnectorPingTimeout(999999);
+ .setDebugName(debugName)
+ .newRepository(discoveryPath, true)
+ .setConnectorPingInterval(999999)
+ .setConnectorPingTimeout(999999);
builder.getConfig().setMinEventDelay(minEventDelay);
builder.setMinEventDelay(minEventDelay);
builder.getConfig().setJoinerDelaySeconds(joinerDelay);
@@ -1103,4 +1098,4 @@ public class OakDiscoveryServiceTest {
builder.getConfig().setSuppressPartiallyStartedInstance(true);
return builder;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/discovery/oak/PartialStartupTest.java b/src/test/java/org/apache/sling/discovery/oak/PartialStartupTest.java
index 0e80f7f..8174e6d 100644
--- a/src/test/java/org/apache/sling/discovery/oak/PartialStartupTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/PartialStartupTest.java
@@ -18,12 +18,6 @@
*/
package org.apache.sling.discovery.oak;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
@@ -63,6 +57,12 @@ import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
public class PartialStartupTest {
private MemoryNodeStore nodeStore;
@@ -87,11 +87,20 @@ public class PartialStartupTest {
private final SlingSettingsService settingsService;
private final OakClusterViewService ocvService;
- MiniInstance(int me, NodeStore nodeStore, final boolean suppressPartiallyStartedInstances, final boolean syncTokenEnabled) {
+ MiniInstance(
+ int me,
+ NodeStore nodeStore,
+ final boolean suppressPartiallyStartedInstances,
+ final boolean syncTokenEnabled) {
this(me, UUID.randomUUID().toString(), nodeStore, suppressPartiallyStartedInstances, syncTokenEnabled);
}
- MiniInstance(int me, String slingId, NodeStore nodeStore, final boolean suppressPartiallyStartedInstances, final boolean syncTokenEnabled) {
+ MiniInstance(
+ int me,
+ String slingId,
+ NodeStore nodeStore,
+ final boolean suppressPartiallyStartedInstances,
+ final boolean syncTokenEnabled) {
this(me, slingId, nodeStore, new Config() {
@Override
public long getClusterSyncServiceIntervalMillis() {
@@ -123,20 +132,26 @@ public class PartialStartupTest {
idMapService = IdMapService.testConstructor(config, settingsService, resourceResolverFactory);
- ocvService = OakClusterViewService.testConstructor(settingsService, resourceResolverFactory, idMapService, config);
+ ocvService = OakClusterViewService.testConstructor(
+ settingsService, resourceResolverFactory, idMapService, config);
}
private void setDescriptor(DiscoveryLiteDescriptorBuilder builder) throws Exception {
- DescriptorHelper.setDescriptor(resourceResolverFactory, DiscoveryLiteDescriptor.OAK_DISCOVERYLITE_CLUSTERVIEW, builder == null ? null : builder.me(me).asJson());
+ DescriptorHelper.setDescriptor(
+ resourceResolverFactory,
+ DiscoveryLiteDescriptor.OAK_DISCOVERYLITE_CLUSTERVIEW,
+ builder == null ? null : builder.me(me).asJson());
}
private void initLeaderElectionId() {
- OakViewChecker viewChecker = OakViewCheckerFactory.createOakViewChecker(settingsService, resourceResolverFactory, config);
+ OakViewChecker viewChecker =
+ OakViewCheckerFactory.createOakViewChecker(settingsService, resourceResolverFactory, config);
viewChecker.resetLeaderElectionId();
}
private void storeSyncToken(String syncToken) {
- SyncTokenService syncTokenService = SyncTokenService.testConstructorAndActivate(config, resourceResolverFactory, settingsService);
+ SyncTokenService syncTokenService =
+ SyncTokenService.testConstructorAndActivate(config, resourceResolverFactory, settingsService);
final String clusterId = UUID.randomUUID().toString();
final DefaultClusterView cluster = new DefaultClusterView(clusterId);
BaseTopologyView view = new DummyTopologyView(syncToken).addInstance(slingId, cluster, true, true);
@@ -147,7 +162,6 @@ public class PartialStartupTest {
public void run() {
done.set(true);
}
-
});
assertTrue(done.get());
}
@@ -198,11 +212,19 @@ public class PartialStartupTest {
return new MiniInstance(baseInstance.me, newSlingId, nodeStore, true, true);
}
- private MiniInstance create(int id, boolean storeSlingId, boolean storeLeaderElectionId, String syncIdOrNull) throws Exception {
+ private MiniInstance create(int id, boolean storeSlingId, boolean storeLeaderElectionId, String syncIdOrNull)
+ throws Exception {
return create(true, true, id, storeSlingId, storeLeaderElectionId, syncIdOrNull);
}
- private MiniInstance create(boolean suppressPartiallyStartedInstances, boolean syncTokenEnabled, int id, boolean storeSlingId, boolean storeLeaderElectionId, String syncIdOrNull) throws Exception {
+ private MiniInstance create(
+ boolean suppressPartiallyStartedInstances,
+ boolean syncTokenEnabled,
+ int id,
+ boolean storeSlingId,
+ boolean storeLeaderElectionId,
+ String syncIdOrNull)
+ throws Exception {
MiniInstance instance = new MiniInstance(id, nodeStore, suppressPartiallyStartedInstances, syncTokenEnabled);
if (storeSlingId) {
instance.storeSlingId();
@@ -213,7 +235,11 @@ public class PartialStartupTest {
if (storeSlingId && storeLeaderElectionId) {
try {
@SuppressWarnings("deprecation")
- ClusterReader r = new ClusterReader(instance.resourceResolverFactory.getAdministrativeResourceResolver(null), instance.config, instance.idMapService, null);
+ ClusterReader r = new ClusterReader(
+ instance.resourceResolverFactory.getAdministrativeResourceResolver(null),
+ instance.config,
+ instance.idMapService,
+ null);
InstanceReadResult i = r.readInstance(id, false, -1);
assertNotNull(i.getInstanceInfo());
System.out.println(" instance " + id + " read " + i.getInstanceInfo());
@@ -249,10 +275,11 @@ public class PartialStartupTest {
return new DiscoveryLiteDescriptorBuilder().id("anyId").setFinal(true).seq(seqNum);
}
- private static DiscoveryLiteDescriptorBuilder simpleDesc(int seqNum, Identifiable...instances) {
- final DiscoveryLiteDescriptorBuilder builder = new DiscoveryLiteDescriptorBuilder().id("anyId").setFinal(true).seq(seqNum);
+ private static DiscoveryLiteDescriptorBuilder simpleDesc(int seqNum, Identifiable... instances) {
+ final DiscoveryLiteDescriptorBuilder builder =
+ new DiscoveryLiteDescriptorBuilder().id("anyId").setFinal(true).seq(seqNum);
Integer[] activeIds = new Integer[instances.length];
- for (int i = 0; i < instances.length; i++ ) {
+ for (int i = 0; i < instances.length; i++) {
activeIds[i] = instances[i].me;
}
builder.activeIds(activeIds);
@@ -288,7 +315,7 @@ public class PartialStartupTest {
try {
instance.getLocalClusterView(null);
fail("should have thrown exception");
- } catch(UndefinedClusterViewException ucve) {
+ } catch (UndefinedClusterViewException ucve) {
// this empty catch is okay
}
}
@@ -305,7 +332,7 @@ public class PartialStartupTest {
try {
instance.getLocalClusterView(desc().id("id").me(1).activeIds(1));
fail("should have thrown exception");
- } catch(UndefinedClusterViewException ucve) {
+ } catch (UndefinedClusterViewException ucve) {
// this empty catch is okay
}
}
@@ -316,7 +343,7 @@ public class PartialStartupTest {
try {
instance.getLocalClusterView(simpleDesc(1).me(1).activeIds(1));
fail("should have thrown exception");
- } catch(UndefinedClusterViewException ucve) {
+ } catch (UndefinedClusterViewException ucve) {
// this empty catch is okay
}
}
@@ -330,7 +357,8 @@ public class PartialStartupTest {
}
private void doTestSimple(MiniInstance instance) throws Exception {
- LocalClusterView localView = instance.getLocalClusterView(simpleDesc(1).me(instance.me).activeIds(instance.me));
+ LocalClusterView localView =
+ instance.getLocalClusterView(simpleDesc(1).me(instance.me).activeIds(instance.me));
assertNotNull(localView);
assertNoPartiallyStarted(localView);
assertEquals(1, localView.getInstances().size());
@@ -346,42 +374,42 @@ public class PartialStartupTest {
try {
instance1.getLocalClusterView(simpleDesc(2, instance1, instance2, instance3));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance3 = create(3, true, false, null);
try {
instance1.getLocalClusterView(simpleDesc(2, instance1, instance2, instance3));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance3 = create(3, false, true, null);
try {
instance1.getLocalClusterView(simpleDesc(2, instance1, instance2, instance3));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance3 = create(3, false, false, "2");
try {
instance1.getLocalClusterView(simpleDesc(2, instance1, instance2, instance3));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance3 = create(3, true, false, "2");
try {
instance1.getLocalClusterView(simpleDesc(2, instance1, instance2, instance3));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance3 = create(3, false, true, "2");
try {
instance1.getLocalClusterView(simpleDesc(2, instance1, instance2, instance3));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
System.out.println(" => instance1 is " + instance1);
@@ -401,7 +429,7 @@ public class PartialStartupTest {
try {
instance.getLocalClusterView(simpleDesc(2).activeIds(1, 2));
fail("should complain");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
}
@@ -410,7 +438,8 @@ public class PartialStartupTest {
public void testSlowJoiner() throws Exception {
// init just with 1 instance
MiniInstance instance1 = create(1, true, true, null);
- assertNotNull(instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
+ assertNotNull(
+ instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
instance1.storeSyncToken("1");
@@ -428,7 +457,8 @@ public class PartialStartupTest {
public void testFastJoiner() throws Exception {
// init just with 1 instance
MiniInstance instance1 = create(1, true, true, null);
- assertNotNull(instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
+ assertNotNull(
+ instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
instance1.storeSyncToken("1");
@@ -451,10 +481,12 @@ public class PartialStartupTest {
@Test
public void testJoineLeaveMultiple() throws Exception {
MiniInstance instance1 = create(1, true, true, null);
- assertNotNull(instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
+ assertNotNull(
+ instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
instance1.storeSyncToken("1");
- assertNotNull(instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
+ assertNotNull(
+ instance1.getLocalClusterView(simpleDesc(1).me(instance1.me).activeIds(instance1.me)));
// let a fast instance 2 join
MiniInstance instance2 = create(2, true, true, "2");
@@ -524,7 +556,8 @@ public class PartialStartupTest {
assertEquals(1, localView.getInstances().size());
localView = instance1.getLocalClusterView(simpleDesc(3, instance1, instance2b));
assertEquals(1, localView.getInstances().size());
- // storing the slingId doesn't change anything, it was already considered as not previously seen, hence suppressed
+ // storing the slingId doesn't change anything, it was already considered as not previously seen, hence
+ // suppressed
instance2b.storeSlingId();
localView = instance1.getLocalClusterView(simpleDesc(3, instance1, instance2b));
assertEquals(1, localView.getInstances().size());
@@ -694,12 +727,12 @@ public class PartialStartupTest {
assertEqualList(localView.getInstances(), instance1, instance3, instance4, instance2, instance5);
}
- private void assertEqualList(List<InstanceDescription> actualInstances,
- MiniInstance... expectedInstances) {
+ private void assertEqualList(List<InstanceDescription> actualInstances, MiniInstance... expectedInstances) {
assertEquals(actualInstances.size(), expectedInstances.length);
Set<InstanceDescription> s = new HashSet<>(actualInstances);
Iterator<InstanceDescription> it = s.iterator();
- out: while(it.hasNext()) {
+ out:
+ while (it.hasNext()) {
InstanceDescription n = it.next();
StringBuffer sb = new StringBuffer();
for (MiniInstance i : expectedInstances) {
@@ -786,14 +819,14 @@ public class PartialStartupTest {
try {
instance1.getLocalClusterView(simpleDesc(1, instance1, instance2));
fail("should have failed");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance2.storeSlingId();
try {
instance1.getLocalClusterView(simpleDesc(1, instance1, instance2));
fail("should have failed");
- } catch(Exception e) {
+ } catch (Exception e) {
// this empty catch is okay
}
instance2.initLeaderElectionId();
diff --git a/src/test/java/org/apache/sling/discovery/oak/TestSlingIdCleanupTask.java b/src/test/java/org/apache/sling/discovery/oak/TestSlingIdCleanupTask.java
index 0a95df4..8b43e55 100644
--- a/src/test/java/org/apache/sling/discovery/oak/TestSlingIdCleanupTask.java
+++ b/src/test/java/org/apache/sling/discovery/oak/TestSlingIdCleanupTask.java
@@ -18,12 +18,6 @@
*/
package org.apache.sling.discovery.oak;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.io.Closeable;
import java.io.IOException;
import java.lang.annotation.Annotation;
@@ -40,6 +34,8 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
+import com.google.common.io.Closer;
+import junitx.util.PrivateAccessor;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
@@ -67,9 +63,11 @@ import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.io.Closer;
-
-import junitx.util.PrivateAccessor;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
public class TestSlingIdCleanupTask {
@@ -118,7 +116,6 @@ public class TestSlingIdCleanupTask {
public long slingid_cleanup_min_creation_age() {
return age;
}
-
}
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -146,14 +143,13 @@ public class TestSlingIdCleanupTask {
private Scheduler createRealScheduler() throws Throwable {
final BundleContext ctx = Mockito.mock(BundleContext.class);
final Map<String, Object> props = new HashMap<>();
- final DefaultThreadPoolManager threadPoolManager = new DefaultThreadPoolManager(
- ctx, new Hashtable<String, Object>());
+ final DefaultThreadPoolManager threadPoolManager =
+ new DefaultThreadPoolManager(ctx, new Hashtable<String, Object>());
final QuartzScheduler qScheduler = new QuartzScheduler();
Scheduler scheduler = new SchedulerServiceFactory();
PrivateAccessor.setField(qScheduler, "threadPoolManager", threadPoolManager);
- PrivateAccessor.invoke(qScheduler, "activate",
- new Class[] { BundleContext.class, Map.class },
- new Object[] { ctx, props });
+ PrivateAccessor.invoke(
+ qScheduler, "activate", new Class[] {BundleContext.class, Map.class}, new Object[] {ctx, props});
PrivateAccessor.setField(scheduler, "scheduler", qScheduler);
closer.register(new Closeable() {
@@ -161,13 +157,12 @@ public class TestSlingIdCleanupTask {
@Override
public void close() throws IOException {
try {
- PrivateAccessor.invoke(qScheduler, "deactivate",
- new Class[] { BundleContext.class }, new Object[] { ctx });
+ PrivateAccessor.invoke(
+ qScheduler, "deactivate", new Class[] {BundleContext.class}, new Object[] {ctx});
} catch (Throwable e) {
throw new IOException(e);
}
}
-
});
return scheduler;
@@ -178,32 +173,46 @@ public class TestSlingIdCleanupTask {
closer = Closer.create();
}
- private void createCleanupTask(int initialDelayMillis, int minCreationAgeMillis)
- throws Exception {
+ private void createCleanupTask(int initialDelayMillis, int minCreationAgeMillis) throws Exception {
createCleanupTask(initialDelayMillis, 1000, 50, minCreationAgeMillis);
}
- private void createCleanupTask(int initialDelayMillis, int intervalMillis,
- int batchSize, long minCreationAgeMillis) throws Exception {
- createCleanupTask(initialDelayMillis, intervalMillis, batchSize,
- minCreationAgeMillis, SlingIdCleanupTask.MIN_CLEANUP_DELAY_MILLIS);
- }
-
- private void createCleanupTask(int initialDelayMillis, int intervalMillis,
- int batchSize, long minCreationAgeMillis, long minCleanupDelayMillis)
+ private void createCleanupTask(int initialDelayMillis, int intervalMillis, int batchSize, long minCreationAgeMillis)
+ throws Exception {
+ createCleanupTask(
+ initialDelayMillis,
+ intervalMillis,
+ batchSize,
+ minCreationAgeMillis,
+ SlingIdCleanupTask.MIN_CLEANUP_DELAY_MILLIS);
+ }
+
+ private void createCleanupTask(
+ int initialDelayMillis,
+ int intervalMillis,
+ int batchSize,
+ long minCreationAgeMillis,
+ long minCleanupDelayMillis)
throws Exception {
OakVirtualInstanceBuilder builder = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
- .setDebugName("instance").newRepository("/foo/bar/", true)
- .setConnectorPingInterval(999).setConnectorPingTimeout(999);
+ .setDebugName("instance")
+ .newRepository("/foo/bar/", true)
+ .setConnectorPingInterval(999)
+ .setConnectorPingTimeout(999);
builder.getConfig().setSuppressPartiallyStartedInstance(true);
instance = builder.build();
scheduler = createScheduler();
factory = instance.getResourceResolverFactory();
config = new OakTestConfig();
- System.setProperty(
- SlingIdCleanupTask.SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME, "true");
- cleanupTask = SlingIdCleanupTask.create(scheduler, factory, config,
- initialDelayMillis, intervalMillis, batchSize, minCreationAgeMillis,
+ System.setProperty(SlingIdCleanupTask.SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME, "true");
+ cleanupTask = SlingIdCleanupTask.create(
+ scheduler,
+ factory,
+ config,
+ initialDelayMillis,
+ intervalMillis,
+ batchSize,
+ minCreationAgeMillis,
minCleanupDelayMillis);
}
@@ -214,8 +223,7 @@ public class TestSlingIdCleanupTask {
instance.stop();
instance = null;
}
- System.clearProperty(
- SlingIdCleanupTask.SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME);
+ System.clearProperty(SlingIdCleanupTask.SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME);
if (cleanupTask != null) {
cleanupTask.deactivate();
cleanupTask = null;
@@ -223,10 +231,10 @@ public class TestSlingIdCleanupTask {
}
private TopologyView newView() {
- final DefaultClusterView cluster = new DefaultClusterView(
- UUID.randomUUID().toString());
- final DummyTopologyView view = new DummyTopologyView()
- .addInstance(UUID.randomUUID().toString(), cluster, true, true);
+ final DefaultClusterView cluster =
+ new DefaultClusterView(UUID.randomUUID().toString());
+ final DummyTopologyView view =
+ new DummyTopologyView().addInstance(UUID.randomUUID().toString(), cluster, true, true);
return view;
}
@@ -238,8 +246,7 @@ public class TestSlingIdCleanupTask {
return new TopologyEvent(TopologyEvent.Type.TOPOLOGY_CHANGING, oldView, null);
}
- private TopologyEvent newPropertiesChangedEvent(TopologyView oldView,
- TopologyView newView) {
+ private TopologyEvent newPropertiesChangedEvent(TopologyView oldView, TopologyView newView) {
return new TopologyEvent(TopologyEvent.Type.PROPERTIES_CHANGED, oldView, newView);
}
@@ -302,18 +309,15 @@ public class TestSlingIdCleanupTask {
assertEquals(1, cleanupTask.getRunCount());
}
- private void assertConfigs(int expectedInitialDelay, int expectedInterval,
- int expectedBatchSize, int expectedAge) throws NoSuchFieldException {
- int initialDelayMillis = (Integer) PrivateAccessor.getField(cleanupTask,
- "initialDelayMillis");
+ private void assertConfigs(int expectedInitialDelay, int expectedInterval, int expectedBatchSize, int expectedAge)
+ throws NoSuchFieldException {
+ int initialDelayMillis = (Integer) PrivateAccessor.getField(cleanupTask, "initialDelayMillis");
assertEquals(expectedInitialDelay, initialDelayMillis);
- int intervalMillis = (Integer) PrivateAccessor.getField(cleanupTask,
- "intervalMillis");
+ int intervalMillis = (Integer) PrivateAccessor.getField(cleanupTask, "intervalMillis");
assertEquals(expectedInterval, intervalMillis);
int batchSize = (Integer) PrivateAccessor.getField(cleanupTask, "batchSize");
assertEquals(expectedBatchSize, batchSize);
- long minCreationAgeMillis = (Long) PrivateAccessor.getField(cleanupTask,
- "minCreationAgeMillis");
+ long minCreationAgeMillis = (Long) PrivateAccessor.getField(cleanupTask, "minCreationAgeMillis");
assertEquals(expectedAge, minCreationAgeMillis);
}
@@ -330,8 +334,8 @@ public class TestSlingIdCleanupTask {
assertEquals(0, cleanupTask.getDeleteCount());
}
- private void waitForRunCount(SlingIdCleanupTask task, int expectedRunCount,
- int timeoutMillis) throws InterruptedException {
+ private void waitForRunCount(SlingIdCleanupTask task, int expectedRunCount, int timeoutMillis)
+ throws InterruptedException {
final long start = System.currentTimeMillis();
long diff;
do {
@@ -341,8 +345,10 @@ public class TestSlingIdCleanupTask {
Thread.sleep(50);
diff = (start + timeoutMillis) - System.currentTimeMillis();
} while (diff > 0);
- assertEquals("did not reach expected runcount within " + timeoutMillis + "ms",
- expectedRunCount, task.getCompletionCount());
+ assertEquals(
+ "did not reach expected runcount within " + timeoutMillis + "ms",
+ expectedRunCount,
+ task.getCompletionCount());
}
@Test
@@ -470,8 +476,7 @@ public class TestSlingIdCleanupTask {
@Test
public void testDisabled() throws Exception {
createCleanupTask(1000, 86400000);
- System.setProperty(
- SlingIdCleanupTask.SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME, "false");
+ System.setProperty(SlingIdCleanupTask.SLINGID_CLEANUP_ENABLED_SYSTEM_PROPERTY_NAME, "false");
assertEquals(0, cleanupTask.getDeleteCount());
createSlingIds(5, 10, 0);
@@ -538,10 +543,10 @@ public class TestSlingIdCleanupTask {
String localSlignId = it.next(); // second is local
int idx = 0;
for (String aSlingId : slingIds) {
- remoteLeaderView.addInstance(aSlingId, remoteLeaderCluster,
- aSlingId.equals(leaderSlingId), aSlingId.equals(localSlignId));
- localLeaderView.addInstance(aSlingId, localLeaderCluster,
- aSlingId.equals(localSlignId), aSlingId.equals(localSlignId));
+ remoteLeaderView.addInstance(
+ aSlingId, remoteLeaderCluster, aSlingId.equals(leaderSlingId), aSlingId.equals(localSlignId));
+ localLeaderView.addInstance(
+ aSlingId, localLeaderCluster, aSlingId.equals(localSlignId), aSlingId.equals(localSlignId));
if (++idx >= 2) {
break;
}
@@ -556,8 +561,7 @@ public class TestSlingIdCleanupTask {
assertEquals(0, cleanupTask.getDeleteCount());
Thread.sleep(1000);
assertEquals(0, cleanupTask.getDeleteCount());
- cleanupTask
- .handleTopologyEvent(newChangedEvent(remoteLeaderView, localLeaderView));
+ cleanupTask.handleTopologyEvent(newChangedEvent(remoteLeaderView, localLeaderView));
assertEquals(0, cleanupTask.getDeleteCount());
assertEquals(0, cleanupTask.getCompletionCount());
waitForRunCount(cleanupTask, 1, 5000);
@@ -589,8 +593,7 @@ public class TestSlingIdCleanupTask {
String localSlignId = leaderSlingId; // and is local too
int idx = 0;
for (String aSlingId : slingIds) {
- view1.addInstance(aSlingId, cluster, aSlingId.equals(leaderSlingId),
- aSlingId.equals(localSlignId));
+ view1.addInstance(aSlingId, cluster, aSlingId.equals(leaderSlingId), aSlingId.equals(localSlignId));
if (++idx >= activeIds) {
break;
}
@@ -636,8 +639,7 @@ public class TestSlingIdCleanupTask {
localSlignId = leaderSlingId; // and is local too
idx = 0;
for (String aSlingId : slingIds) {
- view2.addInstance(aSlingId, cluster, aSlingId.equals(leaderSlingId),
- aSlingId.equals(localSlignId));
+ view2.addInstance(aSlingId, cluster, aSlingId.equals(leaderSlingId), aSlingId.equals(localSlignId));
if (++idx >= 2) { // let's have only 2 active instances
break;
}
@@ -669,19 +671,15 @@ public class TestSlingIdCleanupTask {
}
}
- private void assertStatus(VirtualInstance i, Config c, String slingId,
- boolean deleted) throws Exception {
+ private void assertStatus(VirtualInstance i, Config c, String slingId, boolean deleted) throws Exception {
ResourceResolverFactory f = i.getResourceResolverFactory();
ResourceResolver resolver = null;
resolver = f.getServiceResourceResolver(null);
- final Resource clusterInstances = ResourceHelper.getOrCreateResource(resolver,
- c.getClusterInstancesPath());
- final Resource idMap = ResourceHelper.getOrCreateResource(resolver,
- c.getIdMapPath());
- final Resource syncTokens = ResourceHelper.getOrCreateResource(resolver,
- c.getSyncTokenPath());
+ final Resource clusterInstances = ResourceHelper.getOrCreateResource(resolver, c.getClusterInstancesPath());
+ final Resource idMap = ResourceHelper.getOrCreateResource(resolver, c.getIdMapPath());
+ final Resource syncTokens = ResourceHelper.getOrCreateResource(resolver, c.getSyncTokenPath());
resolver.refresh();
if (deleted) {
@@ -744,14 +742,15 @@ public class TestSlingIdCleanupTask {
throws Exception, InterruptedException {
logger.info(
"doTestOldSlingIdsButActive : recentIds={}, oldIds={}, activeIds={} : START",
- recentIds, oldIds, activeIds);
+ recentIds,
+ oldIds,
+ activeIds);
createCleanupTask(1000, 86400000);
assertEquals(0, cleanupTask.getDeleteCount());
- List<String> slingIds = createSlingIds(recentIds, oldIds,
- Math.max(0, activeIds - recentIds));
+ List<String> slingIds = createSlingIds(recentIds, oldIds, Math.max(0, activeIds - recentIds));
- final DefaultClusterView cluster = new DefaultClusterView(
- UUID.randomUUID().toString());
+ final DefaultClusterView cluster =
+ new DefaultClusterView(UUID.randomUUID().toString());
final DummyTopologyView view = new DummyTopologyView();
Iterator<String> it = slingIds.iterator();
@@ -759,8 +758,7 @@ public class TestSlingIdCleanupTask {
String localSlignId = leaderSlingId; // and is local too
int idx = 0;
for (String aSlingId : slingIds) {
- view.addInstance(aSlingId, cluster, aSlingId.equals(leaderSlingId),
- aSlingId.equals(localSlignId));
+ view.addInstance(aSlingId, cluster, aSlingId.equals(leaderSlingId), aSlingId.equals(localSlignId));
if (++idx >= activeIds) {
break;
}
@@ -770,15 +768,14 @@ public class TestSlingIdCleanupTask {
assertEquals(0, cleanupTask.getDeleteCount());
assertEquals(0, cleanupTask.getCompletionCount());
waitForRunCount(cleanupTask, 1, 5000);
- assertEquals(Math.max(0, oldIds - Math.max(0, activeIds - recentIds)),
- cleanupTask.getDeleteCount());
+ assertEquals(Math.max(0, oldIds - Math.max(0, activeIds - recentIds)), cleanupTask.getDeleteCount());
assertNoGarbageLeft(instance, config, view, 86400000);
}
- private void assertNoGarbageLeft(VirtualInstance i, Config c,
- TopologyView currentView, long maxAgeMillis) throws Exception {
- List<InstanceDescription> instances = currentView.getLocalInstance()
- .getClusterView().getInstances();
+ private void assertNoGarbageLeft(VirtualInstance i, Config c, TopologyView currentView, long maxAgeMillis)
+ throws Exception {
+ List<InstanceDescription> instances =
+ currentView.getLocalInstance().getClusterView().getInstances();
Set<String> activeIds = new HashSet<>();
for (InstanceDescription id : instances) {
activeIds.add(id.getSlingId());
@@ -789,12 +786,9 @@ public class TestSlingIdCleanupTask {
ResourceResolver resolver = null;
resolver = f.getServiceResourceResolver(null);
- final Resource clusterInstances = ResourceHelper.getOrCreateResource(resolver,
- c.getClusterInstancesPath());
- final Resource idMap = ResourceHelper.getOrCreateResource(resolver,
- c.getIdMapPath());
- final Resource syncTokens = ResourceHelper.getOrCreateResource(resolver,
- c.getSyncTokenPath());
+ final Resource clusterInstances = ResourceHelper.getOrCreateResource(resolver, c.getClusterInstancesPath());
+ final Resource idMap = ResourceHelper.getOrCreateResource(resolver, c.getIdMapPath());
+ final Resource syncTokens = ResourceHelper.getOrCreateResource(resolver, c.getSyncTokenPath());
resolver.refresh();
final ValueMap idMapMap = idMap.adaptTo(ValueMap.class);
@@ -841,11 +835,11 @@ public class TestSlingIdCleanupTask {
return diffMillis > maxAgeMillis;
}
- private void assertCurrentSlingIds(Set<String> slingIds, Set<String> activeIds,
- String context) {
+ private void assertCurrentSlingIds(Set<String> slingIds, Set<String> activeIds, String context) {
for (String aSlingId : slingIds) {
- assertTrue("[" + context + "] stored slingId " + aSlingId
- + " not in current view", activeIds.contains(aSlingId));
+ assertTrue(
+ "[" + context + "] stored slingId " + aSlingId + " not in current view",
+ activeIds.contains(aSlingId));
}
}
@@ -859,13 +853,11 @@ public class TestSlingIdCleanupTask {
*/
private String newLeaderElectionId(String slingId) {
int maxLongLength = String.valueOf(Long.MAX_VALUE).length();
- String currentTimeMillisStr = String.format("%0" + maxLongLength + "d",
- System.currentTimeMillis());
+ String currentTimeMillisStr = String.format("%0" + maxLongLength + "d", System.currentTimeMillis());
String prefix = String.valueOf(config.getLeaderElectionPrefix());
- final String newLeaderElectionId = prefix + "_" + currentTimeMillisStr + "_"
- + slingId;
+ final String newLeaderElectionId = prefix + "_" + currentTimeMillisStr + "_" + slingId;
return newLeaderElectionId;
}
@@ -876,12 +868,10 @@ public class TestSlingIdCleanupTask {
fail("could not login");
return false;
}
- final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver,
- syncTokenPath);
+ final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, syncTokenPath);
final ModifiableValueMap resourceMap = resource.adaptTo(ModifiableValueMap.class);
resourceMap.put(slingId, seqNum);
- logger.info("createSyncToken: storing syncToken: {}, slingId: {}", seqNum,
- slingId);
+ logger.info("createSyncToken: storing syncToken: {}, slingId: {}", seqNum, slingId);
resourceResolver.commit();
return true;
}
@@ -897,8 +887,8 @@ public class TestSlingIdCleanupTask {
resourceResolver.commit();
}
- private boolean createClusterInstance(String uuid, String runtimeId,
- String slingHomePath, String endpointsAsString, Calendar jcrCreated)
+ private boolean createClusterInstance(
+ String uuid, String runtimeId, String slingHomePath, String endpointsAsString, Calendar jcrCreated)
throws Exception {
final String myClusterNodePath = config.getClusterInstancesPath() + "/" + uuid;
ResourceResolver resourceResolver = getResourceResolver();
@@ -908,8 +898,7 @@ public class TestSlingIdCleanupTask {
}
String newLeaderElectionId = newLeaderElectionId(uuid);
- final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver,
- myClusterNodePath);
+ final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, myClusterNodePath);
final ModifiableValueMap resourceMap = resource.adaptTo(ModifiableValueMap.class);
resourceMap.put(PROPERTY_ID_RUNTIME, runtimeId);
@@ -923,16 +912,14 @@ public class TestSlingIdCleanupTask {
logger.info(
"createClusterInstance: storing my runtimeId: {}, endpoints: {}, sling home path: {}, new leaderElectionId: {}, created at: {}",
- new Object[] { runtimeId, endpointsAsString, slingHomePath,
- newLeaderElectionId, jcrCreated });
+ new Object[] {runtimeId, endpointsAsString, slingHomePath, newLeaderElectionId, jcrCreated});
resourceResolver.commit();
return true;
}
private void fillIdMap(Map<String, Long> ids) throws Exception {
ResourceResolver resourceResolver = getResourceResolver();
- final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver,
- config.getIdMapPath());
+ final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, config.getIdMapPath());
ModifiableValueMap idmap = resource.adaptTo(ModifiableValueMap.class);
for (Entry<String, Long> e : ids.entrySet()) {
idmap.put(e.getKey(), e.getValue());
@@ -940,13 +927,12 @@ public class TestSlingIdCleanupTask {
resourceResolver.commit();
}
- private List<String> createSlingIds(int currentIds, int oldIds, int activeOldIds)
- throws Exception {
+ private List<String> createSlingIds(int currentIds, int oldIds, int activeOldIds) throws Exception {
return createSlingIds(currentIds, oldIds, activeOldIds, currentIds + oldIds);
}
- private List<String> createSlingIds(int currentIds, int oldIds, int activeOldIds,
- int numSyncTokens) throws Exception {
+ private List<String> createSlingIds(int currentIds, int oldIds, int activeOldIds, int numSyncTokens)
+ throws Exception {
final List<String> orderedIds = new LinkedList<>();
final Map<String, Long> slingIdToClusterNodeIds = new HashMap<>();
final Map<String, Long> slingIdToSeqNums = new HashMap<>();
@@ -956,8 +942,7 @@ public class TestSlingIdCleanupTask {
orderedIds.add(uuid);
slingIdToClusterNodeIds.put(uuid, i);
slingIdToSeqNums.put(uuid, Long.valueOf(currentSeqNum));
- createClusterInstance(uuid, UUID.randomUUID().toString(), "/a/b/c", "n/a",
- Calendar.getInstance());
+ createClusterInstance(uuid, UUID.randomUUID().toString(), "/a/b/c", "n/a", Calendar.getInstance());
}
for (long i = 0; i < oldIds; i++) {
final String uuid = UUID.randomUUID().toString();
@@ -968,8 +953,7 @@ public class TestSlingIdCleanupTask {
slingIdToSeqNums.put(uuid, Long.valueOf(i));
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -(7 + (int) i));
- createClusterInstance(uuid, UUID.randomUUID().toString(), "/a/b/c", "n/a",
- cal);
+ createClusterInstance(uuid, UUID.randomUUID().toString(), "/a/b/c", "n/a", cal);
}
// idmap is created for all currentIds and active old ids
fillIdMap(slingIdToClusterNodeIds);
@@ -1000,4 +984,4 @@ public class TestSlingIdCleanupTask {
}
return orderedIds;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/discovery/oak/TopologyWebConsolePluginTest.java b/src/test/java/org/apache/sling/discovery/oak/TopologyWebConsolePluginTest.java
index c06927a..d179621 100644
--- a/src/test/java/org/apache/sling/discovery/oak/TopologyWebConsolePluginTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/TopologyWebConsolePluginTest.java
@@ -31,9 +31,10 @@ public class TopologyWebConsolePluginTest {
@Test
/** trivial test that covers the first new Exception catch case */
public void testNoResourceResolverFactory() throws Exception {
- final DefaultClusterView cluster = new DefaultClusterView(UUID.randomUUID().toString());
- final DummyTopologyView view = new DummyTopologyView()
- .addInstance(UUID.randomUUID().toString(), cluster, true, true);
+ final DefaultClusterView cluster =
+ new DefaultClusterView(UUID.randomUUID().toString());
+ final DummyTopologyView view =
+ new DummyTopologyView().addInstance(UUID.randomUUID().toString(), cluster, true, true);
final TopologyWebConsolePlugin p = new TopologyWebConsolePlugin();
p.activate(MockFactory.mockBundleContext());
p.handleTopologyEvent(new TopologyEvent(TopologyEvent.Type.TOPOLOGY_INIT, null, view));
@@ -44,9 +45,10 @@ public class TopologyWebConsolePluginTest {
@Test
/** trivial test that covers the 2nd new Exception catch case */
public void testResourceResolverFactory() throws Exception {
- final DefaultClusterView cluster = new DefaultClusterView(UUID.randomUUID().toString());
- final DummyTopologyView view = new DummyTopologyView()
- .addInstance(UUID.randomUUID().toString(), cluster, true, true);
+ final DefaultClusterView cluster =
+ new DefaultClusterView(UUID.randomUUID().toString());
+ final DummyTopologyView view =
+ new DummyTopologyView().addInstance(UUID.randomUUID().toString(), cluster, true, true);
final TopologyWebConsolePlugin p = new TopologyWebConsolePlugin();
p.resourceResolverFactory = MockFactory.mockResourceResolverFactory();
p.activate(MockFactory.mockBundleContext());
diff --git a/src/test/java/org/apache/sling/discovery/oak/cluster/OakClusterViewServiceTest.java b/src/test/java/org/apache/sling/discovery/oak/cluster/OakClusterViewServiceTest.java
index 1feaecd..adeb744 100644
--- a/src/test/java/org/apache/sling/discovery/oak/cluster/OakClusterViewServiceTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/cluster/OakClusterViewServiceTest.java
@@ -18,11 +18,6 @@
*/
package org.apache.sling.discovery.oak.cluster;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -46,9 +41,17 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
public class OakClusterViewServiceTest {
- enum Speed { SLOW, FAST };
+ enum Speed {
+ SLOW,
+ FAST
+ };
private static final boolean REUSE_CLUSTERNODEID = true;
private static final boolean NEW_CLUSTERNODEID = false;
@@ -75,8 +78,7 @@ public class OakClusterViewServiceTest {
@Test
public void testLocalClusterView() throws Exception {
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barrio/foo/", true)
.setConnectorPingInterval(999)
@@ -92,8 +94,7 @@ public class OakClusterViewServiceTest {
// ok
}
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingInterval(999)
@@ -120,7 +121,7 @@ public class OakClusterViewServiceTest {
// but this should fail as the repository is shutdown
cvs2.getLocalClusterView();
fail("should throw UndefinedClusterViewException");
- } catch(UndefinedClusterViewException e) {
+ } catch (UndefinedClusterViewException e) {
// ok
}
}
@@ -136,9 +137,14 @@ public class OakClusterViewServiceTest {
}
}
- private void doTestRejoining(boolean reuseClusterNodeId, boolean reuseSlingId, Speed speed, int expectedInstanceCount, int expectedEventCount) throws Exception {
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ private void doTestRejoining(
+ boolean reuseClusterNodeId,
+ boolean reuseSlingId,
+ Speed speed,
+ int expectedInstanceCount,
+ int expectedEventCount)
+ throws Exception {
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barrio/foo/", true)
.setConnectorPingInterval(9970)
@@ -153,18 +159,20 @@ public class OakClusterViewServiceTest {
DummyListener listener1 = JoinerDelayTest.newDummyListener(instance1);
// first let instance1 be by its own
- System.out.println("[A] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[A] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
- System.out.println("[B] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[B] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
- System.out.println("[C] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[C] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
assertEquals(1, listener1.countEvents());
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingInterval(9980)
@@ -179,26 +187,35 @@ public class OakClusterViewServiceTest {
ClusterViewService cvs2 = instance2.getClusterViewService();
// join the 2 nodes
- System.out.println("[D] instance 2 heartbeat, slingId = "+ instance2.getSlingId() + ", id = " + builder2.getLease().getClusterNodeId());
+ System.out.println("[D] instance 2 heartbeat, slingId = " + instance2.getSlingId() + ", id = "
+ + builder2.getLease().getClusterNodeId());
instance2.heartbeatsAndCheckView();
- System.out.println("[E] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[E] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
- System.out.println("[E] instance 2 heartbeat, slingId = "+ instance2.getSlingId() + ", id = " + builder2.getLease().getClusterNodeId());
+ System.out.println("[E] instance 2 heartbeat, slingId = " + instance2.getSlingId() + ", id = "
+ + builder2.getLease().getClusterNodeId());
instance2.heartbeatsAndCheckView();
Thread.sleep(1000);
- System.out.println("[F] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[F] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
- System.out.println("[G] instance 2 heartbeat, slingId = "+ instance2.getSlingId() + ", id = " + builder2.getLease().getClusterNodeId());
+ System.out.println("[G] instance 2 heartbeat, slingId = " + instance2.getSlingId() + ", id = "
+ + builder2.getLease().getClusterNodeId());
instance2.heartbeatsAndCheckView();
Thread.sleep(1000);
- System.out.println("[I] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[I] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
- System.out.println("[J] instance 2 heartbeat, slingId = "+ instance2.getSlingId() + ", id = " + builder2.getLease().getClusterNodeId());
+ System.out.println("[J] instance 2 heartbeat, slingId = " + instance2.getSlingId() + ", id = "
+ + builder2.getLease().getClusterNodeId());
instance2.heartbeatsAndCheckView();
Thread.sleep(1000);
- System.out.println("[I] instance 1 heartbeat, slingId = "+ instance1.getSlingId() + ", id = " + builder1.getLease().getClusterNodeId());
+ System.out.println("[I] instance 1 heartbeat, slingId = " + instance1.getSlingId() + ", id = "
+ + builder1.getLease().getClusterNodeId());
instance1.heartbeatsAndCheckView();
- System.out.println("[J] instance 2 heartbeat, slingId = "+ instance2.getSlingId() + ", id = " + builder2.getLease().getClusterNodeId());
+ System.out.println("[J] instance 2 heartbeat, slingId = " + instance2.getSlingId() + ", id = "
+ + builder2.getLease().getClusterNodeId());
instance2.heartbeatsAndCheckView();
assertEquals(3, listener1.countEvents());
@@ -206,8 +223,7 @@ public class OakClusterViewServiceTest {
assertEquals(2, cvs1.getLocalClusterView().getInstances().size());
assertEquals(2, cvs2.getLocalClusterView().getInstances().size());
- final OakVirtualInstanceBuilder builder2b =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ final OakVirtualInstanceBuilder builder2b = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2b")
.useRepositoryOf(instance1)
.setConnectorPingInterval(9990)
@@ -235,8 +251,8 @@ public class OakClusterViewServiceTest {
builder2.getLease().deactivate();
// now step 1 is to join through the leases, without yet doing the syncToken thingy
- SimulatedLeaseCollection c = builder2b.getSimulatedLeaseCollection();//new
- c.incSeqNum(2);//new
+ SimulatedLeaseCollection c = builder2b.getSimulatedLeaseCollection(); // new
+ c.incSeqNum(2); // new
System.out.println();
System.out.println(" UPDATING SEQ NUM TO " + c.getSeqNum());
System.out.println();
@@ -305,7 +321,6 @@ public class OakClusterViewServiceTest {
lastAsyncException.set(e);
}
}
-
};
Thread th = new Thread(r2bb);
th.start();
@@ -316,9 +331,13 @@ public class OakClusterViewServiceTest {
instance1.heartbeatsAndCheckView();
Thread.sleep(1000);
- System.out.println("instance 1 is " + instance1.getSlingId() + " - " + builder1.getLease().getClusterNodeId() + " - " + builder1.getLease());
- System.out.println("instance 2 is " + instance2.getSlingId() + " - " + builder2.getLease().getClusterNodeId() + " - " + builder2.getLease());
- if (speed == Speed.FAST) System.out.println("instance 2b is " + instance2bRef.get().getSlingId() + " - " + builder2b.getLease().getClusterNodeId() + " - " + builder2b.getLease());
+ System.out.println("instance 1 is " + instance1.getSlingId() + " - "
+ + builder1.getLease().getClusterNodeId() + " - " + builder1.getLease());
+ System.out.println("instance 2 is " + instance2.getSlingId() + " - "
+ + builder2.getLease().getClusterNodeId() + " - " + builder2.getLease());
+ if (speed == Speed.FAST)
+ System.out.println("instance 2b is " + instance2bRef.get().getSlingId() + " - "
+ + builder2b.getLease().getClusterNodeId() + " - " + builder2b.getLease());
final Set<InstanceDescription> instances = listener1.getLastView().getInstances();
for (InstanceDescription id : instances) {
System.out.println("id " + id);
@@ -340,7 +359,14 @@ public class OakClusterViewServiceTest {
instance1.heartbeatsAndCheckView();
instance2bRef.get().heartbeatsAndCheckView();
assertEquals(2, cvs1.getLocalClusterView().getInstances().size());
- assertEquals(2, instance2bRef.get().getClusterViewService().getLocalClusterView().getInstances().size());
+ assertEquals(
+ 2,
+ instance2bRef
+ .get()
+ .getClusterViewService()
+ .getLocalClusterView()
+ .getInstances()
+ .size());
instance1.shutdownRepository();
}
@@ -417,7 +443,11 @@ public class OakClusterViewServiceTest {
*/
@Test
public void testRejoining_newClusterNodeId_reuseSlingId_slow() throws Exception {
- doTestRejoining(NEW_CLUSTERNODEID, REUSE_SLINGID, Speed.SLOW, 1/* only instance1 remaining*/,
+ doTestRejoining(
+ NEW_CLUSTERNODEID,
+ REUSE_SLINGID,
+ Speed.SLOW,
+ 1 /* only instance1 remaining*/,
5 /* kicks out instance2, no new instance, but a stable topology*/);
}
@@ -427,14 +457,17 @@ public class OakClusterViewServiceTest {
*/
@Test
public void testRejoining_newClusterNodeId_newSlingId_slow() throws Exception {
- doTestRejoining(NEW_CLUSTERNODEID, NEW_SLINGID, Speed.SLOW, 1 /* only instance1 remaining*/,
+ doTestRejoining(
+ NEW_CLUSTERNODEID,
+ NEW_SLINGID,
+ Speed.SLOW,
+ 1 /* only instance1 remaining*/,
5 /* kicks out instance2, no new instance, but a stable topology*/);
}
@Test
public void testSuppression() throws Exception {
- OakVirtualInstanceBuilder builder1 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance1")
.newRepository("/foo/barrio/foo/", true)
.setConnectorPingInterval(999)
@@ -447,8 +480,7 @@ public class OakClusterViewServiceTest {
VirtualInstance instance1 = builder1.build();
ClusterViewService cvs1 = instance1.getClusterViewService();
- OakVirtualInstanceBuilder builder2 =
- (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
+ OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder()
.setDebugName("instance2")
.useRepositoryOf(instance1)
.setConnectorPingInterval(999)
@@ -484,7 +516,6 @@ public class OakClusterViewServiceTest {
public void run() {
syncDone.set(true);
}
-
});
s.cancelSync();
assertFalse(syncDone.get());
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/OakClusterLoadTest.java b/src/test/java/org/apache/sling/discovery/oak/its/OakClusterLoadTest.java
index 5ce0636..73326b5 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/OakClusterLoadTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/OakClusterLoadTest.java
@@ -28,5 +28,4 @@ public class OakClusterLoadTest extends AbstractClusterLoadTest {
public VirtualInstanceBuilder newBuilder() {
return new OakVirtualInstanceBuilder();
}
-
}
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/OakClusterTest.java b/src/test/java/org/apache/sling/discovery/oak/its/OakClusterTest.java
index 1d4e5df..544274d 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/OakClusterTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/OakClusterTest.java
@@ -28,5 +28,4 @@ public class OakClusterTest extends AbstractClusterTest {
protected VirtualInstanceBuilder newBuilder() {
return new OakVirtualInstanceBuilder();
}
-
}
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/OakDiscoveryServiceTest.java b/src/test/java/org/apache/sling/discovery/oak/its/OakDiscoveryServiceTest.java
index d1ff26f..d7abad4 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/OakDiscoveryServiceTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/OakDiscoveryServiceTest.java
@@ -18,10 +18,6 @@
*/
package org.apache.sling.discovery.oak.its;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
import org.apache.log4j.Level;
import org.apache.log4j.spi.RootLogger;
import org.apache.sling.discovery.TopologyEvent.Type;
@@ -38,6 +34,10 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -65,12 +65,12 @@ public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
public void teartDown() throws Throwable {
final org.apache.log4j.Logger discoveryLogger = RootLogger.getLogger("org.apache.sling.discovery");
discoveryLogger.setLevel(logLevel);
- if (instance1!=null) {
+ if (instance1 != null) {
instance1.stopViewChecker();
instance1.stop();
instance1 = null;
}
- if (instance2!=null) {
+ if (instance2 != null) {
instance2.stopViewChecker();
instance2.stop();
instance2 = null;
@@ -93,14 +93,14 @@ public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
.setMinEventDelay(3 /*min event delay*/);
instance1 = builder.build();
instance1.stopViewChecker();
-// instance1.stopVoting();
+ // instance1.stopVoting();
TopologyView t1 = instance1.getDiscoveryService().getTopology();
assertFalse(t1.isCurrent()); // current it should not be
assertEquals(1, t1.getInstances().size()); // but it can as well contain the local instance
AssertingTopologyEventListener l1 = new AssertingTopologyEventListener("instance1.l1");
l1.addExpected(Type.TOPOLOGY_INIT);
instance1.bindTopologyEventListener(l1);
- logger.info("testOldView: instance1 created, no events expected yet. slingId="+instance1.slingId);
+ logger.info("testOldView: instance1 created, no events expected yet. slingId=" + instance1.slingId);
instance1.heartbeatsAndCheckView();
Thread.sleep(200);
instance1.heartbeatsAndCheckView();
@@ -126,9 +126,10 @@ public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
.setMinEventDelay(3);
instance2 = builder2.build();
instance2.stopViewChecker();
-// instance2.stopVoting();
+ // instance2.stopVoting();
- logger.info("testOldView: instance2 created, now issuing one heartbeat with instance2 first, so that instance1 can take note of it");
+ logger.info(
+ "testOldView: instance2 created, now issuing one heartbeat with instance2 first, so that instance1 can take note of it");
instance2.getViewChecker().checkView();
OakDiscoveryService oakDisco1 = (OakDiscoveryService) instance2.getDiscoveryService();
oakDisco1.checkForTopologyChange();
@@ -152,9 +153,9 @@ public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
logger.info("testOldView: now issuing 3 rounds of heartbeats/checks and expecting a TOPOLOGY_CHANGED then");
instance2.heartbeatsAndCheckView();
-// instance2.analyzeVotings();
+ // instance2.analyzeVotings();
instance1.heartbeatsAndCheckView();
-// instance1.analyzeVotings();
+ // instance1.analyzeVotings();
Thread.sleep(1200);
instance2.heartbeatsAndCheckView();
instance1.heartbeatsAndCheckView();
@@ -174,7 +175,7 @@ public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
// to let instance2 crash
builder.getSimulatedLeaseCollection().setFinal(false);
l1.addExpected(Type.TOPOLOGY_CHANGING);
- for(int i=0; i<8; i++) {
+ for (int i = 0; i < 8; i++) {
instance1.heartbeatsAndCheckView();
Thread.sleep(500);
}
@@ -185,5 +186,4 @@ public class OakDiscoveryServiceTest extends AbstractDiscoveryServiceTest {
assertFalse(t1.isCurrent()); // and we should be current again
assertEquals(2, t1.getInstances().size()); // and contain both instances now
}
-
}
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/OakSingleInstanceTest.java b/src/test/java/org/apache/sling/discovery/oak/its/OakSingleInstanceTest.java
index c0e5499..f10a315 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/OakSingleInstanceTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/OakSingleInstanceTest.java
@@ -28,5 +28,4 @@ public class OakSingleInstanceTest extends AbstractSingleInstanceTest {
protected VirtualInstanceBuilder newBuilder() {
return new OakVirtualInstanceBuilder();
}
-
}
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/OakTopologyEventTest.java b/src/test/java/org/apache/sling/discovery/oak/its/OakTopologyEventTest.java
index 3b033a2..13b3615 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/OakTopologyEventTest.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/OakTopologyEventTest.java
@@ -18,13 +18,13 @@
*/
package org.apache.sling.discovery.oak.its;
-import static org.junit.Assert.assertNotNull;
-
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.discovery.base.its.AbstractTopologyEventTest;
import org.apache.sling.discovery.base.its.setup.VirtualInstanceBuilder;
import org.apache.sling.discovery.oak.its.setup.OakVirtualInstanceBuilder;
+import static org.junit.Assert.assertNotNull;
+
public class OakTopologyEventTest extends AbstractTopologyEventTest {
@Override
@@ -39,5 +39,4 @@ public class OakTopologyEventTest extends AbstractTopologyEventTest {
assertNotNull(earlyTopo);
assertNotNull(secondTopo);
}
-
}
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/setup/OakTestConfig.java b/src/test/java/org/apache/sling/discovery/oak/its/setup/OakTestConfig.java
index 8fa7844..c1ffb20 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/setup/OakTestConfig.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/setup/OakTestConfig.java
@@ -28,7 +28,7 @@ public class OakTestConfig extends Config implements ModifiableTestBaseConfig {
public OakTestConfig() {
// empty
}
-
+
public void setDiscoveryResourcePath(String discoveryResourcePath) {
this.discoveryResourcePath = discoveryResourcePath;
}
@@ -38,13 +38,13 @@ public class OakTestConfig extends Config implements ModifiableTestBaseConfig {
}
public void addTopologyConnectorWhitelistEntry(String whitelistEntry) {
- if (topologyConnectorWhitelist==null) {
+ if (topologyConnectorWhitelist == null) {
topologyConnectorWhitelist = new String[] {whitelistEntry};
} else {
String[] list = topologyConnectorWhitelist;
- topologyConnectorWhitelist = new String[list.length+1];
+ topologyConnectorWhitelist = new String[list.length + 1];
System.arraycopy(list, 0, topologyConnectorWhitelist, 0, list.length);
- topologyConnectorWhitelist[topologyConnectorWhitelist.length-1] = whitelistEntry;
+ topologyConnectorWhitelist[topologyConnectorWhitelist.length - 1] = whitelistEntry;
}
}
@@ -65,7 +65,7 @@ public class OakTestConfig extends Config implements ModifiableTestBaseConfig {
public void setConnectorTimeout(long connectorTimeout) {
this.connectorPingTimeout = connectorTimeout;
}
-
+
@Override
public void setViewCheckTimeout(int viewCheckTimeout) {
setConnectorTimeout(viewCheckTimeout);
@@ -75,7 +75,7 @@ public class OakTestConfig extends Config implements ModifiableTestBaseConfig {
public void setViewCheckInterval(int viewCheckInterval) {
setConnectorInterval(viewCheckInterval);
}
-
+
public long getViewCheckerTimeout() {
return connectorPingTimeout;
}
@@ -104,4 +104,4 @@ public class OakTestConfig extends Config implements ModifiableTestBaseConfig {
public void setDiscoveryLiteCheckInterval(int discoveryLiteCheckInterval) {
this.discoveryLiteCheckInterval = discoveryLiteCheckInterval;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/setup/OakVirtualInstanceBuilder.java b/src/test/java/org/apache/sling/discovery/oak/its/setup/OakVirtualInstanceBuilder.java
index 6ee188e..f31f65d 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/setup/OakVirtualInstanceBuilder.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/setup/OakVirtualInstanceBuilder.java
@@ -18,10 +18,9 @@
*/
package org.apache.sling.discovery.oak.its.setup;
-import static org.junit.Assert.fail;
-
import javax.jcr.Session;
+import junitx.util.PrivateAccessor;
import org.apache.jackrabbit.api.JackrabbitRepository;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
@@ -44,7 +43,7 @@ import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import junitx.util.PrivateAccessor;
+import static org.junit.Assert.fail;
public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
@@ -74,9 +73,9 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
@Override
public VirtualInstanceBuilder useRepositoryOf(VirtualInstanceBuilder other) throws Exception {
if (!(other instanceof OakVirtualInstanceBuilder)) {
- throw new IllegalArgumentException("other must be of type OakVirtualInstanceBuilder but is: "+other);
+ throw new IllegalArgumentException("other must be of type OakVirtualInstanceBuilder but is: " + other);
}
- OakVirtualInstanceBuilder otherOakbuilder = (OakVirtualInstanceBuilder)other;
+ OakVirtualInstanceBuilder otherOakbuilder = (OakVirtualInstanceBuilder) other;
nodeStore = otherOakbuilder.nodeStore;
JackrabbitRepository jcrRepo = (JackrabbitRepository) RepositoryTestHelper.createOakRepository(nodeStore);
factory = MockFactory.mockResourceResolverFactory(jcrRepo);
@@ -98,7 +97,7 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
}
public IdMapService getIdMapService() {
- if (idMapService==null) {
+ if (idMapService == null) {
idMapService = createIdMapService();
}
return idMapService;
@@ -110,11 +109,12 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
@Override
protected ClusterViewService createClusterViewService() {
- return OakClusterViewService.testConstructor(getSlingSettingsService(), getResourceResolverFactory(), getIdMapService(), getConfig());
+ return OakClusterViewService.testConstructor(
+ getSlingSettingsService(), getResourceResolverFactory(), getIdMapService(), getConfig());
}
public OakTestConfig getConfig() {
- if (config==null) {
+ if (config == null) {
config = createConfig();
}
return config;
@@ -155,7 +155,7 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
try {
getLease().updateDescriptor(getConfig());
} catch (Exception e) {
- logger.error("run: could not update lease: "+e);
+ logger.error("run: could not update lease: " + e);
}
}
@@ -165,19 +165,19 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
@Override
public void heartbeatAndCheckView() {
-// next step is try to simulate the logic
-// where no heartbeat means no descriptor yet
-// one heartbeat means i'm visible for others
-// as soon as I see others the descriptor is updated
+ // next step is try to simulate the logic
+ // where no heartbeat means no descriptor yet
+ // one heartbeat means i'm visible for others
+ // as soon as I see others the descriptor is updated
try {
getLease().updateLeaseAndDescriptor(getConfig());
} catch (Exception e) {
- logger.error("run: could not update lease: "+e, e);
+ logger.error("run: could not update lease: " + e, e);
}
- try{
+ try {
getOakViewChecker().run();
- } catch(Exception e) {
- logger.error("run: could not ping: "+e, e);
+ } catch (Exception e) {
+ logger.error("run: could not ping: " + e, e);
}
if (!getIdMapService().isInitialized()) {
if (!getIdMapService().waitForInit(1500)) {
@@ -189,14 +189,20 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
}
private OakViewChecker getOakViewChecker() throws Exception {
- if (oakViewChecker==null) {
- oakViewChecker = createOakViewChecker() ;
+ if (oakViewChecker == null) {
+ oakViewChecker = createOakViewChecker();
}
return oakViewChecker;
}
private OakViewChecker createOakViewChecker() throws Exception {
- return OakViewChecker.testConstructor(getSlingSettingsService(), getResourceResolverFactory(), getConnectorRegistry(), getAnnouncementRegistry(), getScheduler(), getConfig());
+ return OakViewChecker.testConstructor(
+ getSlingSettingsService(),
+ getResourceResolverFactory(),
+ getConnectorRegistry(),
+ getAnnouncementRegistry(),
+ getScheduler(),
+ getConfig());
}
private OakBacklogClusterSyncService getOakBacklogClusterSyncService() throws Exception {
@@ -207,7 +213,8 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
}
private OakBacklogClusterSyncService createOakBacklogClusterSyncService() {
- return OakBacklogClusterSyncService.testConstructorAndActivate(getConfig(), getIdMapService(), getSlingSettingsService(), getResourceResolverFactory());
+ return OakBacklogClusterSyncService.testConstructorAndActivate(
+ getConfig(), getIdMapService(), getSlingSettingsService(), getResourceResolverFactory());
}
public SyncTokenService getSyncTokenService() throws Exception {
@@ -218,7 +225,8 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
}
protected SyncTokenService createSyncTokenService() {
- return SyncTokenService.testConstructorAndActivate(getConfig(), getResourceResolverFactory(), getSlingSettingsService());
+ return SyncTokenService.testConstructorAndActivate(
+ getConfig(), getResourceResolverFactory(), getSlingSettingsService());
}
@Override
@@ -239,7 +247,7 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
@Override
public VirtualInstance build() throws Exception {
- if (path==null) {
+ if (path == null) {
if (ownRepository) {
setPath("/var/discovery/impl/");
getConfig().setDiscoveryResourcePath("/var/discovery/impl/");
@@ -249,14 +257,14 @@ public class OakVirtualInstanceBuilder extends VirtualInstanceBuilder {
getConfig().setDiscoveryResourcePath(other.path);
}
}
- if (path==null) {
+ if (path == null) {
throw new IllegalStateException("no path set");
}
if (!path.startsWith("/")) {
- throw new IllegalStateException("path must start with /: "+path);
+ throw new IllegalStateException("path must start with /: " + path);
}
if (!path.endsWith("/")) {
- throw new IllegalStateException("path must end with /: "+path);
+ throw new IllegalStateException("path must end with /: " + path);
}
VirtualInstance result = new VirtualInstance(this) {
@Override
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLease.java b/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLease.java
index 32038fc..a88851e 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLease.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLease.java
@@ -29,20 +29,18 @@ public class SimulatedLease {
private final String slingId;
private int clusterNodeIdHint = -1;
- public SimulatedLease(ResourceResolverFactory factory,
- SimulatedLeaseCollection collection,
- String slingId) {
+ public SimulatedLease(ResourceResolverFactory factory, SimulatedLeaseCollection collection, String slingId) {
this.factory = factory;
this.collection = collection;
collection.hooked(this);
this.slingId = slingId;
}
-
+
@Override
public String toString() {
- return "a SimulatedLease[slingId="+slingId+"]";
+ return "a SimulatedLease[slingId=" + slingId + "]";
}
-
+
public String getSlingId() {
return slingId;
}
@@ -51,7 +49,7 @@ public class SimulatedLease {
DiscoveryLiteDescriptorBuilder builder = collection.getDescriptorFor(this, config);
DescriptorHelper.setDiscoveryLiteDescriptor(factory, builder);
}
-
+
public void updateLeaseAndDescriptor(OakTestConfig config) throws Exception {
DiscoveryLiteDescriptorBuilder builder = collection.updateAndGetDescriptorFor(this, config);
DescriptorHelper.setDiscoveryLiteDescriptor(factory, builder);
diff --git a/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLeaseCollection.java b/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLeaseCollection.java
index 4aea737..3034995 100644
--- a/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLeaseCollection.java
+++ b/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLeaseCollection.java
@@ -29,43 +29,41 @@ import org.apache.sling.discovery.commons.providers.spi.base.DiscoveryLiteDescri
public class SimulatedLeaseCollection {
- private final Map<String,Long> leaseUpdates =
- new HashMap<String, Long>();
-
- private final Map<String,Integer> clusterNodeIds =
- new HashMap<String, Integer>();
-
+ private final Map<String, Long> leaseUpdates = new HashMap<String, Long>();
+
+ private final Map<String, Integer> clusterNodeIds = new HashMap<String, Integer>();
+
private int highestId = 0;
-
+
private final String viewId = UUID.randomUUID().toString();
-
+
List<SimulatedLease> leases = new LinkedList<SimulatedLease>();
private volatile boolean isFinal = true;
private int seqNum = 0;
-
+
public SimulatedLeaseCollection() {
// empty
}
-
+
public int getSeqNum() {
return seqNum;
}
-
+
public void setSeqNum(int seqNum) {
this.seqNum = seqNum;
}
-
+
public void incSeqNum() {
seqNum++;
}
-
+
public void incSeqNum(int amount) {
- if (amount<=0) {
- throw new IllegalArgumentException("amount must be >0, is: "+amount);
+ if (amount <= 0) {
+ throw new IllegalArgumentException("amount must be >0, is: " + amount);
}
- seqNum+=amount;
+ seqNum += amount;
}
public synchronized void hooked(SimulatedLease lease) {
@@ -74,25 +72,28 @@ public class SimulatedLeaseCollection {
public synchronized void unhooked(SimulatedLease lease) {
if (!leases.remove(lease)) {
- throw new IllegalStateException("could not unhook lease : " + lease.getClusterNodeIdHint() + "/" + lease.getSlingId());
+ throw new IllegalStateException(
+ "could not unhook lease : " + lease.getClusterNodeIdHint() + "/" + lease.getSlingId());
}
}
- public synchronized DiscoveryLiteDescriptorBuilder getDescriptorFor(SimulatedLease simulatedLease, OakTestConfig config) {
+ public synchronized DiscoveryLiteDescriptorBuilder getDescriptorFor(
+ SimulatedLease simulatedLease, OakTestConfig config) {
return doUpdateAndGet(simulatedLease, config, false);
}
-
- public synchronized DiscoveryLiteDescriptorBuilder updateAndGetDescriptorFor(SimulatedLease simulatedLease, OakTestConfig config) {
+
+ public synchronized DiscoveryLiteDescriptorBuilder updateAndGetDescriptorFor(
+ SimulatedLease simulatedLease, OakTestConfig config) {
return doUpdateAndGet(simulatedLease, config, true);
}
- private DiscoveryLiteDescriptorBuilder doUpdateAndGet(SimulatedLease simulatedLease, OakTestConfig config, boolean updateLease) {
+ private DiscoveryLiteDescriptorBuilder doUpdateAndGet(
+ SimulatedLease simulatedLease, OakTestConfig config, boolean updateLease) {
int clusterNodeId = getClusterNodeId(simulatedLease);
if (updateLease) {
leaseUpdates.put(simulatedLease.getSlingId(), System.currentTimeMillis());
}
- DiscoveryLiteDescriptorBuilder discoBuilder =
- new DiscoveryLiteDescriptorBuilder();
+ DiscoveryLiteDescriptorBuilder discoBuilder = new DiscoveryLiteDescriptorBuilder();
discoBuilder.me(clusterNodeId);
discoBuilder.id(viewId);
discoBuilder.setFinal(isFinal);
@@ -130,7 +131,7 @@ public class SimulatedLeaseCollection {
private int getClusterNodeId(String slingId, int idHint) {
Integer id = clusterNodeIds.get(slingId);
- if (id==null) {
+ if (id == null) {
if (idHint != -1) {
// try to respect the hint
boolean alreadyInUse = false;
@@ -146,7 +147,7 @@ public class SimulatedLeaseCollection {
}
}
}
- if (id==null) {
+ if (id == null) {
id = ++highestId;
clusterNodeIds.put(slingId, id);
}
@@ -166,5 +167,4 @@ public class SimulatedLeaseCollection {
clusterNodeIds.remove(simulatedLease.getSlingId());
incSeqNum();
}
-
}
(sling-org-apache-sling-discovery-oak) 01/02: SLING-12559 Update to parent 62
Posted by ss...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sseifert pushed a commit to branch feature/SLING-12559-parent-62
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-discovery-oak.git
commit 0e7eb0e10f2437d7393d24da7d3310b996c7601e
Author: Stefan Seifert <st...@users.noreply.github.com>
AuthorDate: Thu Dec 12 15:56:34 2024 +0100
SLING-12559 Update to parent 62
---
.sling-module.json | 5 ++++
pom.xml | 83 +++++++++++++-----------------------------------------
2 files changed, 24 insertions(+), 64 deletions(-)
diff --git a/.sling-module.json b/.sling-module.json
new file mode 100644
index 0000000..cfad4d2
--- /dev/null
+++ b/.sling-module.json
@@ -0,0 +1,5 @@
+{
+ "jenkins": {
+ "jdks": [17, 21]
+ }
+}
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index fc7f59b..c5a573f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.sling</groupId>
<artifactId>sling-bundle-parent</artifactId>
- <version>48</version>
+ <version>62</version>
<relativePath />
</parent>
@@ -53,7 +53,6 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
- <version>0.8.6</version>
<executions>
<execution>
<id>prepare-agent</id>
@@ -76,68 +75,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
- <version>3.0.0-M4</version>
<configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
<argLine>${jacoco.command} -Xmx2048m</argLine>
<excludedGroups>${sling.excluded.surefire.groups}</excludedGroups>
</configuration>
</plugin>
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>set-bundle-required-execution-environment</id>
- <phase>initialize</phase>
- <goals>
- <goal>run</goal>
- </goals>
- <configuration>
- <exportAntProperties>true</exportAntProperties>
- <target>
- <!-- apply fix as suggested in this comment:
- https://issues.apache.org/jira/browse/MANTRUN-200?focusedCommentId=17016706&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17016706 -->
- <property name="plugin_classpath" refid="maven.plugin.classpath" />
- <script language="javascript" classpath="${plugin_classpath}">var System = java.lang.System;
- var bree = "JavaSE-1.6";
- var animalSnifferSignaturesVersion = "6";
- var slingJavaVersion = System.getProperty("sling.java.version");
- if (!slingJavaVersion) {
- slingJavaVersion = project.getProperty("sling.java.version");
- }
- if (slingJavaVersion == "7") {
- animalSnifferSignaturesVersion = "7";
- bree = "JavaSE-1.7";
- System.out.println("Setting Bundle-RequiredExecutionEnvironment=" + bree + " from sling.java.version=" + slingJavaVersion);
- } else if ( slingJavaVersion == "8") {
- animalSnifferSignaturesVersion = "8";
- bree = "JavaSE-1.8";
- System.out.println("Setting Bundle-RequiredExecutionEnvironment=" + bree + " from sling.java.version=" + slingJavaVersion);
- } else if (slingJavaVersion != "6") {
- System.out.println("Unsupported sling.java.version=" + slingJavaVersion + "; must be 6, 7 or 8.");
- throw "sling.java.version must be 6, 7 or 8";
- }
- project.setProperty("sling.bree", bree);
- project.setProperty("sling.animalSignatures.version", animalSnifferSignaturesVersion);</script>
- </target>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant-apache-regexp</artifactId>
- <version>1.7.1</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>jakarta-regexp</groupId>
- <artifactId>jakarta-regexp</artifactId>
- <version>1.4</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- </plugin>
</plugins>
</build>
<profiles>
@@ -159,7 +102,12 @@
</dependency>
<dependency>
<groupId>org.osgi</groupId>
- <artifactId>osgi.core</artifactId>
+ <artifactId>org.osgi.framework</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
@@ -286,6 +234,18 @@
<version>3.3</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.healthcheck.api</artifactId>
+ <version>2.0.0</version>
+ <scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.osgi</groupId>
+ <artifactId>osgi.core</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
<!-- Testing -->
<dependency>
@@ -395,11 +355,6 @@
<version>${oak.version}</version>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.healthcheck.api</artifactId>
- <version>2.0.0</version>
- </dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.commons.johnzon</artifactId>