This is an automated email from the ASF dual-hosted git repository. kwin pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-i18n.git
commit 8bb567187653f5974cc865bff714b7fdffecd5d0 Author: Konrad Windszus <[email protected]> AuthorDate: Thu Aug 29 10:18:26 2024 +0200 SLING-12416 Formatting with spotless-m-p --- pom.xml | 116 ++++++------- .../apache/sling/i18n/DefaultLocaleResolver.java | 6 +- .../java/org/apache/sling/i18n/LocaleResolver.java | 1 - .../apache/sling/i18n/RequestLocaleResolver.java | 5 +- .../apache/sling/i18n/ResourceBundleProvider.java | 1 - .../java/org/apache/sling/i18n/impl/Config.java | 43 +++-- .../org/apache/sling/i18n/impl/I18NFilter.java | 110 ++++++------ .../apache/sling/i18n/impl/JcrResourceBundle.java | 61 ++++--- .../sling/i18n/impl/JcrResourceBundleProvider.java | 193 ++++++++++++--------- .../org/apache/sling/i18n/impl/LocatorPaths.java | 48 +++-- .../sling/i18n/impl/LocatorPathsTracker.java | 44 ++--- .../sling/i18n/impl/LocatorPathsVisitor.java | 5 +- .../org/apache/sling/i18n/impl/PathFilter.java | 2 +- .../i18n/impl/PotentialLanguageRootCheck.java | 7 +- .../sling/i18n/impl/ResourceBundleEnumeration.java | 18 +- .../java/org/apache/sling/i18n/package-info.java | 2 - .../ConcurrentJcrResourceBundleLoadingTest.java | 79 +++++---- .../i18n/impl/JcrResourceBundleProviderTest.java | 38 ++-- .../impl/JcrResourceBundleProvider_KeyTest.java | 6 +- .../sling/i18n/impl/JcrResourceBundleTest.java | 48 ++--- .../apache/sling/i18n/impl/LocatorPathsTest.java | 6 +- .../java/org/apache/sling/i18n/impl/Message.java | 1 - .../org/apache/sling/i18n/impl/PathFilterTest.java | 4 +- .../org/apache/sling/i18n/it/I18nTestSupport.java | 42 +++-- .../sling/i18n/it/ResourceBundleLocatorIT.java | 104 ++++++----- .../sling/i18n/it/ResourceBundleProviderIT.java | 16 +- 26 files changed, 545 insertions(+), 461 deletions(-) diff --git a/pom.xml b/pom.xml index 6df012d..ae9093e 100644 --- a/pom.xml +++ b/pom.xml @@ -34,6 +34,13 @@ <name>Apache Sling I18N Support</name> <description>Support for creating Java I18N ResourceBundles from repository resources.</description> + <scm> + <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-i18n.git</connection> + <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-i18n.git</developerConnection> + <tag>HEAD</tag> + <url>https://github.com/apache/sling-org-apache-sling-i18n.git</url> + </scm> + <properties> <project.build.outputTimestamp>2024-08-20T12:35:28Z</project.build.outputTimestamp> <org.ops4j.pax.exam.version>4.13.3</org.ops4j.pax.exam.version> @@ -42,65 +49,6 @@ <sling.java.version>8</sling.java.version> </properties> - <scm> - <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-i18n.git</connection> - <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-i18n.git</developerConnection> - <url>https://github.com/apache/sling-org-apache-sling-i18n.git</url> - <tag>HEAD</tag> - </scm> - - <build> - <plugins> - <plugin> - <groupId>org.apache.rat</groupId> - <artifactId>apache-rat-plugin</artifactId> - <configuration> - <excludes> - <exclude>**/*.json.props</exclude> - </excludes> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <configuration> - <excludePackageNames> - org.apache.sling.i18n.impl - </excludePackageNames> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - <configuration> - <redirectTestOutputToFile>true</redirectTestOutputToFile> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-failsafe-plugin</artifactId> - <executions> - <execution> - <goals> - <goal>integration-test</goal> - <goal>verify</goal> - </goals> - </execution> - </executions> - <configuration> - <redirectTestOutputToFile>true</redirectTestOutputToFile> - <systemPropertyVariables> - <bundle.filename>${basedir}/target/${project.build.finalName}.jar</bundle.filename> - </systemPropertyVariables> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.servicemix.tooling</groupId> - <artifactId>depends-maven-plugin</artifactId> - </plugin> - </plugins> - </build> - <dependencies> <!-- javax --> <dependency> @@ -287,4 +235,54 @@ <scope>test</scope> </dependency> </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.rat</groupId> + <artifactId>apache-rat-plugin</artifactId> + <configuration> + <excludes> + <exclude>**/*.json.props</exclude> + </excludes> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <configuration> + <excludePackageNames>org.apache.sling.i18n.impl</excludePackageNames> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <redirectTestOutputToFile>true</redirectTestOutputToFile> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-failsafe-plugin</artifactId> + <configuration> + <redirectTestOutputToFile>true</redirectTestOutputToFile> + <systemPropertyVariables> + <bundle.filename>${basedir}/target/${project.build.finalName}.jar</bundle.filename> + </systemPropertyVariables> + </configuration> + <executions> + <execution> + <goals> + <goal>integration-test</goal> + <goal>verify</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.servicemix.tooling</groupId> + <artifactId>depends-maven-plugin</artifactId> + </plugin> + </plugins> + </build> </project> diff --git a/src/main/java/org/apache/sling/i18n/DefaultLocaleResolver.java b/src/main/java/org/apache/sling/i18n/DefaultLocaleResolver.java index 4d0ec95..94f1935 100644 --- a/src/main/java/org/apache/sling/i18n/DefaultLocaleResolver.java +++ b/src/main/java/org/apache/sling/i18n/DefaultLocaleResolver.java @@ -18,13 +18,13 @@ */ package org.apache.sling.i18n; +import javax.servlet.http.HttpServletRequest; + import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Locale; -import javax.servlet.http.HttpServletRequest; - import org.apache.sling.api.SlingHttpServletRequest; /** @@ -41,7 +41,7 @@ public class DefaultLocaleResolver implements LocaleResolver, RequestLocaleResol * <code>List</code>. */ public List<Locale> resolveLocale(final SlingHttpServletRequest request) { - return this.resolveLocale((HttpServletRequest)request); + return this.resolveLocale((HttpServletRequest) request); } /** diff --git a/src/main/java/org/apache/sling/i18n/LocaleResolver.java b/src/main/java/org/apache/sling/i18n/LocaleResolver.java index d031d91..8937c7b 100644 --- a/src/main/java/org/apache/sling/i18n/LocaleResolver.java +++ b/src/main/java/org/apache/sling/i18n/LocaleResolver.java @@ -53,5 +53,4 @@ public interface LocaleResolver { * of request processing */ List<Locale> resolveLocale(SlingHttpServletRequest request); - } diff --git a/src/main/java/org/apache/sling/i18n/RequestLocaleResolver.java b/src/main/java/org/apache/sling/i18n/RequestLocaleResolver.java index 75b1205..898ecda 100644 --- a/src/main/java/org/apache/sling/i18n/RequestLocaleResolver.java +++ b/src/main/java/org/apache/sling/i18n/RequestLocaleResolver.java @@ -18,11 +18,11 @@ */ package org.apache.sling.i18n; +import javax.servlet.http.HttpServletRequest; + import java.util.List; import java.util.Locale; -import javax.servlet.http.HttpServletRequest; - /** * The <code>RequestLocaleResolver</code> service interface may be implemented by a * service registered under this name to allow the resolution of the request @@ -52,5 +52,4 @@ public interface RequestLocaleResolver { * of request processing */ List<Locale> resolveLocale(HttpServletRequest request); - } diff --git a/src/main/java/org/apache/sling/i18n/ResourceBundleProvider.java b/src/main/java/org/apache/sling/i18n/ResourceBundleProvider.java index 10e97be..1a66822 100644 --- a/src/main/java/org/apache/sling/i18n/ResourceBundleProvider.java +++ b/src/main/java/org/apache/sling/i18n/ResourceBundleProvider.java @@ -72,5 +72,4 @@ public interface ResourceBundleProvider { * returning a <code>ResourceBundle</code> */ ResourceBundle getResourceBundle(String baseName, Locale locale); - } diff --git a/src/main/java/org/apache/sling/i18n/impl/Config.java b/src/main/java/org/apache/sling/i18n/impl/Config.java index 3039e45..b6cfb85 100644 --- a/src/main/java/org/apache/sling/i18n/impl/Config.java +++ b/src/main/java/org/apache/sling/i18n/impl/Config.java @@ -21,31 +21,38 @@ package org.apache.sling.i18n.impl; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.ObjectClassDefinition; -@ObjectClassDefinition(name ="Apache Sling I18N Resource Bundle Provider", - description ="ResourceBundleProvider service which loads the messages from the repository.") +@ObjectClassDefinition( + name = "Apache Sling I18N Resource Bundle Provider", + description = "ResourceBundleProvider service which loads the messages from the repository.") public @interface Config { - @AttributeDefinition(name = "Default Locale", - description = "The default locale to assume if none can be "+ - "resolved otherwise. This value must be in the form acceptable to the "+ - "java.util.Locale class.") + @AttributeDefinition( + name = "Default Locale", + description = "The default locale to assume if none can be " + + "resolved otherwise. This value must be in the form acceptable to the " + + "java.util.Locale class.") String locale_default() default "en"; - @AttributeDefinition(name = "Preload Bundles", - description = "Whether or not to eagerly load the resource bundles "+ - "on bundle start or a cache invalidation.") + @AttributeDefinition( + name = "Preload Bundles", + description = + "Whether or not to eagerly load the resource bundles " + "on bundle start or a cache invalidation.") boolean preload_bundles() default false; - @AttributeDefinition(name = "Invalidation Delay", - description = "In case of dictionary change events the cached "+ - "resource bundle becomes invalid after the given delay (in ms). ") + @AttributeDefinition( + name = "Invalidation Delay", + description = "In case of dictionary change events the cached " + + "resource bundle becomes invalid after the given delay (in ms). ") long invalidation_delay() default 5000; - - @AttributeDefinition(name="Included paths", - description="Translations in paths starting with one of these values will be included, unless they match one of the excluded paths.") + + @AttributeDefinition( + name = "Included paths", + description = + "Translations in paths starting with one of these values will be included, unless they match one of the excluded paths.") String[] included_paths() default {"/libs", "/apps"}; - @AttributeDefinition(name="Excluded paths", - description="Translations in paths starting with one of these values will be excluded.") + @AttributeDefinition( + name = "Excluded paths", + description = "Translations in paths starting with one of these values will be excluded.") String[] excluded_paths() default {"/var/eventing"}; -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/sling/i18n/impl/I18NFilter.java b/src/main/java/org/apache/sling/i18n/impl/I18NFilter.java index aa3e868..7e30d98 100644 --- a/src/main/java/org/apache/sling/i18n/impl/I18NFilter.java +++ b/src/main/java/org/apache/sling/i18n/impl/I18NFilter.java @@ -18,6 +18,15 @@ */ package org.apache.sling.i18n.impl; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + import java.io.IOException; import java.util.Collections; import java.util.Enumeration; @@ -28,15 +37,6 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TreeMap; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper; import org.apache.sling.commons.osgi.Order; @@ -59,16 +59,18 @@ import org.slf4j.LoggerFactory; * The <code>I18NFilter</code> class is a request level filter, which provides * the resource bundle for the current request. */ -@Component(service = Filter.class, - property = { +@Component( + service = Filter.class, + property = { Constants.SERVICE_DESCRIPTION + "=Internationalization Support Filter", Constants.SERVICE_VENDOR + "=The Apache Software Foundation", Constants.SERVICE_RANKING + ":Integer=700", "sling.filter.scope=REQUEST", "sling.filter.scope=ERROR", HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN + "=/", - HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT + "=(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=*)" - }) + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT + "=(" + + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=*)" + }) public class I18NFilter implements Filter { /** @@ -77,7 +79,7 @@ public class I18NFilter implements Filter { private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; /** Logger */ - private final static Logger LOG = LoggerFactory.getLogger(I18NFilter.class.getName()); + private static final Logger LOG = LoggerFactory.getLogger(I18NFilter.class.getName()); private final DefaultLocaleResolver DEFAULT_LOCALE_RESOLVER = new DefaultLocaleResolver(); @@ -99,7 +101,7 @@ public class I18NFilter implements Filter { */ @Override public void init(FilterConfig filterConfig) { - synchronized(this) { + synchronized (this) { initCount++; } } @@ -108,23 +110,19 @@ public class I18NFilter implements Filter { * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override - public void doFilter(ServletRequest request, - final ServletResponse response, - final FilterChain chain) - throws IOException, ServletException { + public void doFilter(ServletRequest request, final ServletResponse response, final FilterChain chain) + throws IOException, ServletException { final boolean runGlobal = this.initCount == 2; - if ( request instanceof SlingHttpServletRequest ) { + if (request instanceof SlingHttpServletRequest) { // check if we can use the simple version to wrap - if ( !runGlobal || this.requestLocaleResolver == DEFAULT_LOCALE_RESOLVER ) { + if (!runGlobal || this.requestLocaleResolver == DEFAULT_LOCALE_RESOLVER) { // wrap with our ResourceBundle provisioning - request = new I18NSlingHttpServletRequest(request, - combinedProvider, localeResolver); + request = new I18NSlingHttpServletRequest(request, combinedProvider, localeResolver); } else { request = new BaseI18NSlingHttpServletRequest(request, combinedProvider); } } else { - request = new I18NHttpServletRequest(request, - combinedProvider, requestLocaleResolver); + request = new I18NHttpServletRequest(request, combinedProvider, requestLocaleResolver); } // and forward the request @@ -136,16 +134,17 @@ public class I18NFilter implements Filter { */ @Override public void destroy() { - synchronized(this) { + synchronized (this) { initCount--; } } // ---------- SCR Integration ---------------------------------------------- - @Reference(cardinality = ReferenceCardinality.OPTIONAL, + @Reference( + cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, - policyOption=ReferencePolicyOption.GREEDY) + policyOption = ReferencePolicyOption.GREEDY) protected void bindLocaleResolver(final LocaleResolver resolver) { this.localeResolver = resolver; } @@ -156,9 +155,10 @@ public class I18NFilter implements Filter { } } - @Reference(cardinality = ReferenceCardinality.OPTIONAL, + @Reference( + cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, - policyOption=ReferencePolicyOption.GREEDY) + policyOption = ReferencePolicyOption.GREEDY) protected void bindRequestLocaleResolver(final RequestLocaleResolver resolver) { this.requestLocaleResolver = resolver; } @@ -169,18 +169,20 @@ public class I18NFilter implements Filter { } } - @Reference(service = ResourceBundleProvider.class, + @Reference( + service = ResourceBundleProvider.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) protected void bindResourceBundleProvider(final ResourceBundleProvider provider, final Map<String, Object> props) { - synchronized ( this.providers ) { + synchronized (this.providers) { this.providers.put(ServiceUtil.getComparableForServiceRanking(props, Order.ASCENDING), provider); this.sortedProviders = this.providers.values().toArray(new ResourceBundleProvider[this.providers.size()]); } } - protected void unbindResourceBundleProvider(final ResourceBundleProvider provider, final Map<String, Object> props) { - synchronized ( this.providers ) { + protected void unbindResourceBundleProvider( + final ResourceBundleProvider provider, final Map<String, Object> props) { + synchronized (this.providers) { this.providers.remove(ServiceUtil.getComparableForServiceRanking(props, Order.ASCENDING)); this.sortedProviders = this.providers.values().toArray(new ResourceBundleProvider[this.providers.size()]); } @@ -195,7 +197,7 @@ public class I18NFilter implements Filter { public Locale getDefaultLocale() { // ask all registered providers, use the first one that returns final ResourceBundleProvider[] providers = sortedProviders; - for(int i=providers.length-1; i >= 0; i--) { + for (int i = providers.length - 1; i >= 0; i--) { final ResourceBundleProvider provider = providers[i]; final Locale locale = provider.getDefaultLocale(); if (locale != null) { @@ -209,7 +211,7 @@ public class I18NFilter implements Filter { public ResourceBundle getResourceBundle(final Locale locale) { // ask all registered providers, use the first one that returns final ResourceBundleProvider[] providers = sortedProviders; - for(int i=providers.length-1; i >= 0; i--) { + for (int i = providers.length - 1; i >= 0; i--) { final ResourceBundleProvider provider = providers[i]; final ResourceBundle bundle = provider.getResourceBundle(locale); if (bundle != null) { @@ -223,7 +225,7 @@ public class I18NFilter implements Filter { public ResourceBundle getResourceBundle(final String baseName, final Locale locale) { // ask all registered providers, use the first one that returns final ResourceBundleProvider[] providers = sortedProviders; - for(int i=providers.length-1; i >= 0; i--) { + for (int i = providers.length - 1; i >= 0; i--) { final ResourceBundleProvider provider = providers[i]; final ResourceBundle bundle = provider.getResourceBundle(baseName, locale); if (bundle != null) { @@ -241,8 +243,7 @@ public class I18NFilter implements Filter { // ---------- internal class ----------------------------------------------- - private static class I18NHttpServletRequest - extends HttpServletRequestWrapper { + private static class I18NHttpServletRequest extends HttpServletRequestWrapper { private final ResourceBundleProvider bundleProvider; @@ -254,10 +255,11 @@ public class I18NFilter implements Filter { private ResourceBundle resourceBundle; - I18NHttpServletRequest(final ServletRequest delegatee, + I18NHttpServletRequest( + final ServletRequest delegatee, final ResourceBundleProvider bundleProvider, final RequestLocaleResolver localeResolver) { - super((HttpServletRequest)delegatee); + super((HttpServletRequest) delegatee); this.bundleProvider = bundleProvider; this.localeResolver = localeResolver; } @@ -278,8 +280,8 @@ public class I18NFilter implements Filter { @Override public Object getAttribute(final String name) { - if ( ResourceBundleProvider.BUNDLE_REQ_ATTR.equals(name) ) { - if ( this.resourceBundle == null && this.bundleProvider != null) { + if (ResourceBundleProvider.BUNDLE_REQ_ATTR.equals(name)) { + if (this.resourceBundle == null && this.bundleProvider != null) { this.resourceBundle = this.bundleProvider.getResourceBundle(this.getLocale()); } return this.resourceBundle; @@ -289,7 +291,7 @@ public class I18NFilter implements Filter { private List<Locale> getLocaleList() { if (localeList == null) { - List<Locale> resolved = localeResolver.resolveLocale((HttpServletRequest)this.getRequest()); + List<Locale> resolved = localeResolver.resolveLocale((HttpServletRequest) this.getRequest()); this.localeList = (resolved != null && !resolved.isEmpty()) ? resolved : Collections.singletonList(defaultLocale(this.bundleProvider)); @@ -297,16 +299,13 @@ public class I18NFilter implements Filter { return localeList; } - } - private static class BaseI18NSlingHttpServletRequest - extends SlingHttpServletRequestWrapper { + private static class BaseI18NSlingHttpServletRequest extends SlingHttpServletRequestWrapper { protected final ResourceBundleProvider bundleProvider; - BaseI18NSlingHttpServletRequest(final ServletRequest delegatee, - final ResourceBundleProvider bundleProvider) { + BaseI18NSlingHttpServletRequest(final ServletRequest delegatee, final ResourceBundleProvider bundleProvider) { super((SlingHttpServletRequest) delegatee); this.bundleProvider = bundleProvider; } @@ -326,9 +325,7 @@ public class I18NFilter implements Filter { try { return bundleProvider.getResourceBundle(baseName, locale); } catch (MissingResourceException mre) { - LOG.warn( - "getResourceBundle: Cannot get ResourceBundle from provider", - mre); + LOG.warn("getResourceBundle: Cannot get ResourceBundle from provider", mre); } } else { LOG.info("getResourceBundle: ResourceBundleProvider not available, calling default implementation"); @@ -338,8 +335,7 @@ public class I18NFilter implements Filter { } } - private static class I18NSlingHttpServletRequest - extends BaseI18NSlingHttpServletRequest { + private static class I18NSlingHttpServletRequest extends BaseI18NSlingHttpServletRequest { private final LocaleResolver localeResolver; @@ -347,7 +343,8 @@ public class I18NFilter implements Filter { private List<Locale> localeList; - I18NSlingHttpServletRequest(final ServletRequest delegatee, + I18NSlingHttpServletRequest( + final ServletRequest delegatee, final ResourceBundleProvider bundleProvider, final LocaleResolver localeResolver) { super(delegatee, bundleProvider); @@ -356,7 +353,7 @@ public class I18NFilter implements Filter { @Override public Object getAttribute(final String name) { - if ( ResourceBundleProvider.BUNDLE_REQ_ATTR.equals(name) ) { + if (ResourceBundleProvider.BUNDLE_REQ_ATTR.equals(name)) { final Object superValue = super.getAttribute(name); return (superValue != null ? superValue : this.getResourceBundle(null)); } @@ -388,5 +385,4 @@ public class I18NFilter implements Filter { return localeList; } } - } diff --git a/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundle.java b/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundle.java index 9efd86c..ad9585c 100644 --- a/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundle.java +++ b/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundle.java @@ -76,14 +76,17 @@ public class JcrResourceBundle extends ResourceBundle { private final Set<String> languageRoots = new HashSet<>(); - JcrResourceBundle(final Locale locale, final String baseName, - final ResourceResolver resourceResolver, + JcrResourceBundle( + final Locale locale, + final String baseName, + final ResourceResolver resourceResolver, final List<LocatorPaths> locatorPaths, final PathFilter filter) { this.locale = locale; this.baseName = baseName; - log.info("Finding all dictionaries for '{}' (basename: {}) ...", locale, baseName == null ? "<none>" : baseName); + log.info( + "Finding all dictionaries for '{}' (basename: {}) ...", locale, baseName == null ? "<none>" : baseName); final long start = System.currentTimeMillis(); final Set<String> roots = loadPotentialLanguageRoots(resourceResolver, locale, baseName, locatorPaths, filter); @@ -92,9 +95,8 @@ public class JcrResourceBundle extends ResourceBundle { if (log.isInfoEnabled()) { final long end = System.currentTimeMillis(); log.info( - "Finished loading {} entries for '{}' (basename: {}) in {}ms", - new Object[] { resources.size(), locale, baseName == null ? "<none>" : baseName, (end - start)} - ); + "Finished loading {} entries for '{}' (basename: {}) in {}ms", + new Object[] {resources.size(), locale, baseName == null ? "<none>" : baseName, (end - start)}); } } @@ -135,16 +137,16 @@ public class JcrResourceBundle extends ResourceBundle { @Override public Enumeration<String> getKeys() { - Enumeration<String> parentKeys = (parent != null) - ? parent.getKeys() - : null; + Enumeration<String> parentKeys = (parent != null) ? parent.getKeys() : null; return new ResourceBundleEnumeration(resources.keySet(), parentKeys); } @Override protected Object handleGetObject(String key) { if (log.isDebugEnabled()) { - log.debug("Requesting key '{}' from resource bundle (baseName '{}', locale '{}')", new Object[] {key, baseName, locale}); + log.debug( + "Requesting key '{}' from resource bundle (baseName '{}', locale '{}')", + new Object[] {key, baseName, locale}); } return resources.get(key); } @@ -168,7 +170,8 @@ public class JcrResourceBundle extends ResourceBundle { * * @throws NullPointerException if either of the parameters is {@code null}. */ - private Map<String, Object> loadFully(final ResourceResolver resolver, Set<String> roots, Set<String> languageRoots) { + private Map<String, Object> loadFully( + final ResourceResolver resolver, Set<String> roots, Set<String> languageRoots) { final String[] searchPath = resolver.getSearchPath(); @@ -185,7 +188,7 @@ public class JcrResourceBundle extends ResourceBundle { dictionariesBySearchPath.add(new ArrayList<Map<String, Object>>()); } - for (final String root: roots) { + for (final String root : roots) { Resource dictionaryResource = resolver.getResource(root); if (dictionaryResource == null) { @@ -259,16 +262,22 @@ public class JcrResourceBundle extends ResourceBundle { @Override public void object() throws IOException {} + @Override public void endObject() throws IOException {} + @Override public void array() throws IOException {} + @Override public void endArray() throws IOException {} + @Override public void value(boolean value) throws IOException {} + @Override public void value(long value) throws IOException {} + @Override public void value(double value) throws IOException {} }); @@ -303,27 +312,29 @@ public class JcrResourceBundle extends ResourceBundle { */ private void scanForSlingMessages(final Resource rsrc, final Map<String, Object> targetDictionary) { final ValueMap vm = rsrc.adaptTo(ValueMap.class); - if ( vm != null ) { + if (vm != null) { final String value = vm.get(PROP_VALUE, String.class); - if ( value != null ) { + if (value != null) { final String key = vm.get(PROP_KEY, rsrc.getName()); targetDictionary.put(key, value); } } - for(final Resource c : rsrc.getChildren()) { + for (final Resource c : rsrc.getChildren()) { scanForSlingMessages(c, targetDictionary); } } - private void loadSlingMessageDictionary(final Resource dictionaryResource, final Map<String, Object> targetDictionary) { + private void loadSlingMessageDictionary( + final Resource dictionaryResource, final Map<String, Object> targetDictionary) { log.info("Loading sling:Message dictionary: {}", dictionaryResource.getPath()); this.scanForSlingMessages(dictionaryResource, targetDictionary); } - private Set<String> loadPotentialLanguageRoots(final ResourceResolver resourceResolver, - final Locale locale, + private Set<String> loadPotentialLanguageRoots( + final ResourceResolver resourceResolver, + final Locale locale, final String baseName, final Collection<LocatorPaths> locatorPaths, final PathFilter filter) { @@ -339,7 +350,10 @@ public class JcrResourceBundle extends ResourceBundle { if (filter.includePath(bundle.getPath())) { paths.add(bundle.getPath()); } else { - log.warn("Ignoring i18n bundle for language {} at {} because it is not included by the path filter", locale, bundle.getPath()); + log.warn( + "Ignoring i18n bundle for language {} at {} because it is not included by the path filter", + locale, + bundle.getPath()); } } } @@ -348,13 +362,16 @@ public class JcrResourceBundle extends ResourceBundle { // next traverse the ancestors of all of the locator paths final LocatorPathsVisitor visitor = new LocatorPathsVisitor(check, paths); for (final LocatorPaths locator : locatorPaths) { - if ( filter.includePath(locator.getPath())) { + if (filter.includePath(locator.getPath())) { final Resource parentResource = resourceResolver.getResource(locator.getPath()); if (parentResource != null) { visitor.accept(parentResource, locator.getTraverseDepth()); - } + } } else { - log.warn("Ignoring i18n bundle for language {} at {} because it is not included by the path filter", locale, locator.getPath()); + log.warn( + "Ignoring i18n bundle for language {} at {} because it is not included by the path filter", + locale, + locator.getPath()); } } } diff --git a/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider.java b/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider.java index 277ddce..e855bde 100644 --- a/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider.java +++ b/src/main/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider.java @@ -18,10 +18,6 @@ */ package org.apache.sling.i18n.impl; -import static org.apache.sling.i18n.impl.JcrResourceBundle.PROP_BASENAME; -import static org.apache.sling.i18n.impl.JcrResourceBundle.PROP_LANGUAGE; -import static org.apache.sling.i18n.impl.JcrResourceBundle.PROP_PATH; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -69,23 +65,29 @@ import org.osgi.util.tracker.BundleTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.apache.sling.i18n.impl.JcrResourceBundle.PROP_BASENAME; +import static org.apache.sling.i18n.impl.JcrResourceBundle.PROP_LANGUAGE; +import static org.apache.sling.i18n.impl.JcrResourceBundle.PROP_PATH; + /** * The <code>JcrResourceBundleProvider</code> implements the * <code>ResourceBundleProvider</code> interface creating * <code>ResourceBundle</code> instances from resources stored in the * repository. */ -@Component(service = {ResourceBundleProvider.class, ResourceChangeListener.class}, - property = { +@Component( + service = {ResourceBundleProvider.class, ResourceChangeListener.class}, + property = { Constants.SERVICE_DESCRIPTION + "=Apache Sling I18n Resource Bundle Provider", Constants.SERVICE_VENDOR + "=The Apache Software Foundation", ResourceChangeListener.PATHS + "=/", ResourceChangeListener.CHANGES + "=ADDED", ResourceChangeListener.CHANGES + "=REMOVED", ResourceChangeListener.CHANGES + "=CHANGED" - }) + }) @Designate(ocd = Config.class) -public class JcrResourceBundleProvider implements ResourceBundleProvider, ResourceChangeListener, ExternalResourceChangeListener { +public class JcrResourceBundleProvider + implements ResourceBundleProvider, ResourceChangeListener, ExternalResourceChangeListener { /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); @@ -100,7 +102,7 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour private Scheduler scheduler; /** job names of scheduled jobs for reloading individual bundles */ - private final Collection<String> scheduledJobNames = Collections.synchronizedList(new ArrayList<String>()) ; + private final Collection<String> scheduledJobNames = Collections.synchronizedList(new ArrayList<String>()); @Reference private ResourceResolverFactory resourceResolverFactory; @@ -220,34 +222,33 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour final ChangeStatus status = new ChangeStatus(); try { for (final ResourceChange change : changes) { - + if (!this.pathFilter.includePath(change.getPath())) { continue; } this.onChange(status, change); // if we need to reload all, we can skip all other events - if ( status.reloadAll ) { + if (status.reloadAll) { break; } } - if ( status.reloadAll ) { + if (status.reloadAll) { this.scheduleReloadBundles(true); } else { - for(final JcrResourceBundle bundle : status.reloadBundles ) { + for (final JcrResourceBundle bundle : status.reloadBundles) { this.scheduleReloadBundle(bundle); } } - } catch ( final LoginException le) { + } catch (final LoginException le) { log.error("Unable to get service resource resolver.", le); } finally { - if ( status.resourceResolver != null ) { + if (status.resourceResolver != null) { status.resourceResolver.close(); } } } - - private void onChange(final ChangeStatus status, final ResourceChange change) - throws LoginException { + + private void onChange(final ChangeStatus status, final ResourceChange change) throws LoginException { log.debug("onChange: Detecting change {} for path '{}'", change.getType(), change.getPath()); // if this change was on languageRootPath level this might change basename and locale as well, therefore @@ -264,8 +265,10 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour for (JcrResourceBundle bundle : resourceBundleRegistry.getResourceBundles()) { if (bundle.getLanguageRootPaths().contains(root)) { // reload it - log.debug("onChange: Resource changes below '{}', reloading ResourceBundle '{}'", - root, bundle); + log.debug( + "onChange: Resource changes below '{}', reloading ResourceBundle '{}'", + root, + bundle); status.reloadBundles.add(bundle); } } @@ -273,8 +276,8 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour } // may be a completely new dictionary - if ( status.resourceResolver == null ) { - status.resourceResolver = createResourceResolver() ; + if (status.resourceResolver == null) { + status.resourceResolver = createResourceResolver(); } if (isDictionaryResource(status.resourceResolver, change)) { status.reloadAll = true; @@ -282,7 +285,6 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour } } - private boolean isDictionaryResource(final ResourceResolver resolver, final ResourceChange change) { // language node changes happen quite frequently (https://issues.apache.org/jira/browse/SLING-2881) // therefore only consider changes either for sling:MessageEntry's @@ -293,23 +295,32 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour log.trace("Could not get resource for '{}' for event {}", change.getPath(), change.getType()); return false; } - if ( resource.getResourceType() == null ) { + if (resource.getResourceType() == null) { return false; } if (resource.isResourceType(JcrResourceBundle.RT_MESSAGE_ENTRY)) { - log.debug("Found new dictionary entry: New {} resource in '{}' detected", JcrResourceBundle.RT_MESSAGE_ENTRY, change.getPath()); + log.debug( + "Found new dictionary entry: New {} resource in '{}' detected", + JcrResourceBundle.RT_MESSAGE_ENTRY, + change.getPath()); return true; } final ValueMap valueMap = resource.getValueMap(); // FIXME: derivatives from mix:Message are not detected if (hasMixin(valueMap, JcrResourceBundle.MIXIN_MESSAGE)) { - log.debug("Found new dictionary entry: New {} resource in '{}' detected", JcrResourceBundle.MIXIN_MESSAGE, change.getPath()); + log.debug( + "Found new dictionary entry: New {} resource in '{}' detected", + JcrResourceBundle.MIXIN_MESSAGE, + change.getPath()); return true; } if (change.getPath().endsWith(".json")) { // check for mixin if (hasMixin(valueMap, JcrResourceBundle.MIXIN_LANGUAGE)) { - log.debug("Found new dictionary: New {} resource in '{}' detected", JcrResourceBundle.MIXIN_LANGUAGE, change.getPath()); + log.debug( + "Found new dictionary: New {} resource in '{}' detected", + JcrResourceBundle.MIXIN_LANGUAGE, + change.getPath()); return true; } } @@ -318,9 +329,9 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour private boolean hasMixin(ValueMap valueMap, String mixin) { final String[] mixins = valueMap.get(JcrResourceBundle.PROP_MIXINS, String[].class); - if ( mixins != null ) { - for(final String m : mixins) { - if (mixin.equals(m) ) { + if (mixins != null) { + for (final String m : mixins) { + if (mixin.equals(m)) { return true; } } @@ -330,7 +341,7 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour private void scheduleReloadBundles(final boolean withDelay) { // cancel all reload individual bundle jobs! - synchronized(scheduledJobNames) { + synchronized (scheduledJobNames) { for (String scheduledJobName : scheduledJobNames) { scheduler.unschedule(scheduledJobName); } @@ -344,14 +355,16 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour options = scheduler.NOW(); } options.name("ResourceBundleProvider: reload all resource bundles"); - scheduler.schedule(new Runnable() { - @Override - public void run() { - log.info("Reloading all resource bundles"); - clearCache(); - preloadBundles(); - } - }, options); + scheduler.schedule( + new Runnable() { + @Override + public void run() { + log.info("Reloading all resource bundles"); + clearCache(); + preloadBundles(); + } + }, + options); } private void scheduleReloadBundle(final JcrResourceBundle bundle) { @@ -362,13 +375,15 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour final String jobName = "ResourceBundleProvider: reload bundle with key " + key.toString(); scheduledJobNames.add(jobName); options.name(jobName); - scheduler.schedule(new Runnable() { - @Override - public void run() { - reloadBundle(key); - scheduledJobNames.remove(jobName); - } - }, options); + scheduler.schedule( + new Runnable() { + @Override + public void run() { + reloadBundle(key); + scheduledJobNames.remove(jobName); + } + }, + options); } void reloadBundle(final Key key) { @@ -384,7 +399,8 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour JcrResourceBundle parentBundle = (JcrResourceBundle) bundle.getParent(); Key parentKey = new Key(parentBundle.getBaseName(), parentBundle.getLocale()); if (parentKey.equals(key)) { - log.debug("Also invalidate dependent bundle {} which has bundle {} as parent", bundle, parentBundle); + log.debug( + "Also invalidate dependent bundle {} which has bundle {} as parent", bundle, parentBundle); dependentBundles.add(bundle); } } @@ -415,8 +431,7 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour this.resourceBundleRegistry = new ResourceBundleRegistry(context); - this.locatorPathsTracker = new BundleTracker<>(context, - Bundle.ACTIVE, new LocatorPathsTracker(this)); + this.locatorPathsTracker = new BundleTracker<>(context, Bundle.ACTIVE, new LocatorPathsTracker(this)); this.locatorPathsTracker.open(); if (this.resourceResolverFactory != null) { // this is only null during test execution! @@ -450,11 +465,13 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour * created and the <code>ResourceResolver</code> is not * available to access the resources. */ - private ResourceBundle getResourceBundleInternal(ResourceResolver optionalResolver, String baseName, Locale locale) { + private ResourceBundle getResourceBundleInternal( + ResourceResolver optionalResolver, String baseName, Locale locale) { return getResourceBundleInternal(optionalResolver, baseName, locale, false); } - private ResourceBundle getResourceBundleInternal(ResourceResolver optionalResolver, final String baseName, Locale locale, final boolean forceReload) { + private ResourceBundle getResourceBundleInternal( + ResourceResolver optionalResolver, final String baseName, Locale locale, final boolean forceReload) { if (locale == null) { locale = defaultLocale; } @@ -476,8 +493,8 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour } else { log.debug("getResourceBundleInternal({}): reading from Repository", key); ResourceResolver localResolver = null; - try { - if ( optionalResolver == null ) { + try { + if (optionalResolver == null) { localResolver = createResourceResolver(); optionalResolver = localResolver; } @@ -491,12 +508,12 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour log.debug("Key {} - added service registration and language roots {}", key, languageRoots); log.info("Currently loaded dictionaries across all locales: {}", languageRootPaths); - } catch ( final LoginException le) { - throw (MissingResourceException)new MissingResourceException("Unable to create service resource resolver", - baseName, - locale.toString()).initCause(le); + } catch (final LoginException le) { + throw (MissingResourceException) new MissingResourceException( + "Unable to create service resource resolver", baseName, locale.toString()) + .initCause(le); } finally { - if ( localResolver != null ) { + if (localResolver != null) { localResolver.close(); } } @@ -517,8 +534,10 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour * @throws MissingResourceException If the <code>ResourceResolver</code> * is not available to access the resources. */ - private JcrResourceBundle createResourceBundle(final ResourceResolver resolver, final String baseName, final Locale locale) { - final JcrResourceBundle bundle = new JcrResourceBundle(locale, baseName, resolver, locatorPaths, this.pathFilter); + private JcrResourceBundle createResourceBundle( + final ResourceResolver resolver, final String baseName, final Locale locale) { + final JcrResourceBundle bundle = + new JcrResourceBundle(locale, baseName, resolver, locatorPaths, this.pathFilter); // set parent resource bundle Locale parentLocale = getParentLocale(locale); @@ -584,28 +603,33 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour private void preloadBundles() { if (this.preloadBundles && !resourceBundleRegistry.isClosed()) { - try ( final ResourceResolver resolver = createResourceResolver() ) { - final Iterator<Map<String, Object>> bundles = resolver.queryResources( - JcrResourceBundle.QUERY_LANGUAGE_ROOTS, "xpath"); + try (final ResourceResolver resolver = createResourceResolver()) { + final Iterator<Map<String, Object>> bundles = + resolver.queryResources(JcrResourceBundle.QUERY_LANGUAGE_ROOTS, "xpath"); final Set<Key> usedKeys = new HashSet<>(); while (bundles.hasNext()) { - final Map<String,Object> bundle = bundles.next(); + final Map<String, Object> bundle = bundles.next(); if (bundle.containsKey(PROP_LANGUAGE) && bundle.containsKey(PROP_PATH)) { final String path = bundle.get(PROP_PATH).toString(); final String language = bundle.get(PROP_LANGUAGE).toString(); if (this.pathFilter.includePath(path)) { final Locale locale = toLocale(language); - final String baseName = bundle.containsKey(PROP_BASENAME) ? bundle.get(PROP_BASENAME).toString() : null; + final String baseName = bundle.containsKey(PROP_BASENAME) + ? bundle.get(PROP_BASENAME).toString() + : null; final Key key = new Key(baseName, locale); if (usedKeys.add(key)) { getResourceBundleInternal(resolver, baseName, locale); } } else { - log.warn("Ignoring i18n bundle for language {} at {} because it is not included by the path filter", language, path); + log.warn( + "Ignoring i18n bundle for language {} at {} because it is not included by the path filter", + language, + path); } } } - } catch ( final LoginException le) { + } catch (final LoginException le) { log.error("Unable to create service user resource resolver.", le); } } @@ -685,7 +709,7 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour return new Locale(lang, country, parts[2]); } - //---------- internal class + // ---------- internal class /** * The <code>Key</code> class encapsulates the base name and Locale in a @@ -727,8 +751,7 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour return true; } else if (obj instanceof Key) { Key other = (Key) obj; - return equals(this.baseName, other.baseName) - && equals(this.locale, other.locale); + return equals(this.baseName, other.baseName) && equals(this.locale, other.locale); } return false; @@ -783,19 +806,25 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour } Collection<JcrResourceBundle> getResourceBundles() { - return registrations.get().values().stream().map(e -> e.resourceBundle).collect(Collectors.toList()); + return registrations.get().values().stream() + .map(e -> e.resourceBundle) + .collect(Collectors.toList()); } void registerResourceBundle(Key key, JcrResourceBundle resourceBundle) { if (closed.get()) { return; } - ServiceRegistration<ResourceBundle> serviceReg = bundleContext.registerService(ResourceBundle.class, resourceBundle, serviceProps(key)); + ServiceRegistration<ResourceBundle> serviceReg = + bundleContext.registerService(ResourceBundle.class, resourceBundle, serviceProps(key)); Entry oldEntry = registrations.get().put(key, new Entry(resourceBundle, serviceReg)); if (oldEntry != null) { oldEntry.serviceRegistration.unregister(); } - log.debug("[ResourceBundleRegistry.updateResourceBundle] Registry updated - Nr of entries: {} - Keys: {}", registrations.get().size(), registrations.get().keySet()); + log.debug( + "[ResourceBundleRegistry.updateResourceBundle] Registry updated - Nr of entries: {} - Keys: {}", + registrations.get().size(), + registrations.get().keySet()); } private static Dictionary<String, Object> serviceProps(Key key) { @@ -815,7 +844,9 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour if (oldEntry != null) { oldEntry.serviceRegistration.unregister(); } else { - log.warn("[ResourceBundleRegistry.unregisterResourceBundle] Could not find resource bundle service for {}", key); + log.warn( + "[ResourceBundleRegistry.unregisterResourceBundle] Could not find resource bundle service for {}", + key); } } @@ -827,12 +858,18 @@ public class JcrResourceBundleProvider implements ResourceBundleProvider, Resour } private void unregisterAllInternal() { - log.debug("[ResourceBundleRegistry.clearInternal] Before - Nr of Keys: {} - Keys: {}", registrations.get().size(), registrations.get().keySet()); - ConcurrentHashMap<Key,Entry> oldServiceReg = registrations.getAndSet(new ConcurrentHashMap<>()); - for(Entry entry : oldServiceReg.values()) { + log.debug( + "[ResourceBundleRegistry.clearInternal] Before - Nr of Keys: {} - Keys: {}", + registrations.get().size(), + registrations.get().keySet()); + ConcurrentHashMap<Key, Entry> oldServiceReg = registrations.getAndSet(new ConcurrentHashMap<>()); + for (Entry entry : oldServiceReg.values()) { entry.serviceRegistration.unregister(); } - log.debug("[ResourceBundleRegistry.clearInternal] After - Nr of Keys: {} - Keys: {}", registrations.get().size(), registrations.get().keySet()); + log.debug( + "[ResourceBundleRegistry.clearInternal] After - Nr of Keys: {} - Keys: {}", + registrations.get().size(), + registrations.get().keySet()); } boolean isClosed() { diff --git a/src/main/java/org/apache/sling/i18n/impl/LocatorPaths.java b/src/main/java/org/apache/sling/i18n/impl/LocatorPaths.java index 34f1cfd..f5e17bf 100644 --- a/src/main/java/org/apache/sling/i18n/impl/LocatorPaths.java +++ b/src/main/java/org/apache/sling/i18n/impl/LocatorPaths.java @@ -1,18 +1,20 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.sling.i18n.impl; @@ -54,23 +56,15 @@ class LocatorPaths { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; LocatorPaths other = (LocatorPaths) obj; - if (forBundleId != other.forBundleId) - return false; + if (forBundleId != other.forBundleId) return false; if (path == null) { - if (other.path != null) - return false; - } else if (!path.equals(other.path)) - return false; - if (traverseDepth != other.traverseDepth) - return false; + if (other.path != null) return false; + } else if (!path.equals(other.path)) return false; + if (traverseDepth != other.traverseDepth) return false; return true; } - } diff --git a/src/main/java/org/apache/sling/i18n/impl/LocatorPathsTracker.java b/src/main/java/org/apache/sling/i18n/impl/LocatorPathsTracker.java index 55d31be..4637e25 100644 --- a/src/main/java/org/apache/sling/i18n/impl/LocatorPathsTracker.java +++ b/src/main/java/org/apache/sling/i18n/impl/LocatorPathsTracker.java @@ -1,18 +1,20 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.apache.sling.i18n.impl; @@ -29,7 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Handles watching bundles for registration of ResourceBundle locator paths + * Handles watching bundles for registration of ResourceBundle locator paths */ class LocatorPathsTracker implements BundleTrackerCustomizer<Set<LocatorPaths>> { @@ -47,8 +49,7 @@ class LocatorPathsTracker implements BundleTrackerCustomizer<Set<LocatorPaths>> @Override public Set<LocatorPaths> addingBundle(Bundle bundle, BundleEvent event) { - log.debug("Considering bundle for registering resource bundle locator paths: {}", - bundle.getSymbolicName()); + log.debug("Considering bundle for registering resource bundle locator paths: {}", bundle.getSymbolicName()); Set<LocatorPaths> pathsSet = null; String provideCapability = bundle.getHeaders().get(Constants.PROVIDE_CAPABILITY); @@ -82,8 +83,10 @@ class LocatorPathsTracker implements BundleTrackerCustomizer<Set<LocatorPaths>> } if (pathsSet != null) { - log.info("Registered {} resource bundle locator paths for bundle: {}", - pathsSet.size(), bundle.getSymbolicName()); + log.info( + "Registered {} resource bundle locator paths for bundle: {}", + pathsSet.size(), + bundle.getSymbolicName()); this.rbp.registerLocatorPaths(pathsSet); } } @@ -97,9 +100,10 @@ class LocatorPathsTracker implements BundleTrackerCustomizer<Set<LocatorPaths>> @Override public void removedBundle(Bundle bundle, BundleEvent event, Set<LocatorPaths> baseNamesSet) { - log.info("Unregistered {} resource bundle locator paths for bundle: {}", - baseNamesSet.size(), bundle.getSymbolicName()); + log.info( + "Unregistered {} resource bundle locator paths for bundle: {}", + baseNamesSet.size(), + bundle.getSymbolicName()); this.rbp.unregisterLocatorPaths(baseNamesSet); } - } diff --git a/src/main/java/org/apache/sling/i18n/impl/LocatorPathsVisitor.java b/src/main/java/org/apache/sling/i18n/impl/LocatorPathsVisitor.java index b919a40..c4b1405 100644 --- a/src/main/java/org/apache/sling/i18n/impl/LocatorPathsVisitor.java +++ b/src/main/java/org/apache/sling/i18n/impl/LocatorPathsVisitor.java @@ -35,9 +35,9 @@ class LocatorPathsVisitor extends AbstractResourceVisitor { /** * Constructor to prepare visitor - * + * * @param check the callback to check the resource for a match - * @param paths the language + * @param paths the language * @param traverseDepth the maximum depth to traverse the descendant */ public LocatorPathsVisitor(PotentialLanguageRootCheck check, Set<String> paths) { @@ -74,5 +74,4 @@ class LocatorPathsVisitor extends AbstractResourceVisitor { paths.add(res.getPath()); } } - } diff --git a/src/main/java/org/apache/sling/i18n/impl/PathFilter.java b/src/main/java/org/apache/sling/i18n/impl/PathFilter.java index 69220c1..0a9456d 100644 --- a/src/main/java/org/apache/sling/i18n/impl/PathFilter.java +++ b/src/main/java/org/apache/sling/i18n/impl/PathFilter.java @@ -53,4 +53,4 @@ public class PathFilter { } return included; } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/sling/i18n/impl/PotentialLanguageRootCheck.java b/src/main/java/org/apache/sling/i18n/impl/PotentialLanguageRootCheck.java index 3bee10f..573b925 100644 --- a/src/main/java/org/apache/sling/i18n/impl/PotentialLanguageRootCheck.java +++ b/src/main/java/org/apache/sling/i18n/impl/PotentialLanguageRootCheck.java @@ -41,10 +41,10 @@ class PotentialLanguageRootCheck { this.localeRFC4646String = toRFC4646String(locale); this.localeRFC4646StringLower = localeRFC4646String.toLowerCase(); } - + /** * Checks if the specified resource is a match for a resource bundle resource - * + * * @param resource the resource to check */ public boolean isResourceBundle(Resource resource) { @@ -58,7 +58,7 @@ class PotentialLanguageRootCheck { || language.equals(localeRFC4646String) || language.equals(localeRFC4646StringLower)) { // basename might be a multivalue (see https://issues.apache.org/jira/browse/SLING-4547) - String[] baseNames = properties.get(JcrResourceBundle.PROP_BASENAME, new String[]{}); + String[] baseNames = properties.get(JcrResourceBundle.PROP_BASENAME, new String[] {}); if (baseName == null || Arrays.asList(baseNames).contains(baseName)) { match = true; } @@ -72,5 +72,4 @@ class PotentialLanguageRootCheck { private static String toRFC4646String(Locale locale) { return locale.toString().replace('_', '-'); } - } diff --git a/src/main/java/org/apache/sling/i18n/impl/ResourceBundleEnumeration.java b/src/main/java/org/apache/sling/i18n/impl/ResourceBundleEnumeration.java index 033e105..ef72fb1 100644 --- a/src/main/java/org/apache/sling/i18n/impl/ResourceBundleEnumeration.java +++ b/src/main/java/org/apache/sling/i18n/impl/ResourceBundleEnumeration.java @@ -30,15 +30,15 @@ public class ResourceBundleEnumeration implements Enumeration<String> { private Iterator<String> keysIterator; private String next; - + public ResourceBundleEnumeration(Set<String> keys, Enumeration<String> parentKeys) { this.keys = keys; this.parentKeys = parentKeys; this.keysIterator = keys.iterator(); - + next = seek(); } - + public boolean hasMoreElements() { return next != null; } @@ -47,7 +47,7 @@ public class ResourceBundleEnumeration implements Enumeration<String> { if (!hasMoreElements()) { throw new NoSuchElementException(); } - + String result = next; next = seek(); return result; @@ -55,15 +55,15 @@ public class ResourceBundleEnumeration implements Enumeration<String> { private String seek() { if (keysIterator != null) { - + if (keysIterator.hasNext()) { return keysIterator.next(); } - + // my keys are exhausted, set iterator to null keysIterator = null; } - + if (parentKeys != null) { while (parentKeys.hasMoreElements()) { String parentKey = parentKeys.nextElement(); @@ -71,11 +71,11 @@ public class ResourceBundleEnumeration implements Enumeration<String> { return parentKey; } } - + // no more parent keys, set enumeration to null parentKeys = null; } - + // parentKeys are also exhausted, nothing more to return return null; } diff --git a/src/main/java/org/apache/sling/i18n/package-info.java b/src/main/java/org/apache/sling/i18n/package-info.java index c729ae7..92c9c75 100644 --- a/src/main/java/org/apache/sling/i18n/package-info.java +++ b/src/main/java/org/apache/sling/i18n/package-info.java @@ -19,5 +19,3 @@ @org.osgi.annotation.versioning.Version("2.2.1") package org.apache.sling.i18n; - - diff --git a/src/test/java/org/apache/sling/i18n/impl/ConcurrentJcrResourceBundleLoadingTest.java b/src/test/java/org/apache/sling/i18n/impl/ConcurrentJcrResourceBundleLoadingTest.java index 834b6f4..7f3d506 100644 --- a/src/test/java/org/apache/sling/i18n/impl/ConcurrentJcrResourceBundleLoadingTest.java +++ b/src/test/java/org/apache/sling/i18n/impl/ConcurrentJcrResourceBundleLoadingTest.java @@ -18,14 +18,6 @@ */ package org.apache.sling.i18n.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -55,6 +47,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; 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.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; + /** * Test case to verify that each bundle is only loaded once, even * if concurrent requests for the same bundle are made. @@ -70,7 +70,8 @@ public class ConcurrentJcrResourceBundleLoadingTest { return Arrays.asList(Boolean.TRUE, Boolean.FALSE); } - @Parameterized.Parameter public Boolean preload = Boolean.FALSE; + @Parameterized.Parameter + public Boolean preload = Boolean.FALSE; private JcrResourceBundleProvider provider; @@ -80,16 +81,20 @@ public class ConcurrentJcrResourceBundleLoadingTest { Scheduler mockScheduler = context.registerService(Scheduler.class, Mockito.mock(Scheduler.class)); // mock this call to avoid a NPE during activation Mockito.doAnswer(invocation -> { - return Mockito.mock(ScheduleOptions.class); - }).when(mockScheduler).NOW(); + return Mockito.mock(ScheduleOptions.class); + }) + .when(mockScheduler) + .NOW(); // Mock the schedule call so we do not wait for the "ResourceBundleProvider: reload all resource bundles" // scheduled job to be completed during activation. That background schedule execution can interfere with // the multi-threaded tests (i.e. the cache gets reset in the middle of doing something) Mockito.doAnswer(invocation -> { - Runnable runnable = invocation.getArgument(0, Runnable.class); - runnable.run(); - return null; - }).when(mockScheduler).schedule(any(Runnable.class), any(ScheduleOptions.class)); + Runnable runnable = invocation.getArgument(0, Runnable.class); + runnable.run(); + return null; + }) + .when(mockScheduler) + .schedule(any(Runnable.class), any(ScheduleOptions.class)); context.registerService(ServiceUserMapped.class, Mockito.mock(ServiceUserMapped.class)); Map<String, Object> configMap = new HashMap<>(); @@ -184,20 +189,22 @@ public class ConcurrentJcrResourceBundleLoadingTest { ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); executorService.scheduleAtFixedRate( - () -> { - ResourceBundle currentBundle = provider.getResourceBundle(Locale.ENGLISH); - if (currentBundle != english) { - // Shutdown the executor once we got the new ResourceBundle. This will cancel the future and opens the gate below. - // Do not assert the returned bundle directly here, as this may become flaky when the bundle returned by the - // mock above was returned but not yet put into the cache. - executorService.shutdownNow(); - newBundleReturned.countDown(); - } - }, - // start with an initial delay to not call getResourceBundle again before we call reloadBundle below - 200, - 200, - TimeUnit.MILLISECONDS); + () -> { + ResourceBundle currentBundle = provider.getResourceBundle(Locale.ENGLISH); + if (currentBundle != english) { + // Shutdown the executor once we got the new ResourceBundle. This will cancel the future and + // opens the gate below. + // Do not assert the returned bundle directly here, as this may become flaky when the bundle + // returned by the + // mock above was returned but not yet put into the cache. + executorService.shutdownNow(); + newBundleReturned.countDown(); + } + }, + // start with an initial delay to not call getResourceBundle again before we call reloadBundle below + 200, + 200, + TimeUnit.MILLISECONDS); provider.reloadBundle(new Key(null, Locale.ENGLISH)); @@ -228,7 +235,17 @@ public class ConcurrentJcrResourceBundleLoadingTest { @Test public void clearCacheInterleavedWithRegistersClearsAllRBs() throws Exception { Map<Locale, List<ResourceBundle>> rbLists = new ConcurrentHashMap<>(); - final Locale[] testLocales = {Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN, Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN, Locale.CHINESE, Locale.SIMPLIFIED_CHINESE, Locale.TRADITIONAL_CHINESE}; + final Locale[] testLocales = { + Locale.ENGLISH, + Locale.FRENCH, + Locale.GERMAN, + Locale.ITALIAN, + Locale.JAPANESE, + Locale.KOREAN, + Locale.CHINESE, + Locale.SIMPLIFIED_CHINESE, + Locale.TRADITIONAL_CHINESE + }; final int numberOfThreads = 100; // Use a barrier to start the execution of all the threads simultaneously once they are all ready @@ -264,4 +281,4 @@ public class ConcurrentJcrResourceBundleLoadingTest { assertFalse(rbList.contains(rb)); } } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProviderTest.java b/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProviderTest.java index 7a938fb..35f6d52 100644 --- a/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProviderTest.java +++ b/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProviderTest.java @@ -19,14 +19,14 @@ package org.apache.sling.i18n.impl; import java.util.Locale; + import org.apache.sling.testing.mock.sling.junit.SlingContext; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; - public class JcrResourceBundleProviderTest { - + @Rule public final SlingContext context = new SlingContext(); @@ -39,7 +39,8 @@ public class JcrResourceBundleProviderTest { Assert.assertEquals(Locale.ENGLISH, JcrResourceBundleProvider.toLocale("en")); Assert.assertEquals(Locale.GERMAN, JcrResourceBundleProvider.toLocale("de")); // for invalid languages assume default language - Assert.assertEquals(new Locale(Locale.getDefault().getLanguage()), JcrResourceBundleProvider.toLocale("invalid")); + Assert.assertEquals( + new Locale(Locale.getDefault().getLanguage()), JcrResourceBundleProvider.toLocale("invalid")); // both language and country being set (no matter whether lower or upper case) Assert.assertEquals(Locale.GERMANY, JcrResourceBundleProvider.toLocale("de_DE")); @@ -50,15 +51,21 @@ public class JcrResourceBundleProviderTest { Assert.assertEquals(Locale.UK, JcrResourceBundleProvider.toLocale("en_gb")); Assert.assertEquals(Locale.UK, JcrResourceBundleProvider.toLocale("EN_gb")); // for invalid languages assume default language - Assert.assertEquals(new Locale(Locale.getDefault().getLanguage(), "GB"), JcrResourceBundleProvider.toLocale("invalid_GB")); + Assert.assertEquals( + new Locale(Locale.getDefault().getLanguage(), "GB"), JcrResourceBundleProvider.toLocale("invalid_GB")); // for invalid countries assume default country - Assert.assertEquals(new Locale("en", Locale.getDefault().getCountry()), JcrResourceBundleProvider.toLocale("en_invalid")); + Assert.assertEquals( + new Locale("en", Locale.getDefault().getCountry()), JcrResourceBundleProvider.toLocale("en_invalid")); // language, country and variant being set - Assert.assertEquals(new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), JcrResourceBundleProvider.toLocale("en_GB_variant1")); + Assert.assertEquals( + new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), + JcrResourceBundleProvider.toLocale("en_GB_variant1")); // parts after the variant are just ignored - Assert.assertEquals(new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), JcrResourceBundleProvider.toLocale("en_GB_variant1_something")); + Assert.assertEquals( + new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), + JcrResourceBundleProvider.toLocale("en_GB_variant1_something")); } @Test @@ -68,14 +75,20 @@ public class JcrResourceBundleProviderTest { Assert.assertEquals(Locale.UK, JcrResourceBundleProvider.toLocale("en-GB")); // for invalid languages assume default language - Assert.assertEquals(new Locale(Locale.getDefault().getLanguage(), "GB"), JcrResourceBundleProvider.toLocale("invalid-GB")); + Assert.assertEquals( + new Locale(Locale.getDefault().getLanguage(), "GB"), JcrResourceBundleProvider.toLocale("invalid-GB")); // for invalid countries assume default country - Assert.assertEquals(new Locale("en", Locale.getDefault().getCountry()), JcrResourceBundleProvider.toLocale("en-invalid")); + Assert.assertEquals( + new Locale("en", Locale.getDefault().getCountry()), JcrResourceBundleProvider.toLocale("en-invalid")); // language, country and variant being set - Assert.assertEquals(new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), JcrResourceBundleProvider.toLocale("en-GB-variant1")); + Assert.assertEquals( + new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), + JcrResourceBundleProvider.toLocale("en-GB-variant1")); // parts after the variant are just ignored - Assert.assertEquals(new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), JcrResourceBundleProvider.toLocale("en-GB-variant1-something-else")); + Assert.assertEquals( + new Locale(Locale.UK.getLanguage(), Locale.UK.getCountry(), "variant1"), + JcrResourceBundleProvider.toLocale("en-GB-variant1-something-else")); } @Test @@ -93,7 +106,8 @@ public class JcrResourceBundleProviderTest { Assert.assertEquals(new Locale(Locale.GERMAN.getLanguage(), "ZZ"), JcrResourceBundleProvider.toLocale("de_ZZ")); // for invalid countries assume default country - Assert.assertEquals(new Locale("en", Locale.getDefault().getCountry()), JcrResourceBundleProvider.toLocale("en-QB")); + Assert.assertEquals( + new Locale("en", Locale.getDefault().getCountry()), JcrResourceBundleProvider.toLocale("en-QB")); // Lowercase Private use Country 'xa' Assert.assertEquals(new Locale(Locale.GERMAN.getLanguage(), "XA"), JcrResourceBundleProvider.toLocale("de_xa")); diff --git a/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider_KeyTest.java b/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider_KeyTest.java index 2a49d2b..13826a7 100644 --- a/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider_KeyTest.java +++ b/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleProvider_KeyTest.java @@ -32,8 +32,8 @@ public class JcrResourceBundleProvider_KeyTest extends TestCase { super.setUp(); try { - Class<?> clazz = getClass().getClassLoader().loadClass( - "org.apache.sling.i18n.impl.JcrResourceBundleProvider$Key"); + Class<?> clazz = + getClass().getClassLoader().loadClass("org.apache.sling.i18n.impl.JcrResourceBundleProvider$Key"); this.ctor = clazz.getDeclaredConstructor(String.class, Locale.class); } catch (Throwable t) { fail("Cannot get JcrResourceBundleProvider.Key constructor: " + t); @@ -80,7 +80,6 @@ public class JcrResourceBundleProvider_KeyTest extends TestCase { assertFalse(key2.equals("string")); } - public void test_key_String_null() { final Object key1 = createKey("base", null); assertNotNull(key1); @@ -107,7 +106,6 @@ public class JcrResourceBundleProvider_KeyTest extends TestCase { assertFalse(key1.equals(createKey(null, null))); } - public void test_key_String_Locale() { final Object key1 = createKey("base", new Locale("de")); assertNotNull(key1); diff --git a/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleTest.java b/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleTest.java index 267fe74..ddda90c 100644 --- a/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleTest.java +++ b/src/test/java/org/apache/sling/i18n/impl/JcrResourceBundleTest.java @@ -18,9 +18,11 @@ */ package org.apache.sling.i18n.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import javax.jcr.Binary; +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.util.TraversingItemVisitor; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -34,12 +36,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import javax.jcr.Binary; -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.util.TraversingItemVisitor; - import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.testing.mock.jcr.MockJcr; import org.apache.sling.testing.mock.jcr.MockQueryResult; @@ -49,6 +45,10 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Tests the {@link JcrResourceBundle} class. */ @@ -67,9 +67,9 @@ public class JcrResourceBundleTest { public void setUp() throws Exception { Session session = getSession(); String[] cndResourcesToLoad = new String[] { - "/org/apache/jackrabbit/oak/builtin_nodetypes.cnd", - "/SLING-INF/nodetypes/jcrlanguage.cnd", - "/SLING-INF/nodetypes/message.cnd" + "/org/apache/jackrabbit/oak/builtin_nodetypes.cnd", + "/SLING-INF/nodetypes/jcrlanguage.cnd", + "/SLING-INF/nodetypes/message.cnd" }; for (String resourceName : cndResourcesToLoad) { URL cndUrl = getClass().getResource(resourceName); @@ -148,7 +148,8 @@ public class JcrResourceBundleTest { } public void createTestContent() throws Exception { - Node i18n = getSession().getRootNode().addNode("libs", "nt:unstructured").addNode("i18n", "nt:unstructured"); + Node i18n = + getSession().getRootNode().addNode("libs", "nt:unstructured").addNode("i18n", "nt:unstructured"); // some DE content Node de = i18n.addNode("de", "nt:folder"); @@ -254,7 +255,8 @@ public class JcrResourceBundleTest { public void test_bundle_parenting() { // set parent of resource bundle, test if passed through JcrResourceBundle bundle = new JcrResourceBundle(new Locale("de"), null, resolver, null, new PathFilter()); - JcrResourceBundle parentBundle = new JcrResourceBundle(new Locale("en"), null, resolver, null, new PathFilter()); + JcrResourceBundle parentBundle = + new JcrResourceBundle(new Locale("en"), null, resolver, null, new PathFilter()); bundle.setParent(parentBundle); parentBundle.setParent(new RootResourceBundle()); @@ -286,7 +288,8 @@ public class JcrResourceBundleTest { while (keys.hasMoreElements()) { counter++; String key = keys.nextElement(); - assertTrue("bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_APPS.containsKey(key)); + assertTrue( + "bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_APPS.containsKey(key)); } assertEquals(MESSAGES_DE.size(), counter); } @@ -334,7 +337,8 @@ public class JcrResourceBundleTest { while (keys.hasMoreElements()) { counter++; String key = keys.nextElement(); - assertTrue("bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_APPS.containsKey(key)); + assertTrue( + "bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_APPS.containsKey(key)); } assertEquals(MESSAGES_DE.size(), counter); } @@ -346,7 +350,7 @@ public class JcrResourceBundleTest { Node de = appsI18n.addNode("de_basename", "nt:unstructured"); de.addMixin("mix:language"); de.setProperty("jcr:language", "de"); - de.setProperty("sling:basename", new String[]{"FOO", "BAR"}); + de.setProperty("sling:basename", new String[] {"FOO", "BAR"}); for (Message msg : MESSAGES_DE_BASENAME.values()) { msg.add(de); } @@ -357,7 +361,7 @@ public class JcrResourceBundleTest { for (Message msg : MESSAGES_DE_BASENAME.values()) { assertEquals(msg.message, bundle.getString(msg.key)); } - + // test getString bundle = new JcrResourceBundle(new Locale("de"), "BAR", resolver, null, new PathFilter()); for (Message msg : MESSAGES_DE_BASENAME.values()) { @@ -370,7 +374,9 @@ public class JcrResourceBundleTest { while (keys.hasMoreElements()) { counter++; String key = keys.nextElement(); - assertTrue("bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_BASENAME.containsKey(key)); + assertTrue( + "bundle returned key that is not supposed to be there: " + key, + MESSAGES_DE_BASENAME.containsKey(key)); } assertEquals(MESSAGES_DE.size(), counter); } @@ -410,9 +416,9 @@ public class JcrResourceBundleTest { while (keys.hasMoreElements()) { counter++; String key = keys.nextElement(); - assertTrue("bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_APPS.containsKey(key)); + assertTrue( + "bundle returned key that is not supposed to be there: " + key, MESSAGES_DE_APPS.containsKey(key)); } assertEquals(MESSAGES_DE.size(), counter); } - } diff --git a/src/test/java/org/apache/sling/i18n/impl/LocatorPathsTest.java b/src/test/java/org/apache/sling/i18n/impl/LocatorPathsTest.java index 01d4bbc..5abb991 100644 --- a/src/test/java/org/apache/sling/i18n/impl/LocatorPathsTest.java +++ b/src/test/java/org/apache/sling/i18n/impl/LocatorPathsTest.java @@ -18,11 +18,11 @@ */ package org.apache.sling.i18n.impl; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import org.junit.Test; - /** * SLING-10135 Test LocatorPaths methods */ @@ -79,7 +79,6 @@ public class LocatorPathsTest { assertEquals(false, paths1.equals(null)); } - @Test public void testHashCode() { LocatorPaths paths1 = new LocatorPaths("/lib/path", 1, 1); @@ -139,5 +138,4 @@ public class LocatorPathsTest { assertNotEquals(paths1, paths2); assertNotEquals(paths1.hashCode(), paths2.hashCode()); } - } diff --git a/src/test/java/org/apache/sling/i18n/impl/Message.java b/src/test/java/org/apache/sling/i18n/impl/Message.java index 86761c4..45072e2 100644 --- a/src/test/java/org/apache/sling/i18n/impl/Message.java +++ b/src/test/java/org/apache/sling/i18n/impl/Message.java @@ -57,4 +57,3 @@ public class Message { node.setProperty("sling:message", message); } } - diff --git a/src/test/java/org/apache/sling/i18n/impl/PathFilterTest.java b/src/test/java/org/apache/sling/i18n/impl/PathFilterTest.java index c02f14d..05da316 100644 --- a/src/test/java/org/apache/sling/i18n/impl/PathFilterTest.java +++ b/src/test/java/org/apache/sling/i18n/impl/PathFilterTest.java @@ -18,11 +18,11 @@ */ package org.apache.sling.i18n.impl; +import org.junit.Test; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; - public class PathFilterTest { @Test diff --git a/src/test/java/org/apache/sling/i18n/it/I18nTestSupport.java b/src/test/java/org/apache/sling/i18n/it/I18nTestSupport.java index 98c67ad..951f146 100644 --- a/src/test/java/org/apache/sling/i18n/it/I18nTestSupport.java +++ b/src/test/java/org/apache/sling/i18n/it/I18nTestSupport.java @@ -37,32 +37,31 @@ public abstract class I18nTestSupport extends TestSupport { @Configuration public Option[] configuration() { return options( - baseConfiguration(), - quickstart(), - // Sling I18N - testBundle("bundle.filename"), - factoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer") - .put("scripts", new String[]{"create service user sling-i18n\n\n set ACL for sling-i18n\n\n allow jcr:read on /\n\n end"}) - .asOption(), - factoryConfiguration("org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended") - .put("user.mapping", new String[]{"org.apache.sling.i18n=sling-i18n"}) - .asOption(), - // testing - newConfiguration("org.apache.sling.jcr.base.internal.LoginAdminWhitelist") - .put("whitelist.bundles.regexp", "PAXEXAM-PROBE-.*") - .asOption(), - junitBundles(), - optionalRemoteDebug(), - optionalJacocoCommand() - ); + baseConfiguration(), + quickstart(), + // Sling I18N + testBundle("bundle.filename"), + factoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer") + .put("scripts", new String[] { + "create service user sling-i18n\n\n set ACL for sling-i18n\n\n allow jcr:read on /\n\n end" + }) + .asOption(), + factoryConfiguration("org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended") + .put("user.mapping", new String[] {"org.apache.sling.i18n=sling-i18n"}) + .asOption(), + // testing + newConfiguration("org.apache.sling.jcr.base.internal.LoginAdminWhitelist") + .put("whitelist.bundles.regexp", "PAXEXAM-PROBE-.*") + .asOption(), + junitBundles(), + optionalRemoteDebug(), + optionalJacocoCommand()); } protected Option quickstart() { final int httpPort = findFreePort(); final String workingDirectory = workingDirectory(); - return composite( - slingQuickstartOakTar(workingDirectory, httpPort) - ); + return composite(slingQuickstartOakTar(workingDirectory, httpPort)); } /** @@ -90,5 +89,4 @@ public abstract class I18nTestSupport extends TestSupport { } return composite(option); } - } diff --git a/src/test/java/org/apache/sling/i18n/it/ResourceBundleLocatorIT.java b/src/test/java/org/apache/sling/i18n/it/ResourceBundleLocatorIT.java index feab011..ad00168 100644 --- a/src/test/java/org/apache/sling/i18n/it/ResourceBundleLocatorIT.java +++ b/src/test/java/org/apache/sling/i18n/it/ResourceBundleLocatorIT.java @@ -18,12 +18,9 @@ */ package org.apache.sling.i18n.it; -import static org.apache.sling.testing.paxexam.SlingOptions.slingBundleresource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.ops4j.pax.exam.CoreOptions.composite; -import static org.ops4j.pax.exam.CoreOptions.streamBundle; -import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd; +import javax.inject.Inject; +import javax.jcr.RepositoryException; +import javax.jcr.Session; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -33,10 +30,8 @@ import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; -import javax.inject.Inject; -import javax.jcr.RepositoryException; -import javax.jcr.Session; - +import com.google.common.collect.ImmutableListMultimap; +import com.google.common.collect.Multimap; import org.apache.commons.io.IOUtils; import org.apache.sling.i18n.ResourceBundleProvider; import org.apache.sling.jcr.api.SlingRepository; @@ -55,8 +50,12 @@ import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.Multimap; +import static org.apache.sling.testing.paxexam.SlingOptions.slingBundleresource; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.ops4j.pax.exam.CoreOptions.composite; +import static org.ops4j.pax.exam.CoreOptions.streamBundle; +import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd; /** * Tests for SLING-10135 for locating resource bundle resources @@ -66,7 +65,7 @@ import com.google.common.collect.Multimap; @ExamReactorStrategy(PerClass.class) public class ResourceBundleLocatorIT extends I18nTestSupport { private final Logger logger = LoggerFactory.getLogger(ResourceBundleLocatorIT.class); - + public static final String MSG_KEY1 = "hello"; public static final String MSG_KEY2 = "test1"; @@ -91,34 +90,33 @@ public class ResourceBundleLocatorIT extends I18nTestSupport { public Option[] configuration() { // create 4 tiny bundles with different configurations for testing Option[] bundle = new Option[7]; - for (int i=0; i <=6; i++) { + for (int i = 0; i <= 6; i++) { String bundleSymbolicName = String.format("TEST-I18N-BUNDLE-%d", i); String baseName = String.format("org.apache.sling.i18n.testing%d.Resources", i); String traversePath; if (i == 5) { - traversePath = ""; + traversePath = ""; } else if (i == 6) { - traversePath = null; + traversePath = null; } else { - traversePath = String.format("/libs/i18n/testing%d", i); //NOSONAR + traversePath = String.format("/libs/i18n/testing%d", i); // NOSONAR } String resourcePath; if (i <= 1) { - resourcePath = String.format("/libs/i18n/testing%d", i); //NOSONAR + resourcePath = String.format("/libs/i18n/testing%d", i); // NOSONAR } else if (i == 2) { - resourcePath = String.format("/libs/i18n/testing%d/folder1", i); //NOSONAR + resourcePath = String.format("/libs/i18n/testing%d/folder1", i); // NOSONAR } else { - resourcePath = String.format("/libs/i18n/testing%d/folder1/folder2", i); //NOSONAR + resourcePath = String.format("/libs/i18n/testing%d/folder1/folder2", i); // NOSONAR } String pathInBundle = String.format("SLING-INF%s", resourcePath); final Multimap<String, String> content = ImmutableListMultimap.of( pathInBundle, "Resources.json", pathInBundle, "Resources.json.props", pathInBundle, "Resources_en_CA.json", - pathInBundle, "Resources_en_CA.json.props" - ); + pathInBundle, "Resources_en_CA.json.props"); int traverseDepth; if (i < 4) { traverseDepth = i; @@ -126,25 +124,22 @@ public class ResourceBundleLocatorIT extends I18nTestSupport { traverseDepth = 1; } try { - bundle[i] = buildContentBundle(bundleSymbolicName, - pathInBundle, resourcePath, - traversePath, traverseDepth, - content, baseName); + bundle[i] = buildContentBundle( + bundleSymbolicName, pathInBundle, resourcePath, traversePath, traverseDepth, content, baseName); } catch (IOException e) { throw new RuntimeException("Failed to build the content bundle", e); } } - - return composite(composite(super.configuration()), - slingBundleresource(), - composite(bundle)) + + return composite(composite(super.configuration()), slingBundleresource(), composite(bundle)) .getOptions(); } /** * Add content to our test bundle */ - protected void addContent(final TinyBundle bundle, String pathInBundle, String resourcePath, Object ... args) throws IOException { + protected void addContent(final TinyBundle bundle, String pathInBundle, String resourcePath, Object... args) + throws IOException { pathInBundle += "/" + resourcePath; resourcePath = "/test-content/" + resourcePath; try (final InputStream is = getClass().getResourceAsStream(resourcePath)) { @@ -162,25 +157,40 @@ public class ResourceBundleLocatorIT extends I18nTestSupport { } } - protected Option buildContentBundle(String bundleSymbolicName, - String pathInBundle, String resourcePath, - String traversePath, int traverseDepth, - final Multimap<String, String> content, String basename) throws IOException { + protected Option buildContentBundle( + String bundleSymbolicName, + String pathInBundle, + String resourcePath, + String traversePath, + int traverseDepth, + final Multimap<String, String> content, + String basename) + throws IOException { final TinyBundle bundle = TinyBundles.bundle(); bundle.set(Constants.BUNDLE_SYMBOLICNAME, bundleSymbolicName); - bundle.set(Constants.REQUIRE_CAPABILITY, "osgi.extender;filter:=\"(&(osgi.extender=org.apache.sling.i18n.resourcebundle.locator.registrar)(version<=1.0.0)(!(version>=2.0.0)))\""); + bundle.set( + Constants.REQUIRE_CAPABILITY, + "osgi.extender;filter:=\"(&(osgi.extender=org.apache.sling.i18n.resourcebundle.locator.registrar)(version<=1.0.0)(!(version>=2.0.0)))\""); if (traverseDepth <= 0) { - if (traversePath == null) { + if (traversePath == null) { bundle.set(Constants.PROVIDE_CAPABILITY, "org.apache.sling.i18n.resourcebundle.locator"); - } else { - bundle.set(Constants.PROVIDE_CAPABILITY, String.format("org.apache.sling.i18n.resourcebundle.locator;paths=\"%s\"", traversePath)); - } + } else { + bundle.set( + Constants.PROVIDE_CAPABILITY, + String.format("org.apache.sling.i18n.resourcebundle.locator;paths=\"%s\"", traversePath)); + } } else { - if (traversePath == null) { - bundle.set(Constants.PROVIDE_CAPABILITY, String.format("org.apache.sling.i18n.resourcebundle.locator;depth=%d", traverseDepth)); - } else { - bundle.set(Constants.PROVIDE_CAPABILITY, String.format("org.apache.sling.i18n.resourcebundle.locator;paths=\"%s\";depth=%d", traversePath, traverseDepth)); - } + if (traversePath == null) { + bundle.set( + Constants.PROVIDE_CAPABILITY, + String.format("org.apache.sling.i18n.resourcebundle.locator;depth=%d", traverseDepth)); + } else { + bundle.set( + Constants.PROVIDE_CAPABILITY, + String.format( + "org.apache.sling.i18n.resourcebundle.locator;paths=\"%s\";depth=%d", + traversePath, traverseDepth)); + } } bundle.set("Sling-Bundle-Resources", String.format("%s;path:=%s;propsJSON:=props", resourcePath, pathInBundle)); @@ -195,9 +205,7 @@ public class ResourceBundleLocatorIT extends I18nTestSupport { addContent(bundle, entryPathInBundle, entryResourcePath); } } - return streamBundle( - bundle.build(withBnd()) - ).start(); + return streamBundle(bundle.build(withBnd())).start(); } @Before diff --git a/src/test/java/org/apache/sling/i18n/it/ResourceBundleProviderIT.java b/src/test/java/org/apache/sling/i18n/it/ResourceBundleProviderIT.java index 047d424..ed2419b 100644 --- a/src/test/java/org/apache/sling/i18n/it/ResourceBundleProviderIT.java +++ b/src/test/java/org/apache/sling/i18n/it/ResourceBundleProviderIT.java @@ -18,14 +18,14 @@ */ package org.apache.sling.i18n.it; -import java.util.Locale; -import java.util.ResourceBundle; - import javax.inject.Inject; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; +import java.util.Locale; +import java.util.ResourceBundle; + import org.apache.sling.i18n.ResourceBundleProvider; import org.apache.sling.jcr.api.SlingRepository; import org.junit.After; @@ -65,8 +65,7 @@ public class ResourceBundleProviderIT extends I18nTestSupport { private Node enRoot; private Node enBasenameRoot; - - static abstract class Retry { + abstract static class Retry { Retry(int timeoutMsec) { final long timeout = System.currentTimeMillis() + timeoutMsec; Throwable lastT = null; @@ -136,7 +135,8 @@ public class ResourceBundleProviderIT extends I18nTestSupport { @Override protected void exec() { { - final ResourceBundle resourceBundle = resourceBundleProvider.getResourceBundle(basename, locale); // this is the resource bundle for de_DE + final ResourceBundle resourceBundle = resourceBundleProvider.getResourceBundle( + basename, locale); // this is the resource bundle for de_DE assertNotNull(resourceBundle); assertEquals(value, resourceBundle.getString(key)); } @@ -144,7 +144,8 @@ public class ResourceBundleProviderIT extends I18nTestSupport { }; } - private void assertMessages(final String key, final String deMessage, final String deDeMessage, final String frMessage) { + private void assertMessages( + final String key, final String deMessage, final String deDeMessage, final String frMessage) { assertMessage(key, Locale.GERMAN, null, deMessage); assertMessage(key, Locale.GERMANY, null, deDeMessage); assertMessage(key, Locale.FRENCH, null, frMessage); @@ -216,5 +217,4 @@ public class ResourceBundleProviderIT extends I18nTestSupport { assertMessage(MSG_KEY3, Locale.ENGLISH, null, "EN_basename_changed"); assertMessage(MSG_KEY3, Locale.ENGLISH, BASENAME, "EN_basename_changed"); } - }
