This is an automated email from the ASF dual-hosted git repository. kwin pushed a commit to branch feature/parent-61 in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-installer-factory-configuration.git
commit b304c79ea9f5af23daa4ba194f546f3007f7617b Author: Konrad Windszus <[email protected]> AuthorDate: Tue Nov 12 17:42:15 2024 +0100 SLING-12480 Reformat with spotless --- pom.xml | 39 +++--- .../configuration/impl/AbstractConfigTask.java | 6 +- .../factories/configuration/impl/Activator.java | 15 +- .../configuration/impl/ConfigInstallTask.java | 66 +++++---- .../configuration/impl/ConfigRemoveTask.java | 28 ++-- .../configuration/impl/ConfigTaskCreator.java | 116 ++++++++------- .../configuration/impl/ConfigUpdateHandler.java | 80 ++++++----- .../factories/configuration/impl/ConfigUtil.java | 89 ++++++------ .../ConfigurationSerializerWebConsolePlugin.java | 100 +++++++------ .../factories/configuration/impl/Coordinator.java | 19 ++- .../configuration/impl/MetatypeHandler.java | 61 ++++---- .../configuration/impl/ServicesListener.java | 66 +++++---- .../impl/WebconsoleConfigurationHandler.java | 12 +- .../factories/configuration/package-info.java | 2 - .../impl/ConfigUpdateHandlerTest.java | 34 +++-- .../configuration/impl/ConfigUtilTest.java | 48 ++++--- .../configuration/impl/MetatypeHandlerTest.java | 156 +++++++++++---------- 17 files changed, 499 insertions(+), 438 deletions(-) diff --git a/pom.xml b/pom.xml index 38d240a..6df06ab 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ +<?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 @@ -29,34 +30,18 @@ <version>1.4.7-SNAPSHOT</version> <name>Apache Sling Installer Configuration Factory</name> - <description> - Provides support for configurations to the Apache Sling OSGi installer - </description> - - <properties> - <sling.java.version>8</sling.java.version> - </properties> + <description>Provides support for configurations to the Apache Sling OSGi installer</description> <scm> <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-installer-factory-configuration.git</connection> <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-installer-factory-configuration.git</developerConnection> - <url>https://github.com/apache/sling-org-apache-sling-installer-factory-configuration.git</url> <tag>HEAD</tag> + <url>https://github.com/apache/sling-org-apache-sling-installer-factory-configuration.git</url> </scm> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <configuration> - <excludePackageNames> - org.apache.sling.installer.factories.configuration.impl - </excludePackageNames> - </configuration> - </plugin> - </plugins> - </build> + <properties> + <sling.java.version>8</sling.java.version> + </properties> <dependencies> <!-- OSGi annotations (OSGi R7) --> @@ -150,4 +135,16 @@ <scope>test</scope> </dependency> </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <configuration> + <excludePackageNames>org.apache.sling.installer.factories.configuration.impl</excludePackageNames> + </configuration> + </plugin> + </plugins> + </build> </project> diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/AbstractConfigTask.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/AbstractConfigTask.java index 14ce1b1..ddfe454 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/AbstractConfigTask.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/AbstractConfigTask.java @@ -46,8 +46,8 @@ abstract class AbstractConfigTask extends InstallTask { AbstractConfigTask(final TaskResourceGroup r, final ConfigurationAdmin configAdmin) { super(r); this.configAdmin = configAdmin; - this.configPid = (String)getResource().getAttribute(Constants.SERVICE_PID); - this.factoryPid = (String)getResource().getAttribute(ConfigurationAdmin.SERVICE_FACTORYPID); + this.configPid = (String) getResource().getAttribute(Constants.SERVICE_PID); + this.factoryPid = (String) getResource().getAttribute(ConfigurationAdmin.SERVICE_FACTORYPID); } protected Logger getLogger() { @@ -55,7 +55,7 @@ abstract class AbstractConfigTask extends InstallTask { } protected String getRealPID() { - if ( this.factoryPid != null ) { + if (this.factoryPid != null) { return ConfigUtil.getPIDOfFactoryPID(this.factoryPid, this.configPid); } else { return this.configPid; diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/Activator.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/Activator.java index cdf0092..f1c53a0 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/Activator.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/Activator.java @@ -45,19 +45,20 @@ public class Activator implements BundleActivator { public static List<String> MERGE_SCHEMES; - /** * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(final BundleContext context) throws Exception { - if ( context.getProperty(PROP_LOCATION_DEFAULT) != null ) { - final Boolean bool = Boolean.valueOf(context.getProperty(PROP_LOCATION_DEFAULT).toString()); - if ( bool.booleanValue() ) { + if (context.getProperty(PROP_LOCATION_DEFAULT) != null) { + final Boolean bool = + Boolean.valueOf(context.getProperty(PROP_LOCATION_DEFAULT).toString()); + if (bool.booleanValue()) { DEFAULT_LOCATION = "?"; } } - if ( context.getProperty(PROP_MERGE_SCHEMES) != null ) { - MERGE_SCHEMES = Arrays.asList(context.getProperty(PROP_MERGE_SCHEMES).split(",")); + if (context.getProperty(PROP_MERGE_SCHEMES) != null) { + MERGE_SCHEMES = + Arrays.asList(context.getProperty(PROP_MERGE_SCHEMES).split(",")); } this.listener = new ServicesListener(context); } @@ -66,7 +67,7 @@ public class Activator implements BundleActivator { * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(final BundleContext context) { - if ( this.listener != null ) { + if (this.listener != null) { this.listener.deactivate(); this.listener = null; } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigInstallTask.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigInstallTask.java index 3e54698..3959601 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigInstallTask.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigInstallTask.java @@ -50,26 +50,26 @@ public class ConfigInstallTask extends AbstractConfigTask { return CONFIG_INSTALL_ORDER + getRealPID(); } - @Override + @Override protected Dictionary<String, Object> getDictionary() { Dictionary<String, Object> properties = super.getDictionary(); - if ( Activator.MERGE_SCHEMES != null ) { + if (Activator.MERGE_SCHEMES != null) { final List<Dictionary<String, Object>> propertiesList = new ArrayList<>(); propertiesList.add(properties); final Iterator<TaskResource> iter = this.getResourceGroup().getActiveResourceIterator(); - if ( iter != null ) { + if (iter != null) { // skip first active resource iter.next(); - while ( iter.hasNext()) { + while (iter.hasNext()) { final TaskResource rsrc = iter.next(); - - if ( Activator.MERGE_SCHEMES.contains(rsrc.getScheme())) { + + if (Activator.MERGE_SCHEMES.contains(rsrc.getScheme())) { propertiesList.add(rsrc.getDictionary()); } } } - if ( propertiesList.size() > 1 ) { + if (propertiesList.size() > 1) { properties = ConfigUtil.mergeReverseOrder(propertiesList); } } @@ -78,53 +78,65 @@ public class ConfigInstallTask extends AbstractConfigTask { @Override public void execute(final InstallationContext ctx) { - synchronized ( Coordinator.SHARED ) { + synchronized (Coordinator.SHARED) { // Get or create configuration, but do not // update if the new one has the same values. final Dictionary<String, Object> properties = this.getDictionary(); boolean created = false; try { - String location = (String)properties.get(ConfigurationConstants.PROPERTY_BUNDLE_LOCATION); - if ( location == null ) { + String location = (String) properties.get(ConfigurationConstants.PROPERTY_BUNDLE_LOCATION); + if (location == null) { location = Activator.DEFAULT_LOCATION; // default - } else if ( location.length() == 0 ) { + } else if (location.length() == 0) { location = null; } - Configuration config = ConfigUtil.getConfiguration(this.getConfigurationAdmin(), this.factoryPid, this.configPid); + Configuration config = + ConfigUtil.getConfiguration(this.getConfigurationAdmin(), this.factoryPid, this.configPid); if (config == null) { - config = ConfigUtil.createConfiguration(this.getConfigurationAdmin(), this.factoryPid, this.configPid, location); + config = ConfigUtil.createConfiguration( + this.getConfigurationAdmin(), this.factoryPid, this.configPid, location); created = true; } else { - if (ConfigUtil.isSameData(config.getProperties(), properties)) { - this.getLogger().debug("Configuration {} already installed with same data, update request ignored: {}", - config.getPid(), getResource()); - config = null; - } else { + if (ConfigUtil.isSameData(config.getProperties(), properties)) { + this.getLogger() + .debug( + "Configuration {} already installed with same data, update request ignored: {}", + config.getPid(), + getResource()); + config = null; + } else { config.setBundleLocation(location); - } + } } if (config != null) { config.update(properties); ctx.log("Installed configuration {} from resource {}", config.getPid(), getResource()); - this.getLogger().debug("Configuration " + config.getPid() - + " " + (created ? "created" : "updated") - + " from " + getResource()); + this.getLogger() + .debug("Configuration " + config.getPid() + + " " + (created ? "created" : "updated") + + " from " + getResource()); final Operation op = new Coordinator.Operation(config.getPid(), config.getFactoryPid(), false); Coordinator.SHARED.add(op); } // in any case set the state to "INSTALLED" - // (it doesn't matter if the configuration hasn't been updated as it has been in the correct state already) + // (it doesn't matter if the configuration hasn't been updated as it has been in the correct state + // already) this.setFinishedState(ResourceState.INSTALLED); - } catch (IOException|IllegalStateException e) { - this.getLogger().debug("Temporary exception during installation of config " + this.getResource() + " : " + e.getMessage() + ". Retrying later.", e); + } catch (IOException | IllegalStateException e) { + this.getLogger() + .debug( + "Temporary exception during installation of config " + this.getResource() + " : " + + e.getMessage() + ". Retrying later.", + e); } catch (Exception e) { - String message = MessageFormat.format("Exception during installation of config {0} : {1}", this.getResource(), e.getMessage()); + String message = MessageFormat.format( + "Exception during installation of config {0} : {1}", this.getResource(), e.getMessage()); this.getLogger().error(message, e); this.setFinishedState(ResourceState.IGNORED, null, message); } } } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigRemoveTask.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigRemoveTask.java index 0e323c4..ce66800 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigRemoveTask.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigRemoveTask.java @@ -29,8 +29,7 @@ public class ConfigRemoveTask extends AbstractConfigTask { private static final String CONFIG_REMOVE_ORDER = "10-"; - public ConfigRemoveTask(final TaskResourceGroup r, - final ConfigurationAdmin configAdmin) { + public ConfigRemoveTask(final TaskResourceGroup r, final ConfigurationAdmin configAdmin) { super(r, configAdmin); } @@ -44,16 +43,23 @@ public class ConfigRemoveTask extends AbstractConfigTask { */ @Override public void execute(final InstallationContext ctx) { - synchronized ( Coordinator.SHARED ) { + synchronized (Coordinator.SHARED) { try { - Configuration cfg = ConfigUtil.getConfiguration(this.getConfigurationAdmin(), this.factoryPid, this.configPid); + Configuration cfg = + ConfigUtil.getConfiguration(this.getConfigurationAdmin(), this.factoryPid, this.configPid); if (cfg == null) { - this.getLogger().debug("Cannot delete config , pid={} not found, ignored ({})", getRealPID(), getResource()); + this.getLogger() + .debug( + "Cannot delete config , pid={} not found, ignored ({})", + getRealPID(), + getResource()); } else { - if ( !ConfigUtil.isSameData(cfg.getProperties(), this.getResource().getDictionary()) ) { + if (!ConfigUtil.isSameData( + cfg.getProperties(), this.getResource().getDictionary())) { this.getLogger().debug("Configuration has changed after it has been installed!"); } else { - final Coordinator.Operation op = new Coordinator.Operation(cfg.getPid(), cfg.getFactoryPid(), true); + final Coordinator.Operation op = + new Coordinator.Operation(cfg.getPid(), cfg.getFactoryPid(), true); this.getLogger().debug("Deleting config {} ({})", getRealPID(), getResource()); cfg.delete(); @@ -63,10 +69,14 @@ public class ConfigRemoveTask extends AbstractConfigTask { } } } catch (final Exception e) { - this.getLogger().debug("Exception during removal of config " + this.getResource() + " : " + e.getMessage() + ". Retrying later.", e); + this.getLogger() + .debug( + "Exception during removal of config " + this.getResource() + " : " + e.getMessage() + + ". Retrying later.", + e); } // we always set to uninstalled as the resource really has been deleted this.setFinishedState(ResourceState.UNINSTALLED); } } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigTaskCreator.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigTaskCreator.java index e555095..9921d69 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigTaskCreator.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigTaskCreator.java @@ -56,10 +56,10 @@ import org.slf4j.LoggerFactory; /** * Task creator for configurations. */ -public class ConfigTaskCreator - implements InstallTaskFactory, ConfigurationListener, ResourceTransformer { +public class ConfigTaskCreator implements InstallTaskFactory, ConfigurationListener, ResourceTransformer { - private static final Pattern FELIX_FACTORY_CONFIG_PATTERN = Pattern.compile("(.*)\\.([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})"); + private static final Pattern FELIX_FACTORY_CONFIG_PATTERN = + Pattern.compile("(.*)\\.([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})"); /** Logger. */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @@ -73,7 +73,8 @@ public class ConfigTaskCreator /** Info Provider */ private final InfoProvider infoProvider; - public ConfigTaskCreator(final ResourceChangeListener listener, + public ConfigTaskCreator( + final ResourceChangeListener listener, final ConfigurationAdmin configAdmin, final InfoProvider infoProvider) { this.changeListener = listener; @@ -88,78 +89,83 @@ public class ConfigTaskCreator props.put(InstallTaskFactory.NAME, "org.osgi.service.cm"); props.put(ResourceTransformer.NAME, "org.osgi.service.cm"); - final String [] serviceInterfaces = { - InstallTaskFactory.class.getName(), - ConfigurationListener.class.getName(), - ResourceTransformer.class.getName() + final String[] serviceInterfaces = { + InstallTaskFactory.class.getName(), + ConfigurationListener.class.getName(), + ResourceTransformer.class.getName() }; final ServiceRegistration<?> reg = bundleContext.registerService(serviceInterfaces, this, props); - this.logger.info("OSGi Configuration support for OSGi installer active, default location={}, merge schemes={}", - Activator.DEFAULT_LOCATION, Activator.MERGE_SCHEMES); + this.logger.info( + "OSGi Configuration support for OSGi installer active, default location={}, merge schemes={}", + Activator.DEFAULT_LOCATION, + Activator.MERGE_SCHEMES); return reg; } /** * Create a task to install or uninstall a configuration. * - * @see org.apache.sling.installer.api.tasks.InstallTaskFactory#createTask(org.apache.sling.installer.api.tasks.TaskResourceGroup) - */ - @Override + * @see org.apache.sling.installer.api.tasks.InstallTaskFactory#createTask(org.apache.sling.installer.api.tasks.TaskResourceGroup) + */ + @Override public InstallTask createTask(final TaskResourceGroup group) { final TaskResource toActivate = group.getActiveResource(); - if ( !toActivate.getType().equals(InstallableResource.TYPE_CONFIG) ) { + if (!toActivate.getType().equals(InstallableResource.TYPE_CONFIG)) { return null; } final InstallTask result; - if (toActivate.getState() == ResourceState.UNINSTALL) { + if (toActivate.getState() == ResourceState.UNINSTALL) { // if this is an uninstall, check if we have to install an older version // in this case we should do an update instead of uninstall/install (!) final TaskResource second = group.getNextActiveResource(); - if ( second != null - && ( second.getState() == ResourceState.IGNORED || second.getState() == ResourceState.INSTALLED || second.getState() == ResourceState.INSTALL ) - && ( second.getDictionary() == null || second.getDictionary().get(InstallableResource.RESOURCE_IS_TEMPLATE) == null)) { + if (second != null + && (second.getState() == ResourceState.IGNORED + || second.getState() == ResourceState.INSTALLED + || second.getState() == ResourceState.INSTALL) + && (second.getDictionary() == null + || second.getDictionary().get(InstallableResource.RESOURCE_IS_TEMPLATE) == null)) { result = new ChangeStateTask(group, ResourceState.UNINSTALLED); } else { result = new ConfigRemoveTask(group, this.configAdmin); } - } else { - result = new ConfigInstallTask(group, this.configAdmin); - } - return result; - } + } else { + result = new ConfigInstallTask(group, this.configAdmin); + } + return result; + } /** * @see org.osgi.service.cm.ConfigurationListener#configurationEvent(org.osgi.service.cm.ConfigurationEvent) */ @Override public void configurationEvent(final ConfigurationEvent event) { - synchronized ( Coordinator.SHARED ) { - if ( event.getType() == ConfigurationEvent.CM_DELETED ) { + synchronized (Coordinator.SHARED) { + if (event.getType() == ConfigurationEvent.CM_DELETED) { final Coordinator.Operation op = Coordinator.SHARED.get(event.getPid(), event.getFactoryPid(), true); - if ( op == null ) { + if (op == null) { this.changeListener.resourceRemoved(InstallableResource.TYPE_CONFIG, event.getPid()); } else { this.logger.debug("Ignoring configuration event for {}:{}", event.getPid(), event.getFactoryPid()); } - } else if ( event.getType() == ConfigurationEvent.CM_UPDATED ) { + } else if (event.getType() == ConfigurationEvent.CM_UPDATED) { try { // we just need to pass in the pid as we're using named factory configs - final Configuration config = ConfigUtil.getConfiguration(configAdmin, - null, - event.getPid()); - final Coordinator.Operation op = Coordinator.SHARED.get(event.getPid(), event.getFactoryPid(), false); - if ( config != null && op == null ) { - final boolean persist = ConfigUtil.toBoolean(config.getProperties().get(ConfigurationConstants.PROPERTY_PERSISTENCE), true); + final Configuration config = ConfigUtil.getConfiguration(configAdmin, null, event.getPid()); + final Coordinator.Operation op = + Coordinator.SHARED.get(event.getPid(), event.getFactoryPid(), false); + if (config != null && op == null) { + final boolean persist = ConfigUtil.toBoolean( + config.getProperties().get(ConfigurationConstants.PROPERTY_PERSISTENCE), true); final Dictionary<String, Object> dict = ConfigUtil.cleanConfiguration(config.getProperties()); final Map<String, Object> attrs = new HashMap<>(); - if ( !persist ) { + if (!persist) { attrs.put(ResourceChangeListener.RESOURCE_PERSIST, Boolean.FALSE); } attrs.put(Constants.SERVICE_PID, event.getPid()); attrs.put(InstallableResource.RESOURCE_URI_HINT, event.getPid()); - if ( config.getBundleLocation() != null ) { + if (config.getBundleLocation() != null) { attrs.put(InstallableResource.INSTALLATION_HINT, config.getBundleLocation()); } // Factory? @@ -168,12 +174,14 @@ public class ConfigTaskCreator } removeDefaultProperties(this.infoProvider, event.getPid(), dict); - this.changeListener.resourceAddedOrUpdated(InstallableResource.TYPE_CONFIG, event.getPid(), null, dict, attrs); + this.changeListener.resourceAddedOrUpdated( + InstallableResource.TYPE_CONFIG, event.getPid(), null, dict, attrs); } else { - this.logger.debug("Ignoring configuration event for {}:{}", event.getPid(), event.getFactoryPid()); + this.logger.debug( + "Ignoring configuration event for {}:{}", event.getPid(), event.getFactoryPid()); } - } catch ( final Exception ignore) { + } catch (final Exception ignore) { // ignore for now } } @@ -181,24 +189,24 @@ public class ConfigTaskCreator } public static Dictionary<String, Object> getDefaultProperties(final InfoProvider infoProvider, final String pid) { - if ( Activator.MERGE_SCHEMES != null ) { + if (Activator.MERGE_SCHEMES != null) { final List<Dictionary<String, Object>> propertiesList = new ArrayList<>(); final String entityId = InstallableResource.TYPE_CONFIG.concat(":").concat(pid); boolean done = false; - for(final ResourceGroup group : infoProvider.getInstallationState().getInstalledResources()) { - for(final Resource rsrc : group.getResources()) { - if ( rsrc.getEntityId().equals(entityId) ) { + for (final ResourceGroup group : infoProvider.getInstallationState().getInstalledResources()) { + for (final Resource rsrc : group.getResources()) { + if (rsrc.getEntityId().equals(entityId)) { done = true; - if ( Activator.MERGE_SCHEMES.contains(rsrc.getScheme()) ) { + if (Activator.MERGE_SCHEMES.contains(rsrc.getScheme())) { propertiesList.add(rsrc.getDictionary()); } } } - if ( done ) { + if (done) { break; } } - if ( !propertiesList.isEmpty() ) { + if (!propertiesList.isEmpty()) { final Dictionary<String, Object> defaultProps = ConfigUtil.mergeReverseOrder(propertiesList); return defaultProps; } @@ -206,10 +214,11 @@ public class ConfigTaskCreator return null; } - public static void removeDefaultProperties(final InfoProvider infoProvider, final String pid, final Dictionary<String, Object> dict) { - if ( Activator.MERGE_SCHEMES != null ) { + public static void removeDefaultProperties( + final InfoProvider infoProvider, final String pid, final Dictionary<String, Object> dict) { + if (Activator.MERGE_SCHEMES != null) { final Dictionary<String, Object> defaultProps = getDefaultProperties(infoProvider, pid); - if ( defaultProps != null ) { + if (defaultProps != null) { ConfigUtil.removeRedundantProperties(dict, defaultProps); } } @@ -220,7 +229,7 @@ public class ConfigTaskCreator */ @Override public TransformationResult[] transform(final RegisteredResource resource) { - if ( resource.getType().equals(InstallableResource.TYPE_PROPERTIES) ) { + if (resource.getType().equals(InstallableResource.TYPE_PROPERTIES)) { return checkConfiguration(resource); } return null; @@ -229,12 +238,12 @@ public class ConfigTaskCreator private static String getResourceId(final String rawUrl) { final String url = separatorsToUnix(rawUrl); int pos = url.lastIndexOf('/'); - if ( pos == -1 ) { + if (pos == -1) { pos = url.indexOf(':'); } final String lastIdPart; - if ( pos != -1 ) { + if (pos != -1) { lastIdPart = url.substring(pos + 1); } else { lastIdPart = url; @@ -299,9 +308,10 @@ public class ConfigTaskCreator } private static final List<String> EXTENSIONS = Arrays.asList(".config", ".properties", ".cfg", ".cfg.json"); + private static String removeConfigExtension(final String id) { - for(final String ext : EXTENSIONS) { - if ( id.endsWith(ext) ) { + for (final String ext : EXTENSIONS) { + if (id.endsWith(ext)) { return id.substring(0, id.length() - ext.length()); } } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandler.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandler.java index e4d7b12..cdc9320 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandler.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandler.java @@ -48,9 +48,7 @@ public class ConfigUpdateHandler implements ResourceUpdater { private final ServicesListener activator; - - public ConfigUpdateHandler(final ConfigurationAdmin configAdmin, - final ServicesListener activator) { + public ConfigUpdateHandler(final ConfigurationAdmin configAdmin, final ServicesListener activator) { this.configAdmin = configAdmin; this.activator = activator; } @@ -60,30 +58,33 @@ public class ConfigUpdateHandler implements ResourceUpdater { props.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Configuration Install Task Factory Update Handler"); props.put(Constants.SERVICE_VENDOR, ServicesListener.VENDOR); - final String [] serviceInterfaces = { - ResourceUpdater.class.getName() - }; + final String[] serviceInterfaces = {ResourceUpdater.class.getName()}; return bundleContext.registerService(serviceInterfaces, this, props); } @Override public void update(final Collection<UpdatableResourceGroup> groups) { - for(final UpdatableResourceGroup group : groups) { + for (final UpdatableResourceGroup group : groups) { update(group); } this.activator.finishedUpdating(); } private void update(final UpdatableResourceGroup group) { - if ( this.activator.isActive() ) { + if (this.activator.isActive()) { // check if the group handles configurations and has an alias (aka factory config) - if ( InstallableResource.TYPE_CONFIG.equals(group.getResourceType()) ) { - if(group.getAlias() == null && group.getId().contains("~") && group.getId().contains("-")){ + if (InstallableResource.TYPE_CONFIG.equals(group.getResourceType())) { + if (group.getAlias() == null + && group.getId().contains("~") + && group.getId().contains("-")) { // new format config with ~ as separator, cleanup if duplicate old format config exists this.cleanupDuplicateFactoryConfig(group); } else { if (group.getAlias() != null || group.getId().contains("-")) { - this.logger.debug("Configuration going under updation is : {} with alias : {}", group.getId(), group.getAlias()); + this.logger.debug( + "Configuration going under updation is : {} with alias : {}", + group.getId(), + group.getAlias()); this.updateFactoryConfig(group); } } @@ -100,8 +101,8 @@ public class ConfigUpdateHandler implements ResourceUpdater { if (alias.startsWith(oldId)) { final int lastDotIndex = oldId.length(); final String factoryIdString = alias.substring(0, lastDotIndex + 1); // keep it +1 to have last dot - // intact so that we always have - // even dots in the string + // intact so that we always have + // even dots in the string factoryPid = alias.substring(0, getMiddleDotSplitIndex(factoryIdString)); pid = alias.substring(lastDotIndex + 1); @@ -117,21 +118,24 @@ public class ConfigUpdateHandler implements ResourceUpdater { pid = oldId.substring(factoryPid.length() + 1); } } else { - // extract factory id for these cases where alias is not available and factoryId and pid need to be separated from the old id string itself - //format assumption ::: "factory_pid.factory_pid.pid" - // split pid with lastIndexOf('.') then remove the duplicate factory_pid part from the remaining string using the middle dot split index + // extract factory id for these cases where alias is not available and factoryId and pid need to be + // separated from the old id string itself + // format assumption ::: "factory_pid.factory_pid.pid" + // split pid with lastIndexOf('.') then remove the duplicate factory_pid part from the remaining string + // using the middle dot split index final int lastDotIndex = oldId.lastIndexOf('.'); - if(lastDotIndex < 0) { //when oldId does not contain any dot + if (lastDotIndex < 0) { // when oldId does not contain any dot factoryPid = oldId; } else { - final String factoryIdString = oldId.substring(0, lastDotIndex + 1); // keep it +1 to have last dot intact - // so that we always have even dots in the string + final String factoryIdString = + oldId.substring(0, lastDotIndex + 1); // keep it +1 to have last dot intact + // so that we always have even dots in the string factoryPid = oldId.substring(0, getMiddleDotSplitIndex(factoryIdString)); } - pid = oldId.substring(lastDotIndex+1); + pid = oldId.substring(lastDotIndex + 1); } - return new String[] { factoryPid, pid }; + return new String[] {factoryPid, pid}; } private int getMiddleDotSplitIndex(final String strId) { @@ -139,14 +143,13 @@ public class ConfigUpdateHandler implements ResourceUpdater { int dotCount = 0; int[] dotIndexArray = new int[strId.length()]; - for (int i=0;i<strId.length();i++) - + for (int i = 0; i < strId.length(); i++) if (strId.charAt(i) == '.') { dotCount++; dotIndexArray[dotCount] = i; } - return dotIndexArray[dotCount/2]; // get the middle dot index + return dotIndexArray[dotCount / 2]; // get the middle dot index } private void updateFactoryConfig(final UpdatableResourceGroup group) { @@ -167,7 +170,7 @@ public class ConfigUpdateHandler implements ResourceUpdater { this.logger.debug("Updating factory configuration from {} to {}", oldId, newId); try { final Configuration cfg = ConfigUtil.getLegacyFactoryConfig(this.configAdmin, factoryPid, alias, pid); - if ( cfg != null ) { + if (cfg != null) { // keep existing values / location final String location = cfg.getBundleLocation(); final Dictionary<String, Object> dict = ConfigUtil.cleanConfiguration(cfg.getProperties()); @@ -177,26 +180,27 @@ public class ConfigUpdateHandler implements ResourceUpdater { final Configuration upCfg = this.configAdmin.getFactoryConfiguration(factoryPid, pid, location); upCfg.update(dict); } - } catch ( final IOException | InvalidSyntaxException io) { + } catch (final IOException | InvalidSyntaxException io) { // ignore for now } group.update(); } private void cleanupDuplicateFactoryConfig(final UpdatableResourceGroup group) { - final String newPid = group.getId(); - final int indexOfSeparator = newPid.lastIndexOf('~'); - final String pid = newPid.substring(indexOfSeparator+1); - final String factoryPid = newPid.substring(0,indexOfSeparator); - try { - final Configuration cfg = ConfigUtil.getLegacyFactoryConfig(this.configAdmin, factoryPid, null, pid); - if ( cfg != null ) { - this.logger.debug("Duplicate configuration being cleaned up is : {}",cfg.getFactoryPid() + '.' + cfg.getPid()); - // delete old factory configuration - cfg.delete(); - } + final String newPid = group.getId(); + final int indexOfSeparator = newPid.lastIndexOf('~'); + final String pid = newPid.substring(indexOfSeparator + 1); + final String factoryPid = newPid.substring(0, indexOfSeparator); + try { + final Configuration cfg = ConfigUtil.getLegacyFactoryConfig(this.configAdmin, factoryPid, null, pid); + if (cfg != null) { + this.logger.debug( + "Duplicate configuration being cleaned up is : {}", cfg.getFactoryPid() + '.' + cfg.getPid()); + // delete old factory configuration + cfg.delete(); + } - } catch ( final IOException | InvalidSyntaxException io) { + } catch (final IOException | InvalidSyntaxException io) { // ignore for now } } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtil.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtil.java index 9de426a..e835c6d 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtil.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtil.java @@ -57,6 +57,7 @@ abstract class ConfigUtil { /** Configuration properties to ignore when comparing configs */ private static final Set<String> IGNORED_PROPERTIES = new HashSet<>(); + static { IGNORED_PROPERTIES.add(Constants.SERVICE_PID); IGNORED_PROPERTIES.add(CONFIG_PATH_KEY); @@ -64,12 +65,12 @@ abstract class ConfigUtil { IGNORED_PROPERTIES.add(ConfigurationAdmin.SERVICE_FACTORYPID); } - private static Set<String> collectKeys(final Dictionary<String, Object>a) { + private static Set<String> collectKeys(final Dictionary<String, Object> a) { final Set<String> keys = new HashSet<>(); final Enumeration<String> aI = a.keys(); - while (aI.hasMoreElements() ) { + while (aI.hasMoreElements()) { final String key = aI.nextElement(); - if ( !IGNORED_PROPERTIES.contains(key) ) { + if (!IGNORED_PROPERTIES.contains(key)) { keys.add(key); } } @@ -83,25 +84,25 @@ abstract class ConfigUtil { */ private static Object[] convertToObjectArray(final Object value) { final Object[] values = new Object[Array.getLength(value)]; - for(int i=0;i<values.length;i++) { + for (int i = 0; i < values.length; i++) { values[i] = Array.get(value, i); } return values; } /** True if a and b represent the same config data, ignoring "non-configuration" keys in the dictionaries */ - public static boolean isSameData(Dictionary<String, Object>a, Dictionary<String, Object>b) { + public static boolean isSameData(Dictionary<String, Object> a, Dictionary<String, Object> b) { boolean result = false; if (a != null && b != null) { final Set<String> keysA = collectKeys(a); final Set<String> keysB = collectKeys(b); - if ( keysA.size() == keysB.size() && keysA.containsAll(keysB) ) { + if (keysA.size() == keysB.size() && keysA.containsAll(keysB)) { result = true; - for(final String key : keysA ) { + for (final String key : keysA) { final Object valA = a.get(key); final Object valB = b.get(key); - if ( !isSameValue(valA, valB) ) { + if (!isSameValue(valA, valB)) { result = false; break; } @@ -118,21 +119,21 @@ abstract class ConfigUtil { if (valA == null || valB == null) { return false; } - if ( valA.getClass().isArray() && valB.getClass().isArray()) { + if (valA.getClass().isArray() && valB.getClass().isArray()) { final Object[] arrA = convertToObjectArray(valA); final Object[] arrB = convertToObjectArray(valB); - if ( arrA.length != arrB.length ) { + if (arrA.length != arrB.length) { return false; } - for(int i=0; i<arrA.length; i++) { - if ( !(String.valueOf(arrA[i]).equals(String.valueOf(arrB[i]))) ) { + for (int i = 0; i < arrA.length; i++) { + if (!(String.valueOf(arrA[i]).equals(String.valueOf(arrB[i])))) { return false; } } } else if (!valA.getClass().isArray() && !valB.getClass().isArray()) { // if no arrays do a string comparison - if ( !(String.valueOf(valA).equals(String.valueOf(valB))) ) { + if (!(String.valueOf(valA).equals(String.valueOf(valB)))) { return false; } } else { @@ -148,9 +149,9 @@ abstract class ConfigUtil { public static Dictionary<String, Object> cleanConfiguration(final Dictionary<String, Object> config) { final Dictionary<String, Object> cleanedConfig = new Hashtable<>(); final Enumeration<String> e = config.keys(); - while(e.hasMoreElements()) { + while (e.hasMoreElements()) { final String key = e.nextElement(); - if ( !IGNORED_PROPERTIES.contains(key) ) { + if (!IGNORED_PROPERTIES.contains(key)) { cleanedConfig.put(key, config.get(key)); } } @@ -168,10 +169,9 @@ abstract class ConfigUtil { .replace(")", "\\)"); } - public static Configuration getConfiguration(final ConfigurationAdmin ca, - final String factoryPid, - final String configPidOrName) - throws IOException, InvalidSyntaxException { + public static Configuration getConfiguration( + final ConfigurationAdmin ca, final String factoryPid, final String configPidOrName) + throws IOException, InvalidSyntaxException { Configuration config = getOrCreateConfiguration(ca, factoryPid, configPidOrName, null, false); if (config == null && factoryPid != null) { config = getLegacyFactoryConfig(ca, factoryPid, null, configPidOrName); @@ -179,11 +179,9 @@ abstract class ConfigUtil { return config; } - public static Configuration createConfiguration(final ConfigurationAdmin ca, - final String factoryPid, - final String configPidOrName, - final String location) - throws IOException, InvalidSyntaxException { + public static Configuration createConfiguration( + final ConfigurationAdmin ca, final String factoryPid, final String configPidOrName, final String location) + throws IOException, InvalidSyntaxException { return getOrCreateConfiguration(ca, factoryPid, configPidOrName, location, true); } @@ -198,20 +196,20 @@ abstract class ConfigUtil { * @throws IOException - if access to persistent storage fails * @throws InvalidSyntaxException */ - private static Configuration getOrCreateConfiguration(final ConfigurationAdmin ca, + private static Configuration getOrCreateConfiguration( + final ConfigurationAdmin ca, final String factoryPid, final String configPidOrName, final String location, final boolean createIfNeeded) - throws IOException, InvalidSyntaxException { + throws IOException, InvalidSyntaxException { Configuration result = null; if (factoryPid == null) { if (createIfNeeded) { result = ca.getConfiguration(configPidOrName, location); } else { - final String filter = "(" + Constants.SERVICE_PID + "=" + encode(configPidOrName) - + ")"; + final String filter = "(" + Constants.SERVICE_PID + "=" + encode(configPidOrName) + ")"; final Configuration[] configs = ca.listConfigurations(filter); if (configs != null && configs.length > 0) { result = configs[0]; @@ -222,10 +220,11 @@ abstract class ConfigUtil { result = ca.getFactoryConfiguration(factoryPid, configPidOrName, location); } else { final String filter = "(&(" - + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + encode(factoryPid) - + ")(" - + Constants.SERVICE_PID + "=" + encode(ConfigUtil.getPIDOfFactoryPID(factoryPid, configPidOrName)) - + "))"; + + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + encode(factoryPid) + + ")(" + + Constants.SERVICE_PID + "=" + + encode(ConfigUtil.getPIDOfFactoryPID(factoryPid, configPidOrName)) + + "))"; final Configuration[] configs = ca.listConfigurations(filter); if (configs != null && configs.length > 0) { result = configs[0]; @@ -236,17 +235,15 @@ abstract class ConfigUtil { return result; } - public static Configuration getLegacyFactoryConfig(final ConfigurationAdmin ca, - final String factoryPid, - final String aliasPid, - final String pid) - throws IOException, InvalidSyntaxException { + public static Configuration getLegacyFactoryConfig( + final ConfigurationAdmin ca, final String factoryPid, final String aliasPid, final String pid) + throws IOException, InvalidSyntaxException { final String configPid = (aliasPid != null ? aliasPid.substring(factoryPid.length() + 1) : pid); Configuration result = null; Configuration configs[] = null; - if ( configPid != null ) { + if (configPid != null) { configs = ca.listConfigurations("(&(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + encode(factoryPid) + ")(" + Constants.SERVICE_PID + "=" + encode(configPid) @@ -260,8 +257,7 @@ abstract class ConfigUtil { } if (configs == null || configs.length == 0) { // check for old style with alias pid - configs = ca.listConfigurations( - "(&(" + ConfigurationAdmin.SERVICE_FACTORYPID + configs = ca.listConfigurations("(&(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + factoryPid + ")(" + ALIAS_KEY + "=" + encode(configPid) + "))"); @@ -276,7 +272,7 @@ abstract class ConfigUtil { public static boolean toBoolean(final Object obj, final boolean defaultValue) { boolean result = defaultValue; - if ( obj != null ) { + if (obj != null) { if (obj instanceof Boolean) { result = ((Boolean) obj).booleanValue(); } else { @@ -304,7 +300,7 @@ abstract class ConfigUtil { public static Dictionary<String, Object> mergeReverseOrder(final List<Dictionary<String, Object>> propertiesList) { Collections.reverse(propertiesList); final Dictionary<String, Object> properties = new Hashtable<>(); - for(final Dictionary<String, Object> dict : propertiesList) { + for (final Dictionary<String, Object> dict : propertiesList) { merge(properties, dict); } return properties; @@ -317,7 +313,7 @@ abstract class ConfigUtil { */ private static void merge(final Dictionary<String, Object> base, final Dictionary<String, Object> props) { final Enumeration<String> keyIter = props.keys(); - while (keyIter.hasMoreElements() ) { + while (keyIter.hasMoreElements()) { final String key = keyIter.nextElement(); base.put(key, props.get(key)); } @@ -328,14 +324,15 @@ abstract class ConfigUtil { * @param properties the properties to check and modify * @param base the base to compare with */ - public static void removeRedundantProperties(final Dictionary<String, Object> properties, final Dictionary<String, Object> base ) { + public static void removeRedundantProperties( + final Dictionary<String, Object> properties, final Dictionary<String, Object> base) { final Enumeration<String> keyEnum = base.keys(); - while ( keyEnum.hasMoreElements() ) { + while (keyEnum.hasMoreElements()) { final String key = keyEnum.nextElement(); final Object value = base.get(key); final Object newValue = properties.get(key); - if ( newValue != null && isSameValue(newValue, value)) { + if (newValue != null && isSameValue(newValue, value)) { properties.remove(key); } } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigurationSerializerWebConsolePlugin.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigurationSerializerWebConsolePlugin.java index b7a1ca9..46ce0b8 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigurationSerializerWebConsolePlugin.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ConfigurationSerializerWebConsolePlugin.java @@ -18,6 +18,10 @@ */ package org.apache.sling.installer.factories.configuration.impl; +import javax.servlet.GenericServlet; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; @@ -31,10 +35,6 @@ import java.util.Enumeration; import java.util.Hashtable; import java.util.stream.Collectors; -import javax.servlet.GenericServlet; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - import org.apache.sling.installer.api.info.InfoProvider; import org.apache.sling.installer.api.serializer.ConfigurationSerializerFactory; import org.apache.sling.installer.api.serializer.ConfigurationSerializerFactory.Format; @@ -51,14 +51,15 @@ import org.osgi.service.metatype.MetaTypeService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@Component(service=javax.servlet.Servlet.class, - property = { - Constants.SERVICE_VENDOR + "=The Apache Software Foundation", - Constants.SERVICE_DESCRIPTION + "=Apache Sling OSGi Installer Configuration Serializer Web Console Plugin", - "felix.webconsole.label=" + ConfigurationSerializerWebConsolePlugin.LABEL, - "felix.webconsole.title=OSGi Installer Configuration Printer", - "felix.webconsole.category=OSGi" - }) +@Component( + service = javax.servlet.Servlet.class, + property = { + Constants.SERVICE_VENDOR + "=The Apache Software Foundation", + Constants.SERVICE_DESCRIPTION + "=Apache Sling OSGi Installer Configuration Serializer Web Console Plugin", + "felix.webconsole.label=" + ConfigurationSerializerWebConsolePlugin.LABEL, + "felix.webconsole.title=OSGi Installer Configuration Printer", + "felix.webconsole.category=OSGi" + }) @SuppressWarnings("serial") public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { @@ -71,7 +72,7 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { private static final String PARAMETER_REMOVE_MERGED_DEFAULT_PROPERTIES = "removeMergedDefaultProps"; /** The logger */ - private final Logger LOGGER = LoggerFactory.getLogger(ConfigurationSerializerWebConsolePlugin.class); + private final Logger LOGGER = LoggerFactory.getLogger(ConfigurationSerializerWebConsolePlugin.class); @Reference ConfigurationAdmin configurationAdmin; @@ -93,9 +94,8 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { } @Override - public void service(final ServletRequest request, final ServletResponse response) - throws IOException { - + public void service(final ServletRequest request, final ServletResponse response) throws IOException { + final String pid = request.getParameter(PARAMETER_PID); final String format = request.getParameter(PARAMETER_FORMAT); // initial loading @@ -108,9 +108,12 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { removeComponentDefaultProperties = true; removeMergedDefaultProperties = true; } else { - removeMetatypeDefaultProperties = Boolean.parseBoolean(request.getParameter(PARAMETER_REMOVE_METATYPE_DEFAULT_PROPERTIES)); - removeComponentDefaultProperties = Boolean.parseBoolean(request.getParameter(PARAMETER_REMOVE_COMPONENT_DEFAULT_PROPERTIES)); - removeMergedDefaultProperties = Boolean.parseBoolean(request.getParameter(PARAMETER_REMOVE_MERGED_DEFAULT_PROPERTIES)); + removeMetatypeDefaultProperties = + Boolean.parseBoolean(request.getParameter(PARAMETER_REMOVE_METATYPE_DEFAULT_PROPERTIES)); + removeComponentDefaultProperties = + Boolean.parseBoolean(request.getParameter(PARAMETER_REMOVE_COMPONENT_DEFAULT_PROPERTIES)); + removeMergedDefaultProperties = + Boolean.parseBoolean(request.getParameter(PARAMETER_REMOVE_MERGED_DEFAULT_PROPERTIES)); } Collection<ComponentDescriptionDTO> allComponentDescriptions; if (removeComponentDefaultProperties) { @@ -118,7 +121,7 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { } else { allComponentDescriptions = Collections.emptyList(); } - + MetatypeHandler metatypeHandler = new MetatypeHandler(metatypeService, bundleContext); ConfigurationSerializerFactory.Format serializationFormat = Format.JSON; if (format != null && !format.trim().isEmpty()) { @@ -146,10 +149,10 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { pw.print("<input type='text' name='"); pw.print(PARAMETER_PID); pw.print("' value='"); - if ( pid != null ) { + if (pid != null) { pw.print(escapeXml(pid)); } - + pw.println("' class='input' size='120' minlength='3'>"); closeTd(pw); closeTr(pw); @@ -161,10 +164,10 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { pw.print("<input type='checkbox' name='"); pw.print(PARAMETER_REMOVE_METATYPE_DEFAULT_PROPERTIES); pw.print("'"); - if ( removeMetatypeDefaultProperties ) { + if (removeMetatypeDefaultProperties) { pw.print(" checked"); } - + pw.println(" id='"); pw.print(PARAMETER_REMOVE_METATYPE_DEFAULT_PROPERTIES); pw.println("' class='input' value='true'>"); @@ -175,7 +178,7 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { pw.print("<input type='checkbox' name='"); pw.print(PARAMETER_REMOVE_COMPONENT_DEFAULT_PROPERTIES); pw.print("'"); - if ( removeComponentDefaultProperties ) { + if (removeComponentDefaultProperties) { pw.print(" checked"); } @@ -190,10 +193,10 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { pw.print("<input type='checkbox' name='"); pw.print(PARAMETER_REMOVE_MERGED_DEFAULT_PROPERTIES); pw.print("'"); - if ( removeMergedDefaultProperties ) { + if (removeMergedDefaultProperties) { pw.print(" checked"); } - + pw.println(" id='"); pw.print(PARAMETER_REMOVE_MERGED_DEFAULT_PROPERTIES); pw.println("' class='input' value='true'>"); @@ -201,7 +204,8 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { pw.println(PARAMETER_REMOVE_MERGED_DEFAULT_PROPERTIES); pw.println("'>Merged Properties</label>"); } - pw.println("<p>Selecting any of these options strips those properties which have the same name and value as one from any of the selected sources. The removed properties are very likely being redundant and therefore do not need to be added to serialized configs.</a>"); + pw.println( + "<p>Selecting any of these options strips those properties which have the same name and value as one from any of the selected sources. The removed properties are very likely being redundant and therefore do not need to be added to serialized configs.</a>"); closeTd(pw); closeTr(pw); @@ -240,10 +244,16 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { properties = ConfigUtil.cleanConfiguration(properties); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { if (removeMetatypeDefaultProperties) { - metatypeHandler.updateConfiguration(configuration.getFactoryPid(), configuration.getPid(), properties, mergedProperties); + metatypeHandler.updateConfiguration( + configuration.getFactoryPid(), configuration.getPid(), properties, mergedProperties); } if (removeComponentDefaultProperties) { - removeComponentDefaultProperties(allComponentDescriptions, configuration.getPid(), configuration.getFactoryPid(), properties, mergedProperties); + removeComponentDefaultProperties( + allComponentDescriptions, + configuration.getPid(), + configuration.getFactoryPid(), + properties, + mergedProperties); } if (removeMergedDefaultProperties) { ConfigUtil.removeRedundantProperties(properties, mergedProperties); @@ -330,17 +340,17 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { } final StringBuilder b = new StringBuilder(input.length()); - for(int i = 0;i < input.length(); i++) { + for (int i = 0; i < input.length(); i++) { final char c = input.charAt(i); - if(c == '&') { + if (c == '&') { b.append("&"); - } else if(c == '<') { + } else if (c == '<') { b.append("<"); - } else if(c == '>') { + } else if (c == '>') { b.append(">"); - } else if(c == '"') { + } else if (c == '"') { b.append("""); - } else if(c == '\'') { + } else if (c == '\'') { b.append("'"); } else { b.append(c); @@ -358,19 +368,25 @@ public class ConfigurationSerializerWebConsolePlugin extends GenericServlet { * @param dict * @param mergedProperties */ - private void removeComponentDefaultProperties(final Collection<ComponentDescriptionDTO> componentDescriptions, final String pid, final String factoryPid, final Dictionary<String, Object> dict, final Dictionary<String, Object> mergedProperties) { + private void removeComponentDefaultProperties( + final Collection<ComponentDescriptionDTO> componentDescriptions, + final String pid, + final String factoryPid, + final Dictionary<String, Object> dict, + final Dictionary<String, Object> mergedProperties) { String effectivePid = factoryPid != null ? factoryPid : pid; Collection<ComponentDescriptionDTO> relevantComponentDescriptions = componentDescriptions.stream() - // find all with a matching pid - .filter(c -> Arrays.asList(c.configurationPid).contains(effectivePid)).collect(Collectors.toList()); + // find all with a matching pid + .filter(c -> Arrays.asList(c.configurationPid).contains(effectivePid)) + .collect(Collectors.toList()); final Enumeration<String> e = dict.keys(); - while(e.hasMoreElements()) { + while (e.hasMoreElements()) { final String key = e.nextElement(); final Object newValue = dict.get(key); if (relevantComponentDescriptions.stream() - .allMatch(c -> ConfigUtil.isSameValue(newValue, c.properties.get(key)) - && mergedProperties.get(key) == null)) { + .allMatch(c -> ConfigUtil.isSameValue(newValue, c.properties.get(key)) + && mergedProperties.get(key) == null)) { dict.remove(key); } } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/Coordinator.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/Coordinator.java index c2c4b17..0249ee6 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/Coordinator.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/Coordinator.java @@ -25,7 +25,6 @@ import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * Coordinator service. * @@ -61,8 +60,8 @@ public class Coordinator { @Override public String toString() { - return "Operation [pid=" + pid + ", factoryPid=" + factoryPid - + ", isDelete=" + isDelete + ", created=" + created + "]"; + return "Operation [pid=" + pid + ", factoryPid=" + factoryPid + ", isDelete=" + isDelete + ", created=" + + created + "]"; } } @@ -94,12 +93,12 @@ public class Coordinator { logger.debug("Searching {} : {} - {}", new Object[] {pid, factoryPid, isDelete}); Operation result = null; final Iterator<Operation> i = this.operations.iterator(); - while ( i.hasNext() ) { + while (i.hasNext()) { final Operation op = i.next(); - if ( op.isDelete == isDelete ) { - if ( op.pid.equals(pid) ) { - if ( (op.factoryPid == null && factoryPid == null) - || (op.factoryPid != null && op.factoryPid.equals(factoryPid)) ) { + if (op.isDelete == isDelete) { + if (op.pid.equals(pid)) { + if ((op.factoryPid == null && factoryPid == null) + || (op.factoryPid != null && op.factoryPid.equals(factoryPid))) { result = op; i.remove(); break; @@ -118,9 +117,9 @@ public class Coordinator { private void cleanup() { final long time = System.currentTimeMillis() - EXPIRY; final Iterator<Operation> i = this.operations.iterator(); - while ( i.hasNext() ) { + while (i.hasNext()) { final Operation op = i.next(); - if ( op.created <= time ) { + if (op.created <= time) { logger.debug("Deleting expired {}", op); i.remove(); } else { diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandler.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandler.java index 7fd3feb..0e3038e 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandler.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandler.java @@ -39,51 +39,53 @@ public class MetatypeHandler { this.srv = mts; this.bundleContext = bundleContext; } - - public void updateConfiguration(final String factoryPid, + + public void updateConfiguration( + final String factoryPid, final String pid, - final Dictionary<String, Object> props, + final Dictionary<String, Object> props, final Dictionary<String, Object> defaultProps) { // search metatype final ObjectClassDefinition ocd; - if ( factoryPid != null ) { - ocd = this.getObjectClassDefinition( factoryPid ); + if (factoryPid != null) { + ocd = this.getObjectClassDefinition(factoryPid); } else { - ocd = this.getObjectClassDefinition( pid ); + ocd = this.getObjectClassDefinition(pid); } - if ( ocd != null ) { - for(final AttributeDefinition ad : ocd.getAttributeDefinitions(ObjectClassDefinition.ALL)) { + if (ocd != null) { + for (final AttributeDefinition ad : ocd.getAttributeDefinitions(ObjectClassDefinition.ALL)) { final String propName = ad.getID(); final Object newValue = props.get(propName); - if ( newValue != null - && (defaultProps == null || defaultProps.get(propName) == null) ) { - if ( ad.getCardinality() == 0 ) { - if ( !shouldSet(ad, newValue.toString())) { - props.remove(propName); + if (newValue != null && (defaultProps == null || defaultProps.get(propName) == null)) { + if (ad.getCardinality() == 0) { + if (!shouldSet(ad, newValue.toString())) { + props.remove(propName); } } else { - final String[] array = Converters.standardConverter().convert(newValue).to(String[].class); - if ( !shouldSet(ad, array)) { + final String[] array = + Converters.standardConverter().convert(newValue).to(String[].class); + if (!shouldSet(ad, array)) { props.remove(propName); - } - } + } + } } } } } - private ObjectClassDefinition getObjectClassDefinition( final String pid ) { - for(final Bundle b : this.bundleContext.getBundles()) { + private ObjectClassDefinition getObjectClassDefinition(final String pid) { + for (final Bundle b : this.bundleContext.getBundles()) { try { - final MetaTypeInformation mti = this.srv.getMetaTypeInformation( b ); - if ( mti != null ) { - final ObjectClassDefinition ocd = mti.getObjectClassDefinition( pid, null );; - if ( ocd != null ) { + final MetaTypeInformation mti = this.srv.getMetaTypeInformation(b); + if (mti != null) { + final ObjectClassDefinition ocd = mti.getObjectClassDefinition(pid, null); + ; + if (ocd != null) { return ocd; } } - } catch ( final IllegalArgumentException iae ) { + } catch (final IllegalArgumentException iae) { // ignore } } @@ -91,25 +93,24 @@ public class MetatypeHandler { } boolean shouldSet(final AttributeDefinition ad, final String value) { - if ( value.isEmpty() && ad.getDefaultValue() == null ) { + if (value.isEmpty() && ad.getDefaultValue() == null) { return false; } - if ( ad.getDefaultValue() != null && value.equals(ad.getDefaultValue()[0]) ) { + if (ad.getDefaultValue() != null && value.equals(ad.getDefaultValue()[0])) { return false; } return true; } boolean shouldSet(final AttributeDefinition ad, final String[] values) { - if ( ad.getDefaultValue() == null ) { - if ( values.length == 0 || (values.length == 1 && values[0].isEmpty() ) ) { + if (ad.getDefaultValue() == null) { + if (values.length == 0 || (values.length == 1 && values[0].isEmpty())) { return false; } } - if ( ad.getDefaultValue() != null && Arrays.equals(ad.getDefaultValue(), values) ) { + if (ad.getDefaultValue() != null && Arrays.equals(ad.getDefaultValue(), values)) { return false; } return true; } - } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ServicesListener.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ServicesListener.java index 139eb2f..fbb5525 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/ServicesListener.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/ServicesListener.java @@ -77,31 +77,37 @@ public class ServicesListener { public synchronized void notifyChange() { // check if all services are available - final ResourceChangeListener listener = (ResourceChangeListener)this.changeHandlerListener.getService(); - final ConfigurationAdmin configAdmin = (ConfigurationAdmin)this.configAdminListener.getService(); - final InfoProvider infoProvider = (InfoProvider)this.infoServiceListener.getService(); + final ResourceChangeListener listener = (ResourceChangeListener) this.changeHandlerListener.getService(); + final ConfigurationAdmin configAdmin = (ConfigurationAdmin) this.configAdminListener.getService(); + final InfoProvider infoProvider = (InfoProvider) this.infoServiceListener.getService(); - if ( configAdmin != null && listener != null && infoProvider != null ) { - if ( configTaskCreator == null ) { + if (configAdmin != null && listener != null && infoProvider != null) { + if (configTaskCreator == null) { active.set(true); // start and register osgi installer service this.configTaskCreator = new ConfigTaskCreator(listener, configAdmin, infoProvider); final ConfigUpdateHandler handler = new ConfigUpdateHandler(configAdmin, this); configTaskCreatorRegistration = handler.register(this.bundleContext); - if ( Activator.MERGE_SCHEMES != null ) { - this.webconsoleRegistration = this.bundleContext.registerService("org.apache.felix.webconsole.spi.ConfigurationHandler", new ServiceFactory<Object>(){ - - @Override - public Object getService(final Bundle bundle, final ServiceRegistration<Object> registration) { - return new WebconsoleConfigurationHandler(bundleContext, infoProvider); - } - - @Override - public void ungetService(final Bundle bundle, final ServiceRegistration<Object> registration, final Object service) { - ((WebconsoleConfigurationHandler)service).deactivate(); - } - - }, null); + if (Activator.MERGE_SCHEMES != null) { + this.webconsoleRegistration = this.bundleContext.registerService( + "org.apache.felix.webconsole.spi.ConfigurationHandler", + new ServiceFactory<Object>() { + + @Override + public Object getService( + final Bundle bundle, final ServiceRegistration<Object> registration) { + return new WebconsoleConfigurationHandler(bundleContext, infoProvider); + } + + @Override + public void ungetService( + final Bundle bundle, + final ServiceRegistration<Object> registration, + final Object service) { + ((WebconsoleConfigurationHandler) service).deactivate(); + } + }, + null); } } } else { @@ -112,11 +118,11 @@ public class ServicesListener { private synchronized void stop() { active.set(false); // unregister - if ( this.webconsoleRegistration != null ) { + if (this.webconsoleRegistration != null) { this.webconsoleRegistration.unregister(); this.webconsoleRegistration = null; } - if ( this.configTaskCreatorRegistration != null ) { + if (this.configTaskCreatorRegistration != null) { this.configTaskCreatorRegistration.unregister(); this.configTaskCreatorRegistration = null; } @@ -128,7 +134,7 @@ public class ServicesListener { } public synchronized void finishedUpdating() { - if ( this.isActive() ) { + if (this.isActive()) { this.configTaskCreatorRegistration.unregister(); this.configTaskCreatorRegistration = this.configTaskCreator.register(this.bundleContext); } @@ -158,8 +164,7 @@ public class ServicesListener { public void start() { this.retainService(); try { - bundleContext.addServiceListener(this, "(" - + Constants.OBJECTCLASS + "=" + serviceName + ")"); + bundleContext.addServiceListener(this, "(" + Constants.OBJECTCLASS + "=" + serviceName + ")"); } catch (final InvalidSyntaxException ise) { // this should really never happen throw new RuntimeException("Unexpected exception occured.", ise); @@ -173,12 +178,13 @@ public class ServicesListener { public synchronized Object getService() { return this.service; } + private synchronized void retainService() { - if ( this.reference == null ) { + if (this.reference == null) { this.reference = bundleContext.getServiceReference(this.serviceName); - if ( this.reference != null ) { + if (this.reference != null) { this.service = bundleContext.getService(this.reference); - if ( this.service == null ) { + if (this.service == null) { this.reference = null; } else { notifyChange(); @@ -188,7 +194,7 @@ public class ServicesListener { } private synchronized void releaseService() { - if ( this.reference != null ) { + if (this.reference != null) { this.service = null; bundleContext.ungetService(this.reference); this.reference = null; @@ -201,9 +207,9 @@ public class ServicesListener { */ @Override public void serviceChanged(ServiceEvent event) { - if (event.getType() == ServiceEvent.REGISTERED ) { + if (event.getType() == ServiceEvent.REGISTERED) { this.retainService(); - } else if ( event.getType() == ServiceEvent.UNREGISTERING ) { + } else if (event.getType() == ServiceEvent.UNREGISTERING) { this.releaseService(); } } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/impl/WebconsoleConfigurationHandler.java b/src/main/java/org/apache/sling/installer/factories/configuration/impl/WebconsoleConfigurationHandler.java index 7563347..ed06668 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/impl/WebconsoleConfigurationHandler.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/impl/WebconsoleConfigurationHandler.java @@ -49,28 +49,28 @@ public class WebconsoleConfigurationHandler implements ConfigurationHandler { @Override public void createConfiguration(final String pid) throws ValidationException, IOException { - // nothing to do + // nothing to do } @Override - public void createFactoryConfiguration(final String factoryPid, String name) throws ValidationException, IOException { - // nothing to do + public void createFactoryConfiguration(final String factoryPid, String name) + throws ValidationException, IOException { + // nothing to do } @Override public void deleteConfiguration(final String factoryPid, final String pid) throws ValidationException, IOException { - // nothing to do + // nothing to do } @Override public void updateConfiguration(final String factoryPid, final String pid, final Dictionary<String, Object> props) throws ValidationException, IOException { final MetaTypeService mts = this.metatypeTracker.getService(); - if ( mts != null ) { + if (mts != null) { final Dictionary<String, Object> defaultProps = ConfigTaskCreator.getDefaultProperties(infoProvider, pid); final MetatypeHandler mt = new MetatypeHandler(mts, this.bundleContext); mt.updateConfiguration(factoryPid, pid, props, defaultProps); } } - } diff --git a/src/main/java/org/apache/sling/installer/factories/configuration/package-info.java b/src/main/java/org/apache/sling/installer/factories/configuration/package-info.java index eb71c4d..f9b49f7 100644 --- a/src/main/java/org/apache/sling/installer/factories/configuration/package-info.java +++ b/src/main/java/org/apache/sling/installer/factories/configuration/package-info.java @@ -19,5 +19,3 @@ @org.osgi.annotation.versioning.Version("1.1.2") package org.apache.sling.installer.factories.configuration; - - diff --git a/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandlerTest.java b/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandlerTest.java index 204d94e..38078e7 100644 --- a/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandlerTest.java +++ b/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUpdateHandlerTest.java @@ -18,10 +18,10 @@ */ package org.apache.sling.installer.factories.configuration.impl; -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class ConfigUpdateHandlerTest { private void checkFactoryPid(final String alias, final String oldId, final String factoryId, final String pid) { @@ -31,40 +31,44 @@ public class ConfigUpdateHandlerTest { assertEquals(pid, result[1]); } - @Test public void testGettingFactoryPid() { + @Test + public void testGettingFactoryPid() { // normal conversion - checkFactoryPid("org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment.org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment.43e4778d-3e72-460a-9da9-bca80558f1f7", + checkFactoryPid( + "org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment.org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment.43e4778d-3e72-460a-9da9-bca80558f1f7", "org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment.my-platform", - "org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment", "my-platform"); + "org.apache.sling.jcr.base.internal.LoginAdminWhitelist.fragment", + "my-platform"); // case where the pid starts with the same characters as the factory pid : "c" checkFactoryPid( "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup.com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup.08f330fd-63d2-4175-ad3c-79efa3c69e2f", "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup.cloud", - "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup", "cloud"); + "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup", + "cloud"); // case where the pid starts with the same characters as the factory pid : "co" checkFactoryPid( "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup.com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup.3ba307f5-a5d0-40a4-98b6-8616b7a1d1e8", "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup.contentpackages", - "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup", "contentpackages"); + "com.apache.sling.upgrades.cleanup.impl.UpgradeContentCleanup", + "contentpackages"); // case where alias is null and factoryPid and Pid would be inferred from oldId itself checkFactoryPid( null, "org.apache.sling.commons.log.LogManager.factory.config.org.apache.sling.commons.log.LogManager.factory.config.3a514ecf-2e1d-4903-bf88-d878360e8ff1", - "org.apache.sling.commons.log.LogManager.factory.config", "3a514ecf-2e1d-4903-bf88-d878360e8ff1"); + "org.apache.sling.commons.log.LogManager.factory.config", + "3a514ecf-2e1d-4903-bf88-d878360e8ff1"); // case where alias is null and factoryPid and Pid would be inferred from oldId itself - checkFactoryPid( - null, - "org-test-form-servlet", - "org-test-form-servlet", "org-test-form-servlet"); - + checkFactoryPid(null, "org-test-form-servlet", "org-test-form-servlet", "org-test-form-servlet"); } @Test public void testDuplicateFactoryPID() { - checkFactoryPid("a.b.c.MyFactoryConfig.a.b.c.MyFactoryConfig.5a61b4ab-c8c9-4e20-ab3d-b8b7ea12dfca", - "a.b.c.MyFactoryConfig.a.b.c.MyFactoryConfig", "a.b.c.MyFactoryConfig", + checkFactoryPid( + "a.b.c.MyFactoryConfig.a.b.c.MyFactoryConfig.5a61b4ab-c8c9-4e20-ab3d-b8b7ea12dfca", + "a.b.c.MyFactoryConfig.a.b.c.MyFactoryConfig", + "a.b.c.MyFactoryConfig", "5a61b4ab-c8c9-4e20-ab3d-b8b7ea12dfca"); } } diff --git a/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtilTest.java b/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtilTest.java index 57e0402..88a5c28 100644 --- a/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtilTest.java +++ b/src/test/java/org/apache/sling/installer/factories/configuration/impl/ConfigUtilTest.java @@ -18,10 +18,6 @@ */ package org.apache.sling.installer.factories.configuration.impl; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; @@ -31,9 +27,14 @@ import org.mockito.Mockito; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + public class ConfigUtilTest { - @Test public void testIsSameDataEmptyAndNullDictionaries() throws Exception { + @Test + public void testIsSameDataEmptyAndNullDictionaries() throws Exception { final Dictionary<String, Object> a = new Hashtable<>(); final Dictionary<String, Object> b = new Hashtable<>(); @@ -44,7 +45,8 @@ public class ConfigUtilTest { assertFalse(ConfigUtil.isSameData(b, null)); } - @Test public void testIsSameDataSameDictionaries() throws Exception { + @Test + public void testIsSameDataSameDictionaries() throws Exception { final Dictionary<String, Object> a = new Hashtable<>(); final Dictionary<String, Object> b = new Hashtable<>(); @@ -55,7 +57,7 @@ public class ConfigUtilTest { a.put("e", 1.1); final Enumeration<String> e = a.keys(); - while ( e.hasMoreElements() ) { + while (e.hasMoreElements()) { final String name = e.nextElement(); b.put(name, a.get(name)); } @@ -64,7 +66,7 @@ public class ConfigUtilTest { assertTrue(ConfigUtil.isSameData(b, a)); final Enumeration<String> e1 = a.keys(); - while ( e1.hasMoreElements() ) { + while (e1.hasMoreElements()) { final String name = e1.nextElement(); b.put(name, a.get(name).toString()); } @@ -73,59 +75,61 @@ public class ConfigUtilTest { assertTrue(ConfigUtil.isSameData(b, a)); } - @Test public void testIsSameDataArrays() throws Exception { + @Test + public void testIsSameDataArrays() throws Exception { final Dictionary<String, Object> a = new Hashtable<>(); final Dictionary<String, Object> b = new Hashtable<>(); a.put("a", new String[] {"1", "2", "3"}); b.put("a", a.get("a")); - a.put("b", new Integer[] {1,2,3}); + a.put("b", new Integer[] {1, 2, 3}); b.put("b", a.get("b")); - a.put("c", new Long[] {1L,2L,3L}); + a.put("c", new Long[] {1L, 2L, 3L}); b.put("c", a.get("c")); - a.put("d", new Integer[] {1,2,3}); + a.put("d", new Integer[] {1, 2, 3}); b.put("d", new String[] {"1", "2", "3"}); assertTrue(ConfigUtil.isSameData(a, b)); assertTrue(ConfigUtil.isSameData(b, a)); } - @Test public void testIsSameDataWithPrimitiveArrays() throws Exception { + @Test + public void testIsSameDataWithPrimitiveArrays() throws Exception { final Dictionary<String, Object> a = new Hashtable<>(); final Dictionary<String, Object> b = new Hashtable<>(); - a.put("b", new int[] {1,2,3}); + a.put("b", new int[] {1, 2, 3}); b.put("b", a.get("b")); - a.put("c", new long[] {1L,2L,3L}); + a.put("c", new long[] {1L, 2L, 3L}); b.put("c", a.get("c")); - a.put("d", new int[] {1,2,3}); + a.put("d", new int[] {1, 2, 3}); b.put("d", new String[] {"1", "2", "3"}); assertTrue(ConfigUtil.isSameData(a, b)); assertTrue(ConfigUtil.isSameData(b, a)); } - @Test public void testGetOrCreateConfiguration() throws Exception { + @Test + public void testGetOrCreateConfiguration() throws Exception { Configuration c1 = Mockito.mock(Configuration.class); ConfigurationAdmin cm = Mockito.mock(ConfigurationAdmin.class); - Mockito.when(cm.listConfigurations( - "(&(service.factoryPid=a.b.c)(service.pid=a.b.c~c1))")) + Mockito.when(cm.listConfigurations("(&(service.factoryPid=a.b.c)(service.pid=a.b.c~c1))")) .thenReturn(new Configuration[] {c1}); Configuration cfg = ConfigUtil.getConfiguration(cm, "a.b.c", "c1"); assertSame(c1, cfg); } - - @Test public void testIsSameDataWithSwitchFromArrayToSingleValue() throws Exception { + @Test + public void testIsSameDataWithSwitchFromArrayToSingleValue() throws Exception { final Dictionary<String, Object> a = new Hashtable<>(); final Dictionary<String, Object> b = new Hashtable<>(); - a.put("b", new int[] {1,2,3}); + a.put("b", new int[] {1, 2, 3}); b.put("b", 1); assertFalse(ConfigUtil.isSameData(a, b)); diff --git a/src/test/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandlerTest.java b/src/test/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandlerTest.java index 51c906b..3eff9bf 100644 --- a/src/test/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandlerTest.java +++ b/src/test/java/org/apache/sling/installer/factories/configuration/impl/MetatypeHandlerTest.java @@ -18,8 +18,6 @@ */ package org.apache.sling.installer.factories.configuration.impl; -import static org.junit.Assert.assertEquals; - import java.util.Arrays; import java.util.Dictionary; import java.util.Hashtable; @@ -33,82 +31,86 @@ import org.osgi.service.metatype.MetaTypeInformation; import org.osgi.service.metatype.MetaTypeService; import org.osgi.service.metatype.ObjectClassDefinition; +import static org.junit.Assert.assertEquals; + public class MetatypeHandlerTest { - @Test public void testUpdateConfiguration() throws Exception { - final BundleContext bundleContext = Mockito.mock(BundleContext.class); - final MetaTypeService mts = Mockito.mock(MetaTypeService.class); - final Bundle bundle = Mockito.mock(Bundle.class); - Mockito.when(bundleContext.getBundles()).thenReturn(new Bundle[] {bundle}); - - final MetaTypeInformation info = Mockito.mock(MetaTypeInformation.class); - Mockito.when(mts.getMetaTypeInformation(bundle)).thenReturn(info); - final MetatypeHandler handler = new MetatypeHandler(mts, bundleContext); - - final ObjectClassDefinition ocd = Mockito.mock(ObjectClassDefinition.class); - Mockito.when(info.getObjectClassDefinition("my.pid", null)).thenReturn(ocd); - - final AttributeDefinition ada = Mockito.mock(AttributeDefinition.class); - Mockito.when(ada.getID()).thenReturn("a"); - Mockito.when(ada.getDefaultValue()).thenReturn(new String[] {"1"}); - Mockito.when(ada.getCardinality()).thenReturn(1); - Mockito.when(ada.getType()).thenReturn(AttributeDefinition.STRING); - - final AttributeDefinition adb = Mockito.mock(AttributeDefinition.class); - Mockito.when(adb.getID()).thenReturn("b"); - Mockito.when(adb.getDefaultValue()).thenReturn(new String[] {"2"}); - Mockito.when(adb.getCardinality()).thenReturn(1); - Mockito.when(adb.getType()).thenReturn(AttributeDefinition.STRING); - - final AttributeDefinition adc = Mockito.mock(AttributeDefinition.class); - Mockito.when(adc.getID()).thenReturn("c"); - Mockito.when(adc.getDefaultValue()).thenReturn(new String[] {"3"}); - Mockito.when(adc.getCardinality()).thenReturn(1); - Mockito.when(adc.getType()).thenReturn(AttributeDefinition.STRING); - - final AttributeDefinition add = Mockito.mock(AttributeDefinition.class); - Mockito.when(add.getID()).thenReturn("d"); - Mockito.when(add.getDefaultValue()).thenReturn(new String[] {"4"}); - Mockito.when(add.getCardinality()).thenReturn(1); - Mockito.when(add.getType()).thenReturn(AttributeDefinition.INTEGER); - - final AttributeDefinition adE = Mockito.mock(AttributeDefinition.class); - Mockito.when(adE.getID()).thenReturn("e"); - Mockito.when(adE.getDefaultValue()).thenReturn(new String[] {"5"}); - Mockito.when(adE.getCardinality()).thenReturn(1); - Mockito.when(adE.getType()).thenReturn(AttributeDefinition.INTEGER); - - final AttributeDefinition adF = Mockito.mock(AttributeDefinition.class); - Mockito.when(adF.getID()).thenReturn("f"); - Mockito.when(adF.getDefaultValue()).thenReturn(new String[] {"/a", "/b"}); - Mockito.when(adF.getCardinality()).thenReturn(-100); - Mockito.when(adF.getType()).thenReturn(AttributeDefinition.STRING); - - final AttributeDefinition adG = Mockito.mock(AttributeDefinition.class); - Mockito.when(adG.getID()).thenReturn("g"); - Mockito.when(adG.getDefaultValue()).thenReturn(new String[] {"/x", "/y"}); - Mockito.when(adG.getCardinality()).thenReturn(-100); - Mockito.when(adG.getType()).thenReturn(AttributeDefinition.STRING); - - Mockito.when(ocd.getAttributeDefinitions(ObjectClassDefinition.ALL)).thenReturn(new AttributeDefinition[] {ada,adb,adc,add,adE,adF,adG}); - - final Dictionary<String, Object> props = new Hashtable<>(); - props.put("a", "2"); - props.put("c", "3"); - props.put("d", 4); - props.put("e", 5); - props.put("f", Arrays.asList("/a", "/b")); - props.put("g", Arrays.asList("/a", "/b")); - - final Dictionary<String, Object> defaultProps = new Hashtable<>(); - defaultProps.put("b", "5"); - defaultProps.put("d", 7); - - handler.updateConfiguration(null, "my.pid", props, defaultProps); - - assertEquals(3, props.size()); - assertEquals("2", props.get("a")); - assertEquals(4, props.get("d")); - assertEquals(Arrays.asList("/a", "/b"), props.get("g")); + @Test + public void testUpdateConfiguration() throws Exception { + final BundleContext bundleContext = Mockito.mock(BundleContext.class); + final MetaTypeService mts = Mockito.mock(MetaTypeService.class); + final Bundle bundle = Mockito.mock(Bundle.class); + Mockito.when(bundleContext.getBundles()).thenReturn(new Bundle[] {bundle}); + + final MetaTypeInformation info = Mockito.mock(MetaTypeInformation.class); + Mockito.when(mts.getMetaTypeInformation(bundle)).thenReturn(info); + final MetatypeHandler handler = new MetatypeHandler(mts, bundleContext); + + final ObjectClassDefinition ocd = Mockito.mock(ObjectClassDefinition.class); + Mockito.when(info.getObjectClassDefinition("my.pid", null)).thenReturn(ocd); + + final AttributeDefinition ada = Mockito.mock(AttributeDefinition.class); + Mockito.when(ada.getID()).thenReturn("a"); + Mockito.when(ada.getDefaultValue()).thenReturn(new String[] {"1"}); + Mockito.when(ada.getCardinality()).thenReturn(1); + Mockito.when(ada.getType()).thenReturn(AttributeDefinition.STRING); + + final AttributeDefinition adb = Mockito.mock(AttributeDefinition.class); + Mockito.when(adb.getID()).thenReturn("b"); + Mockito.when(adb.getDefaultValue()).thenReturn(new String[] {"2"}); + Mockito.when(adb.getCardinality()).thenReturn(1); + Mockito.when(adb.getType()).thenReturn(AttributeDefinition.STRING); + + final AttributeDefinition adc = Mockito.mock(AttributeDefinition.class); + Mockito.when(adc.getID()).thenReturn("c"); + Mockito.when(adc.getDefaultValue()).thenReturn(new String[] {"3"}); + Mockito.when(adc.getCardinality()).thenReturn(1); + Mockito.when(adc.getType()).thenReturn(AttributeDefinition.STRING); + + final AttributeDefinition add = Mockito.mock(AttributeDefinition.class); + Mockito.when(add.getID()).thenReturn("d"); + Mockito.when(add.getDefaultValue()).thenReturn(new String[] {"4"}); + Mockito.when(add.getCardinality()).thenReturn(1); + Mockito.when(add.getType()).thenReturn(AttributeDefinition.INTEGER); + + final AttributeDefinition adE = Mockito.mock(AttributeDefinition.class); + Mockito.when(adE.getID()).thenReturn("e"); + Mockito.when(adE.getDefaultValue()).thenReturn(new String[] {"5"}); + Mockito.when(adE.getCardinality()).thenReturn(1); + Mockito.when(adE.getType()).thenReturn(AttributeDefinition.INTEGER); + + final AttributeDefinition adF = Mockito.mock(AttributeDefinition.class); + Mockito.when(adF.getID()).thenReturn("f"); + Mockito.when(adF.getDefaultValue()).thenReturn(new String[] {"/a", "/b"}); + Mockito.when(adF.getCardinality()).thenReturn(-100); + Mockito.when(adF.getType()).thenReturn(AttributeDefinition.STRING); + + final AttributeDefinition adG = Mockito.mock(AttributeDefinition.class); + Mockito.when(adG.getID()).thenReturn("g"); + Mockito.when(adG.getDefaultValue()).thenReturn(new String[] {"/x", "/y"}); + Mockito.when(adG.getCardinality()).thenReturn(-100); + Mockito.when(adG.getType()).thenReturn(AttributeDefinition.STRING); + + Mockito.when(ocd.getAttributeDefinitions(ObjectClassDefinition.ALL)) + .thenReturn(new AttributeDefinition[] {ada, adb, adc, add, adE, adF, adG}); + + final Dictionary<String, Object> props = new Hashtable<>(); + props.put("a", "2"); + props.put("c", "3"); + props.put("d", 4); + props.put("e", 5); + props.put("f", Arrays.asList("/a", "/b")); + props.put("g", Arrays.asList("/a", "/b")); + + final Dictionary<String, Object> defaultProps = new Hashtable<>(); + defaultProps.put("b", "5"); + defaultProps.put("d", 7); + + handler.updateConfiguration(null, "my.pid", props, defaultProps); + + assertEquals(3, props.size()); + assertEquals("2", props.get("a")); + assertEquals(4, props.get("d")); + assertEquals(Arrays.asList("/a", "/b"), props.get("g")); } }
