diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/BundleDefaultPreferences.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/BundleDefaultPreferences.java index efb745435c3..ff4d54e9fea 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/BundleDefaultPreferences.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/BundleDefaultPreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2015 IBM Corporation and others. + * Copyright (c) 2009, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,7 +13,8 @@ *******************************************************************************/ package org.eclipse.core.internal.preferences; -import java.util.*; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.preferences.*; @@ -29,14 +30,11 @@ */ public class BundleDefaultPreferences extends EclipsePreferences { - private static Set loadedNodes = Collections.synchronizedSet(new HashSet()); - private String qualifier; - private int segmentCount; + private static final Set LOADED_NODES = ConcurrentHashMap.newKeySet(); + private final String qualifier; + private final int segmentCount; private IEclipsePreferences loadLevel; - /* - * Default constructor. - */ public BundleDefaultPreferences() { this(null, null); } @@ -46,30 +44,24 @@ private BundleDefaultPreferences(EclipsePreferences parent, String name) { // cache the segment count IPath path = IPath.fromOSString(absolutePath()); segmentCount = path.segmentCount(); - if (segmentCount < 2) - return; - - // cache the qualifier - String scope = path.segment(0); - if (BundleDefaultsScope.SCOPE.equals(scope)) - qualifier = path.segment(1); - - // cache the location - if (qualifier == null) - return; + qualifier = segmentCount > 1 && BundleDefaultsScope.SCOPE.equals(path.segment(0)) // cache the qualifier + ? path.segment(1) + : null; } @Override protected IEclipsePreferences getLoadLevel() { if (loadLevel == null) { - if (qualifier == null) + if (qualifier == null) { return null; + } // Make it relative to this node rather than navigating to it from the root. // Walk backwards up the tree starting at this node. // This is important to avoid a chicken/egg thing on startup. IEclipsePreferences node = this; - for (int i = 2; i < segmentCount; i++) + for (int i = 2; i < segmentCount; i++) { node = (IEclipsePreferences) node.parent(); + } loadLevel = node; } return loadLevel; @@ -77,12 +69,12 @@ protected IEclipsePreferences getLoadLevel() { @Override protected boolean isAlreadyLoaded(IEclipsePreferences node) { - return loadedNodes.contains(node.name()); + return LOADED_NODES.contains(node.name()); } @Override protected void loaded() { - loadedNodes.add(name()); + LOADED_NODES.add(name()); } @Override diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java index eac5ce8fa2e..3f1cc94b9b7 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2015 IBM Corporation and others. + * Copyright (c) 2004, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -19,6 +19,7 @@ import java.lang.ref.WeakReference; import java.net.URL; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import org.eclipse.core.internal.preferences.exchange.IProductPreferencesService; import org.eclipse.core.internal.runtime.RuntimeLog; import org.eclipse.core.runtime.*; @@ -36,7 +37,7 @@ */ public class DefaultPreferences extends EclipsePreferences { // cache which nodes have been loaded from disk - private static Set loadedNodes = Collections.synchronizedSet(new HashSet()); + private static final Set LOADED_NODES = ConcurrentHashMap.newKeySet(); private static final String KEY_PREFIX = "%"; //$NON-NLS-1$ private static final String KEY_DOUBLE_PREFIX = "%%"; //$NON-NLS-1$ private static final IPath NL_DIR = IPath.fromOSString("$nl$"); //$NON-NLS-1$ @@ -49,15 +50,12 @@ public class DefaultPreferences extends EclipsePreferences { private Thread initializingThread; // cached values - private String qualifier; - private int segmentCount; + private final String qualifier; + private final int segmentCount; private WeakReference pluginReference; - public static String pluginCustomizationFile = null; + static String pluginCustomizationFile = null; - /** - * Default constructor for this class. - */ public DefaultPreferences() { this(null, null); } @@ -70,17 +68,13 @@ private DefaultPreferences(EclipsePreferences parent, String name, Object contex private DefaultPreferences(EclipsePreferences parent, String name) { super(parent, name); - if (parent instanceof DefaultPreferences) - this.pluginReference = ((DefaultPreferences) parent).pluginReference; - + if (parent instanceof DefaultPreferences defaultPreferences) { + this.pluginReference = defaultPreferences.pluginReference; + } // cache the segment count String path = absolutePath(); segmentCount = getSegmentCount(path); - if (segmentCount < 2) - return; - - // cache the qualifier - qualifier = getSegment(path, 1); + qualifier = segmentCount > 1 ? getSegment(path, 1) : null; // cache the qualifier } /* @@ -90,22 +84,25 @@ private DefaultPreferences(EclipsePreferences parent, String name) { */ private void applyBundleDefaults() { Bundle bundle = PreferencesOSGiUtils.getDefault().getBundle(name()); - if (bundle == null) + if (bundle == null) { return; + } URL url = FileLocator.find(bundle, IPath.fromOSString(IPreferencesConstants.PREFERENCES_DEFAULT_OVERRIDE_FILE_NAME), null); if (url == null) { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages .message("Preference default override file not found for bundle: " + bundle.getSymbolicName()); //$NON-NLS-1$ + } return; } URL transURL = FileLocator.find(bundle, NL_DIR.append(IPreferencesConstants.PREFERENCES_DEFAULT_OVERRIDE_BASE_NAME) .addFileExtension(PROPERTIES_FILE_EXTENSION), null); - if (transURL == null && EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (transURL == null && EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Preference translation file not found for bundle: " + bundle.getSymbolicName()); //$NON-NLS-1$ + } applyDefaults(name(), loadProperties(url), loadProperties(transURL)); } @@ -114,8 +111,9 @@ private void applyBundleDefaults() { * command-line. */ private void applyCommandLineDefaults() { - if (commandLineCustomization != null) + if (commandLineCustomization != null) { applyDefaults(null, commandLineCustomization, null); + } } /* @@ -126,8 +124,9 @@ private void applyDefaults(String id, Properties defaultValues, Properties trans for (Enumeration e = defaultValues.keys(); e.hasMoreElements();) { String fullKey = (String) e.nextElement(); String value = defaultValues.getProperty(fullKey); - if (value == null) + if (value == null) { continue; + } String localQualifier = id; String fullPath = fullKey; int firstIndex = fullKey.indexOf(PATH_SEPARATOR); @@ -141,10 +140,11 @@ private void applyDefaults(String id, Properties defaultValues, Properties trans String key = splitPath[1]; if (name().equals(localQualifier)) { value = translatePreference(value, translations); - if (EclipsePreferences.DEBUG_PREFERENCE_SET) + if (EclipsePreferences.DEBUG_PREFERENCE_SET) { PrefsMessages.message("Setting default preference: " //$NON-NLS-1$ - + (IPath.fromOSString(absolutePath()).append(childPath).append(key)) + '=' + value); - ((EclipsePreferences) internalNode(childPath.toString(), false, null)).internalPut(key, value); + + IPath.fromOSString(absolutePath()).append(childPath).append(key) + '=' + value); + } + ((EclipsePreferences) internalNode(childPath, false, null)).internalPut(key, value); } } } @@ -154,28 +154,27 @@ public IEclipsePreferences node(String childName, Object context) { } private boolean containsNode(Properties props, IPath path) { - if (props == null) + if (props == null) { return false; - for (Enumeration e = props.keys(); e.hasMoreElements();) { - String fullKey = (String) e.nextElement(); - if (props.getProperty(fullKey) == null) - continue; + } + return props.entrySet().stream().filter(e -> e.getValue() != null).anyMatch(e -> { + String fullKey = (String) e.getKey(); // remove last segment which stands for key IPath nodePath = IPath.fromOSString(fullKey).removeLastSegments(1); - if (path.isPrefixOf(nodePath)) - return true; - } - return false; + return path.isPrefixOf(nodePath); + }); } @Override public boolean nodeExists(String path) throws BackingStoreException { // use super implementation for empty and absolute paths - if (path.length() == 0 || path.charAt(0) == IPath.SEPARATOR) + if (path.length() == 0 || path.charAt(0) == IPath.SEPARATOR) { return super.nodeExists(path); + } // if the node already exists, nothing more to do - if (super.nodeExists(path)) + if (super.nodeExists(path)) { return true; + } // if the node does not exist, maybe it has not been loaded yet initializeCustomizations(); // scope based path is a path relative to the "/default" node; this is the path @@ -185,7 +184,7 @@ public boolean nodeExists(String path) throws BackingStoreException { || containsNode(commandLineCustomization, scopeBasedPath); } - private void initializeCustomizations() { + private static void initializeCustomizations() { // prime the cache the first time if (productCustomization == null) { BundleContext context = Activator.getContext(); @@ -202,17 +201,20 @@ private void initializeCustomizations() { } else { PrefsMessages.message("Product-specified preferences called before plugin is started"); //$NON-NLS-1$ } - if (productCustomization == null) + if (productCustomization == null) { productCustomization = new Properties(); + } } if (commandLineCustomization == null) { String filename = pluginCustomizationFile; if (filename == null) { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Command-line preferences customization file not specified."); //$NON-NLS-1$ + } } else { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Using command-line preference customization file: " + filename); //$NON-NLS-1$ + } commandLineCustomization = loadProperties(filename); } } @@ -229,8 +231,9 @@ private void initializeCustomizations() { */ private void applyRuntimeDefaults() { WeakReference ref = PreferencesService.getDefault().applyRuntimeDefaults(name(), pluginReference); - if (ref != null) + if (ref != null) { pluginReference = ref; + } } /* @@ -240,8 +243,9 @@ private void applyRuntimeDefaults() { * primary feature's plug-in directory. */ private void applyProductDefaults() { - if (!productCustomization.isEmpty()) + if (!productCustomization.isEmpty()) { applyDefaults(null, productCustomization, productTranslation); + } } @Override @@ -252,14 +256,16 @@ public void flush() { @Override protected IEclipsePreferences getLoadLevel() { if (loadLevel == null) { - if (qualifier == null) + if (qualifier == null) { return null; + } // Make it relative to this node rather than navigating to it from the root. // Walk backwards up the tree starting at this node. // This is important to avoid a chicken/egg thing on startup. EclipsePreferences node = this; - for (int i = 2; i < segmentCount; i++) + for (int i = 2; i < segmentCount; i++) { node = (EclipsePreferences) node.parent(); + } loadLevel = node; } return loadLevel; @@ -272,7 +278,7 @@ protected EclipsePreferences internalCreate(EclipsePreferences nodeParent, Strin @Override protected boolean isAlreadyLoaded(IEclipsePreferences node) { - return loadedNodes.contains(node.name()); + return LOADED_NODES.contains(node.name()); } @Override @@ -299,8 +305,8 @@ protected String internalPut(String key, String newValue) { if (isInitializingBundleDefaults()) { String relativePath = getScopeRelativePath(absolutePath()); if (relativePath != null) { - Preferences node = PreferencesService.getDefault().getRootNode().node(BundleDefaultsScope.SCOPE) - .node(relativePath); + IEclipsePreferences rootNode = PreferencesService.getDefault().getRootNode(); + Preferences node = rootNode.node(BundleDefaultsScope.SCOPE).node(relativePath); node.put(key, newValue); } } @@ -314,8 +320,7 @@ protected String internalPut(String key, String newValue) { */ private void setInitializingBundleDefaults() { IEclipsePreferences node = getLoadLevel(); - if (node instanceof DefaultPreferences) { - DefaultPreferences loader = (DefaultPreferences) node; + if (node instanceof DefaultPreferences loader) { loader.initializingThread = Thread.currentThread(); } } @@ -327,8 +332,7 @@ private void setInitializingBundleDefaults() { */ private void clearInitializingBundleDefaults() { IEclipsePreferences node = getLoadLevel(); - if (node instanceof DefaultPreferences) { - DefaultPreferences loader = (DefaultPreferences) node; + if (node instanceof DefaultPreferences loader) { loader.initializingThread = null; } } @@ -340,8 +344,7 @@ private void clearInitializingBundleDefaults() { */ private boolean isInitializingBundleDefaults() { IEclipsePreferences node = getLoadLevel(); - if (node instanceof DefaultPreferences) { - DefaultPreferences loader = (DefaultPreferences) node; + if (node instanceof DefaultPreferences loader) { return loader.initializingThread == Thread.currentThread(); } return false; @@ -353,65 +356,49 @@ private boolean isInitializingBundleDefaults() { */ protected static String getScopeRelativePath(String absolutePath) { // shouldn't happen but handle empty or root - if (absolutePath.length() < 2) + if (absolutePath.length() < 2) { return null; + } int index = absolutePath.indexOf('/', 1); - if (index == -1 || index + 1 >= absolutePath.length()) + if (index == -1 || index + 1 >= absolutePath.length()) { return null; + } return absolutePath.substring(index + 1); } private Properties loadProperties(URL url) { Properties result = new Properties(); - if (url == null) + if (url == null) { return result; - InputStream input = null; - try { - input = url.openStream(); + } + try (InputStream input = url.openStream()) { result.load(input); } catch (IOException | IllegalArgumentException e) { if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Problem opening stream to preference customization file: " + url); //$NON-NLS-1$ e.printStackTrace(); } - } finally { - if (input != null) - try { - input.close(); - } catch (IOException e) { - // ignore - } } return result; } - private Properties loadProperties(String filename) { + private static Properties loadProperties(String filename) { Properties result = new Properties(); - InputStream input = null; - try { - input = new BufferedInputStream(new FileInputStream(filename)); + try (InputStream input = new FileInputStream(filename)) { result.load(input); } catch (FileNotFoundException e) { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Preference customization file not found: " + filename); //$NON-NLS-1$ + } } catch (IOException | IllegalArgumentException e) { - String message = NLS.bind(PrefsMessages.preferences_loadException, filename); - IStatus status = new Status(IStatus.ERROR, PrefsMessages.OWNER_NAME, IStatus.ERROR, message, e); - RuntimeLog.log(status); - } finally { - if (input != null) - try { - input.close(); - } catch (IOException e) { - // ignore - } + RuntimeLog.log(Status.error(NLS.bind(PrefsMessages.preferences_loadException, filename), e)); } return result; } @Override protected void loaded() { - loadedNodes.add(name()); + LOADED_NODES.add(name()); } @Override @@ -424,8 +411,9 @@ public void sync() { * translated version of this value (if one exists). */ private String translatePreference(String origValue, Properties props) { - if (props == null || origValue.startsWith(KEY_DOUBLE_PREFIX)) + if (props == null || origValue.startsWith(KEY_DOUBLE_PREFIX)) { return origValue; + } if (origValue.startsWith(KEY_PREFIX)) { String value = origValue.trim(); int ix = value.indexOf(" "); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/EclipsePreferences.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/EclipsePreferences.java index b8f9ddefe61..c2dd35030ed 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/EclipsePreferences.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/EclipsePreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2022 IBM Corporation and others. + * Copyright (c) 2004, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -76,17 +76,14 @@ public class EclipsePreferences implements IEclipsePreferences, IScope { private final ListenerList preferenceChangeListeners = new ListenerList<>(); private ScopeDescriptor descriptor; - public static boolean DEBUG_PREFERENCE_GENERAL = false; - public static boolean DEBUG_PREFERENCE_SET = false; - public static boolean DEBUG_PREFERENCE_GET = false; - - protected static final String debugPluginName = "org.eclipse.equinox.preferences"; //$NON-NLS-1$ - + public static final boolean DEBUG_PREFERENCE_GENERAL; + public static final boolean DEBUG_PREFERENCE_SET; + public static final boolean DEBUG_PREFERENCE_GET; static { - DEBUG_PREFERENCE_GENERAL = PreferencesOSGiUtils.getDefault().getBooleanDebugOption(debugPluginName + "/general", //$NON-NLS-1$ - false); - DEBUG_PREFERENCE_SET = PreferencesOSGiUtils.getDefault().getBooleanDebugOption(debugPluginName + "/set", false); //$NON-NLS-1$ - DEBUG_PREFERENCE_GET = PreferencesOSGiUtils.getDefault().getBooleanDebugOption(debugPluginName + "/get", false); //$NON-NLS-1$ + PreferencesOSGiUtils osgiDefaults = PreferencesOSGiUtils.getDefault(); + DEBUG_PREFERENCE_GENERAL = osgiDefaults.getBooleanDebugOption(Activator.PI_PREFERENCES + "/general", false); //$NON-NLS-1$ + DEBUG_PREFERENCE_SET = osgiDefaults.getBooleanDebugOption(Activator.PI_PREFERENCES + "/set", false); //$NON-NLS-1$ + DEBUG_PREFERENCE_GET = osgiDefaults.getBooleanDebugOption(Activator.PI_PREFERENCES + "/get", false); //$NON-NLS-1$ } public EclipsePreferences() { @@ -102,9 +99,9 @@ protected EclipsePreferences(EclipsePreferences parent, String name) { @Override public String absolutePath() { if (cachedPath == null) { - if (parent == null) + if (parent == null) { cachedPath = PATH_SEPARATOR; - else { + } else { String parentPath = parent.absolutePath(); // if the parent is the root then we don't have to add a separator // between the parent path and our path @@ -120,8 +117,9 @@ public String absolutePath() { @Override public void accept(IPreferenceNodeVisitor visitor) throws BackingStoreException { - if (!visitor.visit(this)) + if (!visitor.visit(this)) { return; + } for (IEclipsePreferences p : getChildren(true)) { p.accept(visitor); } @@ -142,22 +140,25 @@ protected IEclipsePreferences addChild(String childName, IEclipsePreferences chi public void addNodeChangeListener(INodeChangeListener listener) { checkRemoved(); nodeChangeListeners.add(listener); - if (DEBUG_PREFERENCE_GENERAL) + if (DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Added preference node change listener: " + listener + " to: " + absolutePath()); //$NON-NLS-1$ //$NON-NLS-2$ + } } @Override public void addPreferenceChangeListener(IPreferenceChangeListener listener) { checkRemoved(); preferenceChangeListeners.add(listener); - if (DEBUG_PREFERENCE_GENERAL) + if (DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Added preference property change listener: " + listener + " to: " + absolutePath()); //$NON-NLS-1$ //$NON-NLS-2$ + } } private IEclipsePreferences calculateRoot() { IEclipsePreferences result = this; - while (result.parent() != null) + while (result.parent() != null) { result = (IEclipsePreferences) result.parent(); + } return result; } @@ -166,8 +167,9 @@ private IEclipsePreferences calculateRoot() { * removed node. */ protected void checkRemoved() { - if (removed) + if (removed) { throw new IllegalStateException(NLS.bind(PrefsMessages.preferences_removedNode, name)); + } } @Override @@ -176,12 +178,14 @@ public String[] childrenNames() throws BackingStoreException { checkRemoved(); String[] internal = internalChildNames(); // if we are != 0 then we have already been initialized - if (internal.length != 0) + if (internal.length != 0) { return internal; + } // we only want to query the descriptor for the child names if // this node is the scope root - if (descriptor != null && getSegmentCount(absolutePath()) == 1) + if (descriptor != null && getSegmentCount(absolutePath()) == 1) { return descriptor.childrenNames(absolutePath()); + } return internal; } @@ -253,14 +257,16 @@ protected static void convertFromProperties(EclipsePreferences node, Properties String path = splitPath[0]; path = makeRelative(path); String key = splitPath[1]; - if (DEBUG_PREFERENCE_SET) + if (DEBUG_PREFERENCE_SET) { PrefsMessages.message("Setting preference: " + path + '/' + key + '=' + value); //$NON-NLS-1$ + } // use internal methods to avoid notifying listeners EclipsePreferences childNode = (EclipsePreferences) node.internalNode(path, false, null); String oldValue = childNode.internalPut(key, value); // notify listeners if applicable - if (notify && !value.equals(oldValue)) + if (notify && !value.equals(oldValue)) { childNode.firePreferenceEvent(key, oldValue, value); + } } } } @@ -323,8 +329,9 @@ protected Properties convertToProperties(Properties result, String prefix) throw } for (String key : temp.keys()) { String value = temp.get(key); - if (value != null) + if (value != null) { result.put(encodePath(prefix, key), value); + } } // recursively add the child information for (IEclipsePreferences childNode : getChildren(true)) { @@ -408,15 +415,15 @@ protected IEclipsePreferences internalFlush() throws BackingStoreException { } return null; } - // a parent is the load level for this node - if (this != loadLevel) + if (this != loadLevel) { return loadLevel; - + } // this node is a load level // any work to do? - if (!dirty) + if (!dirty) { return null; + } // remove dirty bit before saving, to ensure that concurrent // changes during save mark the store as dirty dirty = false; @@ -454,8 +461,9 @@ public byte[] getByteArray(String key, byte[] defaultValue) { */ protected boolean childExists(String childName) { synchronized (childAndPropertyLock) { - if (children == null) + if (children == null) { return false; + } return children.get(childName) != null; } } @@ -466,17 +474,20 @@ protected boolean childExists(String childName) { */ protected IEclipsePreferences getChild(String key, Object context, boolean create) { synchronized (childAndPropertyLock) { - if (children == null) + if (children == null) { return null; + } Object value = children.get(key); - if (value == null) + if (value == null) { return null; - if (value instanceof IEclipsePreferences eclipsePreferences) + } else if (value instanceof IEclipsePreferences eclipsePreferences) { return eclipsePreferences; + } // if we aren't supposed to create this node, then // just return null - if (!create) + if (!create) { return null; + } } return addChild(key, create(this, key, context)); } @@ -499,12 +510,13 @@ private List getChildren(boolean create) { public double getDouble(String key, double defaultValue) { String value = internalGet(key); double result = defaultValue; - if (value != null) + if (value != null) { try { result = Double.parseDouble(value); } catch (NumberFormatException e) { // use default } + } return result; } @@ -512,12 +524,13 @@ public double getDouble(String key, double defaultValue) { public float getFloat(String key, float defaultValue) { String value = internalGet(key); float result = defaultValue; - if (value != null) + if (value != null) { try { result = Float.parseFloat(value); } catch (NumberFormatException e) { // use default } + } return result; } @@ -525,12 +538,13 @@ public float getFloat(String key, float defaultValue) { public int getInt(String key, int defaultValue) { String value = internalGet(key); int result = defaultValue; - if (value != null) + if (value != null) { try { result = Integer.parseInt(value); } catch (NumberFormatException e) { // use default } + } return result; } @@ -549,12 +563,13 @@ protected IPath getLocation() { public long getLong(String key, long defaultValue) { String value = internalGet(key); long result = defaultValue; - if (value != null) + if (value != null) { try { result = Long.parseLong(value); } catch (NumberFormatException e) { // use default } + } return result; } @@ -569,16 +584,18 @@ protected EclipsePreferences internalCreate(EclipsePreferences nodeParent, Strin */ protected String internalGet(String key) { // throw NPE if key is null - if (key == null) + if (key == null) { throw new NullPointerException(); + } // illegal state if this node has been removed checkRemoved(); String result; synchronized (childAndPropertyLock) { result = properties.get(key); } - if (DEBUG_PREFERENCE_GET) + if (DEBUG_PREFERENCE_GET) { PrefsMessages.message("Getting preference value: " + absolutePath() + '/' + key + "->" + result); //$NON-NLS-1$ //$NON-NLS-2$ + } return result; } @@ -591,15 +608,15 @@ protected IEclipsePreferences internalNode(String path, boolean notify, Object c checkRemoved(); // short circuit this node - if (path.length() == 0) + if (path.isEmpty()) { return this; - + } // if we have an absolute path use the root relative to // this node instead of the global root // in case we have a different hierarchy. (e.g. export) - if (path.charAt(0) == IPath.SEPARATOR) + if (path.charAt(0) == IPath.SEPARATOR) { return (IEclipsePreferences) calculateRoot().node(path.substring(1)); - + } int index = path.indexOf(IPath.SEPARATOR); String key = index == -1 ? path : path.substring(0, index); boolean added = false; @@ -609,8 +626,9 @@ protected IEclipsePreferences internalNode(String path, boolean notify, Object c added = true; } // notify listeners if a child was added - if (added && notify) + if (added && notify) { fireNodeEvent(new NodeChangeEvent(this, child), true); + } return (IEclipsePreferences) child.node(index == -1 ? EMPTY_STRING : path.substring(index + 1)); } @@ -663,15 +681,17 @@ protected void load() throws BackingStoreException { } else { // load the properties then set them without sending out change events Properties props = descriptor.load(absolutePath()); - if (props == null || props.isEmpty()) + if (props == null || props.isEmpty()) { return; + } convertFromProperties(this, props, false); } } protected static Properties loadProperties(IPath location) throws BackingStoreException { - if (DEBUG_PREFERENCE_GENERAL) + if (DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Loading preferences from file: " + location); //$NON-NLS-1$ + } Properties result = new Properties(); try (InputStream input = getSaveInputStream(location)) { result.load(input); @@ -698,8 +718,9 @@ private static InputStream getSaveInputStream(IPath location) throws IOException protected void load(IPath location) throws BackingStoreException { if (location == null) { - if (DEBUG_PREFERENCE_GENERAL) + if (DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Unable to determine location of preference file for node: " + absolutePath()); //$NON-NLS-1$ + } return; } Properties fromDisk = loadProperties(location); @@ -755,32 +776,34 @@ protected void fireNodeEvent(final NodeChangeEvent event, final boolean added) { @Override public boolean nodeExists(String path) throws BackingStoreException { // short circuit for checking this node - if (path.length() == 0) + if (path.isEmpty()) { return !removed; - + } // illegal state if this node has been removed. // do this AFTER checking for the empty string. checkRemoved(); // use the root relative to this node instead of the global root // in case we have a different hierarchy. (e.g. export) - if (path.charAt(0) == IPath.SEPARATOR) + if (path.charAt(0) == IPath.SEPARATOR) { return calculateRoot().nodeExists(path.substring(1)); - + } int index = path.indexOf(IPath.SEPARATOR); boolean noSlash = index == -1; // if we are looking for a simple child then just look in the table and return - if (noSlash) + if (noSlash) { return childExists(path); - + } // otherwise load the parent of the child and then recursively ask String childName = path.substring(0, index); - if (!childExists(childName)) + if (!childExists(childName)) { return false; + } IEclipsePreferences child = getChild(childName, null, true); - if (child == null) + if (child == null) { return false; + } return child.nodeExists(path.substring(index + 1)); } @@ -803,8 +826,9 @@ protected void firePreferenceEvent(String key, Object oldValue, Object newValue) @Override public void put(String key, String newValue) { - if (key == null || newValue == null) + if (key == null || newValue == null) { throw new NullPointerException(); + } String oldValue = internalPut(key, newValue); if (!newValue.equals(oldValue)) { makeDirty(); @@ -849,8 +873,9 @@ public void remove(String key) { // illegal state if this node has been removed checkRemoved(); oldValue = properties.get(key); - if (oldValue == null) + if (oldValue == null) { return; + } properties = properties.removeKey(key); } makeDirty(); @@ -952,12 +977,14 @@ protected void save() throws BackingStoreException { protected void save(IPath location) throws BackingStoreException { if (location == null) { - if (DEBUG_PREFERENCE_GENERAL) + if (DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Unable to determine location of preference file for node: " + absolutePath()); //$NON-NLS-1$ + } return; } - if (DEBUG_PREFERENCE_GENERAL) + if (DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Saving preferences to file: " + location); //$NON-NLS-1$ + } Properties table = convertToProperties(new SortedProperties(), EMPTY_STRING); if (table.isEmpty()) { // nothing to save. delete existing file if one exists. @@ -998,16 +1025,19 @@ public static String encodePath(String path, String key) { public static String getSegment(String path, int segment) { int start = path.indexOf(IPath.SEPARATOR) == 0 ? 1 : 0; int end = path.indexOf(IPath.SEPARATOR, start); - if (end == path.length() - 1) + if (end == path.length() - 1) { end = -1; + } for (int i = 0; i < segment; i++) { - if (end == -1) + if (end == -1) { return null; + } start = end + 1; end = path.indexOf(IPath.SEPARATOR, start); } - if (end == -1) + if (end == -1) { end = path.length(); + } return path.substring(start, end); } @@ -1020,12 +1050,13 @@ public static int getSegmentCount(String path) { * Return a relative path */ public static String makeRelative(String path) { - String result = path; - if (path == null) + if (path == null) { return EMPTY_STRING; - if (path.length() > 0 && path.charAt(0) == IPath.SEPARATOR) - result = path.substring(1); - return result; + } + if (path.length() > 0 && path.charAt(0) == IPath.SEPARATOR) { + return path.substring(1); + } + return path; } /* @@ -1033,7 +1064,7 @@ public static String makeRelative(String path) { * path may be null. The key is never null. */ public static String[] decodePath(String fullPath) { - String key = null; + String key; String path = null; // check to see if we have an indicator which tells us where the path ends @@ -1056,7 +1087,7 @@ public static String[] decodePath(String fullPath) { } // adjust if we have an absolute path if (path != null) { - if (path.length() == 0) { + if (path.isEmpty()) { path = null; } else if (path.charAt(0) == IPath.SEPARATOR) { path = path.substring(1); @@ -1084,22 +1115,15 @@ public void sync() throws BackingStoreException { public String toDeepDebugString() { final StringBuilder buffer = new StringBuilder(); - IPreferenceNodeVisitor visitor = node -> { - buffer.append(node); - buffer.append('\n'); - String[] keys = node.keys(); - for (String key : keys) { - buffer.append(node.absolutePath()); - buffer.append(PATH_SEPARATOR); - buffer.append(key); - buffer.append('='); - buffer.append(node.get(key, "*default*")); //$NON-NLS-1$ - buffer.append('\n'); - } - return true; - }; try { - accept(visitor); + accept(node -> { + buffer.append(node).append('\n'); + for (String key : node.keys()) { + buffer.append(node.absolutePath()).append(PATH_SEPARATOR); + buffer.append(key).append('=').append(node.get(key, "*default*")).append('\n'); //$NON-NLS-1$ + } + return true; + }); } catch (BackingStoreException e) { System.out.println("Exception while calling #toDeepDebugString()"); //$NON-NLS-1$ e.printStackTrace(); diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/ExportedPreferences.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/ExportedPreferences.java index d50ac9e4008..3be3bab8814 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/ExportedPreferences.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/ExportedPreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2015 IBM Corporation and others. + * Copyright (c) 2004, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -71,11 +71,13 @@ protected EclipsePreferences internalCreate(EclipsePreferences nodeParent, Strin @Override public String toString() { StringBuilder buffer = new StringBuilder(); - if (isExportRoot) + if (isExportRoot) { buffer.append("* "); //$NON-NLS-1$ + } buffer.append(absolutePath()); - if (version != null) + if (version != null) { buffer.append(" (" + version + ')'); //$NON-NLS-1$ + } return buffer.toString(); } } diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/LookupOrder.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/LookupOrder.java deleted file mode 100644 index a6fd63ef5db..00000000000 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/LookupOrder.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2015 IBM Corporation and others. - * - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.core.internal.preferences; - -/** - * Object used to store the look-up order for preference scope searching. - * - * @since 3.0 - */ -public class LookupOrder { - - private String[] order; - - LookupOrder(String[] order) { - for (String o : order) { - if (o == null) { - throw new IllegalArgumentException(); - } - } - this.order = order; - } - - public String[] getOrder() { - return order; - } -} diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java index 67983a63d70..5ac9525faca 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2015 IBM Corporation and others. + * Copyright (c) 2004, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -48,7 +48,7 @@ public class PreferencesService implements IPreferencesService { private static PreferencesService instance; private static final RootPreferences root = new RootPreferences(); - private static final Map DEFAULTS_REGISTRY = new ConcurrentHashMap<>(); + private static final Map DEFAULTS_REGISTRY = new ConcurrentHashMap<>(); private Object registryHelper = null; private final Map defaultScopes = new HashMap<>(); @@ -63,13 +63,17 @@ public static PreferencesService getDefault() { } private PreferencesService() { - initializeDefaultScopes(); + initializeDefaultScope(BundleDefaultsScope.SCOPE, new BundleDefaultPreferences()); + initializeDefaultScope(DefaultScope.SCOPE, new DefaultPreferences()); + initializeDefaultScope(InstanceScope.SCOPE, new InstancePreferences()); + initializeDefaultScope(ConfigurationScope.SCOPE, new ConfigurationPreferences()); } @Override public void applyPreferences(IEclipsePreferences tree, IPreferenceFilter[] filters) throws CoreException { - if (filters == null || filters.length == 0) + if (filters == null || filters.length == 0) { return; + } try { internalApply(tree, filters); } catch (BackingStoreException e) { @@ -87,13 +91,12 @@ public void applyPreferences(IEclipsePreferences tree, IPreferenceFilter[] filte public IStatus applyPreferences(IExportedPreferences preferences) throws CoreException { // TODO investigate refactoring to merge with new #apply(IEclipsePreferences, // IPreferenceFilter[]) APIs - if (preferences == null) + if (preferences == null) { throw new IllegalArgumentException(); - - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + } else if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message( "Applying exported preferences: " + ((ExportedPreferences) preferences).toDeepDebugString()); //$NON-NLS-1$ - + } final MultiStatus result = new MultiStatus(PrefsMessages.OWNER_NAME, IStatus.OK, PrefsMessages.preferences_applyProblems, null); @@ -113,8 +116,9 @@ public IStatus applyPreferences(IExportedPreferences preferences) throws CoreExc // it from the global preferences before continuing. boolean removed = false; if (epNode.isExportRoot()) { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Found export root: " + epNode.absolutePath()); //$NON-NLS-1$ + } // TODO should only have to do this if any of my children have properties to set globalNode.removeNode(); removed = true; @@ -239,9 +243,10 @@ private IExportedPreferences convertFromProperties(Properties properties) { current.put(key, value); } } - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Converted preferences file to IExportedPreferences tree: " //$NON-NLS-1$ + ((ExportedPreferences) result).toDeepDebugString()); + } return result; } @@ -257,25 +262,24 @@ private SortedProperties convertToProperties(IEclipsePreferences preferences, fi // don't store defaults String absolutePath = node.absolutePath(); String scope = getScope(absolutePath); - if (DefaultScope.SCOPE.equals(scope)) + if (DefaultScope.SCOPE.equals(scope)) { return false; + } String path = absolutePath.length() <= baseLength ? EMPTY_STRING : EclipsePreferences.makeRelative(absolutePath.substring(baseLength)); // check the excludes list to see if this node should be considered for (String exclude : excludesList) { String exclusion = EclipsePreferences.makeRelative(exclude); - if (path.startsWith(exclusion)) + if (path.startsWith(exclusion)) { return false; + } } boolean needToAddVersion = InstanceScope.SCOPE.equals(scope); // check the excludes list for each preference String[] keys = node.keys(); for (String key : keys) { - boolean ignore = false; - for (int j = 0; !ignore && j < excludesList.length; j++) - if (EclipsePreferences.encodePath(path, key) - .startsWith(EclipsePreferences.makeRelative(excludesList[j]))) - ignore = true; + boolean ignore = Arrays.stream(excludesList).map(EclipsePreferences::makeRelative) + .anyMatch(EclipsePreferences.encodePath(path, key)::startsWith); if (!ignore) { String value = node.get(key, null); if (value != null) { @@ -283,8 +287,9 @@ private SortedProperties convertToProperties(IEclipsePreferences preferences, fi String bundle = getBundleName(absolutePath); if (bundle != null) { String version = getBundleVersion(bundle); - if (version != null) + if (version != null) { result.put(BUNDLE_VERSION_PREFIX + bundle, version); + } } needToAddVersion = false; } @@ -316,8 +321,9 @@ void copyFromTo(Preferences source, Preferences destination, String[] keys, int destination.put(key, value); } } - if (depth == 0) + if (depth == 0) { return; + } String[] children = source.childrenNames(); for (String child : children) { copyFromTo(source.node(child), destination.node(child), keys, depth); @@ -325,27 +331,23 @@ void copyFromTo(Preferences source, Preferences destination, String[] keys, int } public WeakReference applyRuntimeDefaults(String name, WeakReference pluginReference) { - if (registryHelper == null) + if (registryHelper == null) { return null; + } return ((PreferenceServiceRegistryHelper) registryHelper).applyRuntimeDefaults(name, pluginReference); } - private void initializeDefaultScopes() { - defaultScopes.put(BundleDefaultsScope.SCOPE, new BundleDefaultPreferences()); - root.addChild(BundleDefaultsScope.SCOPE, null); - defaultScopes.put(DefaultScope.SCOPE, new DefaultPreferences()); - root.addChild(DefaultScope.SCOPE, null); - defaultScopes.put(InstanceScope.SCOPE, new InstancePreferences()); - root.addChild(InstanceScope.SCOPE, null); - defaultScopes.put(ConfigurationScope.SCOPE, new ConfigurationPreferences()); - root.addChild(ConfigurationScope.SCOPE, null); + private void initializeDefaultScope(String scope, EclipsePreferences preferences) { + defaultScopes.put(scope, preferences); + root.addChild(scope, null); } public IEclipsePreferences createNode(String key) { IScope scope = defaultScopes.get(key); if (scope == null) { - if (registryHelper == null) + if (registryHelper == null) { return new EclipsePreferences(root, key); + } return ((PreferenceServiceRegistryHelper) registryHelper).createNode(root, key); } return scope.create(root, key); @@ -354,8 +356,9 @@ public IEclipsePreferences createNode(String key) { @Override public void exportPreferences(IEclipsePreferences node, IPreferenceFilter[] filters, OutputStream stream) throws CoreException { - if (filters == null || filters.length == 0) + if (filters == null || filters.length == 0) { return; + } try { internalExport(node, filters, stream); } catch (BackingStoreException e) { @@ -368,15 +371,18 @@ public IStatus exportPreferences(IEclipsePreferences node, OutputStream output, throws CoreException { // TODO investigate refactoring to merge with new #export(IEclipsePreferences, // IPreferenceFilter[]) APIs - if (node == null || output == null) + if (node == null || output == null) { throw new IllegalArgumentException(); + } SortedProperties properties = null; - if (excludesList == null) + if (excludesList == null) { excludesList = new String[0]; + } try { properties = convertToProperties(node, excludesList); - if (properties.isEmpty()) + if (properties.isEmpty()) { return Status.OK_STATUS; + } properties.put(VERSION_KEY, Float.toString(EXPORT_VERSION)); properties.put(EXPORT_ROOT_PREFIX + node.absolutePath(), EMPTY_STRING); } catch (BackingStoreException e) { @@ -394,8 +400,9 @@ public IStatus exportPreferences(IEclipsePreferences node, OutputStream output, * Give clients a chance to modify the tree before it is applied globally */ private IEclipsePreferences firePreApplyEvent(IEclipsePreferences tree) { - if (registryHelper == null) + if (registryHelper == null) { return tree; + } final IEclipsePreferences[] result = new IEclipsePreferences[] { tree }; ListenerList listeners = ((PreferenceServiceRegistryHelper) registryHelper) .getModifyListeners(); @@ -407,13 +414,15 @@ private IEclipsePreferences firePreApplyEvent(IEclipsePreferences tree) { @Override public String get(String key, String defaultValue, Preferences[] nodes) { - if (nodes == null) + if (nodes == null) { return defaultValue; + } for (Preferences node : nodes) { if (node != null) { String result = node.get(key, null); - if (result != null) + if (result != null) { return result; + } } } return defaultValue; @@ -430,11 +439,13 @@ public boolean getBoolean(String qualifier, String key, boolean defaultValue, IS * path is: - absolute - in the instance scope */ String getBundleName(String path) { - if (path.length() == 0 || path.charAt(0) != IPath.SEPARATOR) + if (path.length() == 0 || path.charAt(0) != IPath.SEPARATOR) { return null; + } int first = path.indexOf(IPath.SEPARATOR, 1); - if (first == -1) + if (first == -1) { return null; + } int second = path.indexOf(IPath.SEPARATOR, first + 1); return second == -1 ? path.substring(first + 1) : path.substring(first + 1, second); } @@ -462,15 +473,15 @@ public byte[] getByteArray(String qualifier, String key, byte[] defaultValue, IS @Override public String[] getDefaultLookupOrder(String qualifier, String key) { - LookupOrder order = DEFAULTS_REGISTRY.get(getRegistryKey(qualifier, key)); - return order == null ? null : order.getOrder(); + return DEFAULTS_REGISTRY.get(getRegistryKey(qualifier, key)); } @Override public double getDouble(String qualifier, String key, double defaultValue, IScopeContext[] scopes) { String value = get(EclipsePreferences.decodePath(key)[1], null, getNodes(qualifier, key, scopes)); - if (value == null) + if (value == null) { return defaultValue; + } try { return Double.parseDouble(value); } catch (NumberFormatException e) { @@ -481,8 +492,9 @@ public double getDouble(String qualifier, String key, double defaultValue, IScop @Override public float getFloat(String qualifier, String key, float defaultValue, IScopeContext[] scopes) { String value = get(EclipsePreferences.decodePath(key)[1], null, getNodes(qualifier, key, scopes)); - if (value == null) + if (value == null) { return defaultValue; + } try { return Float.parseFloat(value); } catch (NumberFormatException e) { @@ -493,8 +505,9 @@ public float getFloat(String qualifier, String key, float defaultValue, IScopeCo @Override public int getInt(String qualifier, String key, int defaultValue, IScopeContext[] scopes) { String value = get(EclipsePreferences.decodePath(key)[1], null, getNodes(qualifier, key, scopes)); - if (value == null) + if (value == null) { return defaultValue; + } try { return Integer.parseInt(value); } catch (NumberFormatException e) { @@ -505,8 +518,9 @@ public int getInt(String qualifier, String key, int defaultValue, IScopeContext[ @Override public long getLong(String qualifier, String key, long defaultValue, IScopeContext[] scopes) { String value = get(EclipsePreferences.decodePath(key)[1], null, getNodes(qualifier, key, scopes)); - if (value == null) + if (value == null) { return defaultValue; + } try { return Long.parseLong(value); } catch (NumberFormatException e) { @@ -547,16 +561,18 @@ public void run() throws Exception { Preferences node = context.getNode(qualifier); if (node != null) { found = true; - if (childPath != null) + if (childPath != null) { node = node.node(childPath); + } result.add(node); } } } if (!found) { Preferences node = getRootNode().node(scopeString).node(qualifier); - if (childPath != null) + if (childPath != null) { node = node.node(childPath); + } result.add(node); } } @@ -591,10 +607,11 @@ public void handleException(Throwable exception) { * registry. */ private String getRegistryKey(String qualifier, String key) { - if (qualifier == null) + if (qualifier == null) { throw new IllegalArgumentException(); - if (key == null) + } else if (key == null) { return qualifier; + } return qualifier + '/' + key; } @@ -608,16 +625,20 @@ public IEclipsePreferences getRootNode() { * string if it cannot be determined. */ String getScope(String path) { - if (path == null || path.length() == 0) + if (path == null || path.length() == 0) { return EMPTY_STRING; + } int startIndex = path.indexOf(IPath.SEPARATOR); - if (startIndex == -1) + if (startIndex == -1) { return path; - if (path.length() == 1) + } + if (path.length() == 1) { return EMPTY_STRING; + } int endIndex = path.indexOf(IPath.SEPARATOR, startIndex + 1); - if (endIndex == -1) + if (endIndex == -1) { endIndex = path.length(); + } return path.substring(startIndex + 1, endIndex); } @@ -628,8 +649,9 @@ public String getString(String qualifier, String key, String defaultValue, IScop @Override public IStatus importPreferences(InputStream input) throws CoreException { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Importing preferences..."); //$NON-NLS-1$ + } return applyPreferences(readPreferences(input)); } @@ -678,8 +700,9 @@ private void internalExport(IEclipsePreferences node, IPreferenceFilter[] filter */ private boolean internalMatches(IEclipsePreferences tree, IPreferenceFilter filter) throws BackingStoreException { String[] scopes = filter.getScopes(); - if (scopes == null) + if (scopes == null) { throw new IllegalArgumentException(); + } String treePath = tree.absolutePath(); // see if this node is applicable by going over all our scopes for (String scope : scopes) { @@ -702,8 +725,9 @@ && containsKeys((IEclipsePreferences) tree.node(scope))) { String nodeFullPath = '/' + scope + '/' + nodePath; // if this subtree isn't in a hierarchy we are interested in, then go to the // next one - if (!nodeFullPath.startsWith(treePath)) + if (!nodeFullPath.startsWith(treePath)) { continue; + } // get the child node String childPath = nodeFullPath.substring(treePath.length()); childPath = EclipsePreferences.makeRelative(childPath); @@ -720,8 +744,9 @@ && containsKeys((IEclipsePreferences) tree.node(scope))) { // are supposed to match on the existence of the node as a whole (bug 88820) Preferences child = tree.node(childPath); if (entries == null) { - if (child.keys().length != 0 || child.childrenNames().length != 0) + if (child.keys().length != 0 || child.childrenNames().length != 0) { return true; + } } else { // otherwise check to see if we have any applicable keys for (PreferenceFilterEntry entry : entries) { @@ -763,12 +788,14 @@ private IPreferenceFilter[] internalMatches(IEclipsePreferences tree, IPreferenc * match type. */ private boolean internalMatchesWithMatchType(PreferenceFilterEntry entry, String[] keys) { - if (keys == null || keys.length == 0) + if (keys == null || keys.length == 0) { return false; + } String key = entry.getKey(); String matchType = entry.getMatchType(); - if (!matchType.equalsIgnoreCase(MATCH_TYPE_PREFIX)) + if (!matchType.equalsIgnoreCase(MATCH_TYPE_PREFIX)) { return false; + } for (String k : keys) { if (k.startsWith(key)) { return true; @@ -790,8 +817,9 @@ private boolean isLegacy(Properties properties) { @Override public IPreferenceFilter[] matches(IEclipsePreferences tree, IPreferenceFilter[] filters) throws CoreException { - if (filters == null || filters.length == 0) + if (filters == null || filters.length == 0) { return new IPreferenceFilter[0]; + } try { return internalMatches(tree, filters); } catch (BackingStoreException e) { @@ -800,11 +828,13 @@ public IPreferenceFilter[] matches(IEclipsePreferences tree, IPreferenceFilter[] } private IEclipsePreferences mergeTrees(IEclipsePreferences[] trees) throws BackingStoreException { - if (trees.length == 1) + if (trees.length == 1) { return trees[0]; + } final IEclipsePreferences result = ExportedPreferences.newRoot(); - if (trees.length == 0) + if (trees.length == 0) { return result; + } IPreferenceNodeVisitor visitor = node -> { Preferences destination = result.node(node.absolutePath()); copyFromTo(node, destination, null, 0); @@ -818,12 +848,11 @@ private IEclipsePreferences mergeTrees(IEclipsePreferences[] trees) throws Backi @Override public IExportedPreferences readPreferences(InputStream input) throws CoreException { - if (input == null) + if (input == null) { throw new IllegalArgumentException(); - - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + } else if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Reading preferences from stream..."); //$NON-NLS-1$ - + } // read the file into a properties object Properties properties = new Properties(); try (input) { @@ -831,19 +860,20 @@ public IExportedPreferences readPreferences(InputStream input) throws CoreExcept } catch (IOException | IllegalArgumentException e) { throw new CoreException(Status.error(PrefsMessages.preferences_importProblems, e)); } - // an empty file is an invalid file format - if (properties.isEmpty()) + if (properties.isEmpty()) { throw new CoreException(Status.error(PrefsMessages.preferences_invalidFileFormat, null)); - + } // manipulate the file if it from a legacy preference export if (isLegacy(properties)) { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Read legacy preferences file, converting to 3.0 format..."); //$NON-NLS-1$ + } properties = convertFromLegacy(properties); } else { - if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) + if (EclipsePreferences.DEBUG_PREFERENCE_GENERAL) { PrefsMessages.message("Read preferences file."); //$NON-NLS-1$ + } properties.remove(VERSION_KEY); } @@ -856,8 +886,9 @@ public IExportedPreferences readPreferences(InputStream input) throws CoreExcept */ private boolean scopeMatches(String scope, IEclipsePreferences tree) { // the root isn't in any scope - if (tree.parent() == null) + if (tree.parent() == null) { return false; + } // fancy math to get the first segment of the path String path = tree.absolutePath(); int index = path.indexOf('/', 1); @@ -868,17 +899,18 @@ private boolean scopeMatches(String scope, IEclipsePreferences tree) { @Override public void setDefaultLookupOrder(String qualifier, String key, String[] order) { String registryKey = getRegistryKey(qualifier, key); - if (order == null) + if (order == null) { DEFAULTS_REGISTRY.remove(registryKey); - else { - LookupOrder obj = new LookupOrder(order); - DEFAULTS_REGISTRY.put(registryKey, obj); + } else { + Arrays.asList(order).forEach(Objects::requireNonNull); + DEFAULTS_REGISTRY.put(registryKey, order); } } public void setRegistryHelper(Object registryHelper) { - if (this.registryHelper != null && this.registryHelper != registryHelper) + if (this.registryHelper != null && this.registryHelper != registryHelper) { ((PreferenceServiceRegistryHelper) this.registryHelper).stop(); + } this.registryHelper = registryHelper; } @@ -890,8 +922,9 @@ private IEclipsePreferences trimTree(IEclipsePreferences tree, IPreferenceFilter throws BackingStoreException { IEclipsePreferences result = (IEclipsePreferences) ExportedPreferences.newRoot().node(tree.absolutePath()); String[] scopes = filter.getScopes(); - if (scopes == null) + if (scopes == null) { throw new IllegalArgumentException(); + } String treePath = tree.absolutePath(); // see if this node is applicable by going over all our scopes for (String scope : scopes) { @@ -899,11 +932,11 @@ private IEclipsePreferences trimTree(IEclipsePreferences tree, IPreferenceFilter // if the mapping is null then copy everything if the scope matches if (mapping == null) { // if we are the root node then check our children - if (tree.parent() == null && tree.nodeExists(scope)) + if (tree.parent() == null && tree.nodeExists(scope)) { copyFromTo(tree.node(scope), result.node(scope), null, -1); - // ensure we are in the correct scope - else if (scopeMatches(scope, tree)) + } else if (scopeMatches(scope, tree)) { // ensure we are in the correct scope copyFromTo(tree, result, null, -1); + } continue; } // iterate over the list of declared nodes @@ -911,8 +944,9 @@ else if (scopeMatches(scope, tree)) String nodeFullPath = '/' + scope + '/' + nodePath; // if this subtree isn't in a hierarchy we are interested in, then go to the // next one - if (!nodeFullPath.startsWith(treePath)) + if (!nodeFullPath.startsWith(treePath)) { continue; + } // get the child node String childPath = nodeFullPath.substring(treePath.length()); childPath = EclipsePreferences.makeRelative(childPath); @@ -954,8 +988,9 @@ private void addMatchedKeys(List list, PreferenceFilterEntry entry, Stri list.add(entry.getKey()); return; } - if (keys == null) + if (keys == null) { return; + } String key = entry.getKey(); for (String k : keys) { if (matchType.equals(MATCH_TYPE_PREFIX) && k.startsWith(key)) { diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/RootPreferences.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/RootPreferences.java index 72ecbfbb528..bc609e9abac 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/RootPreferences.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/RootPreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2015 IBM Corporation and others. + * Copyright (c) 2004, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -14,7 +14,6 @@ package org.eclipse.core.internal.preferences; import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; @@ -24,9 +23,6 @@ */ public class RootPreferences extends EclipsePreferences { - /** - * Default constructor. - */ public RootPreferences() { super(null, ""); //$NON-NLS-1$ } @@ -42,20 +38,24 @@ public void flush() throws BackingStoreException { } catch (BackingStoreException e) { // store the first exception we get and still try and flush // the rest of the children. - if (exception == null) + if (exception == null) { exception = e; + } } } - if (exception != null) + if (exception != null) { throw exception; + } } - protected synchronized IEclipsePreferences getChild(String key, Object context) { - if (children == null) + private synchronized IEclipsePreferences getChild(String key) { + if (children == null) { return null; + } Object value = children.get(key); - if (value == null) + if (value == null) { return null; + } if (value instanceof IEclipsePreferences eclipsePreferences) { return eclipsePreferences; } @@ -65,43 +65,30 @@ protected synchronized IEclipsePreferences getChild(String key, Object context) return child; } - protected synchronized IEclipsePreferences[] getChildren() { - // must perform lazy initialization of child nodes - String[] childNames; - try { - childNames = childrenNames(); - } catch (BackingStoreException e) { - log(Status.error(PrefsMessages.childrenNames, e)); - return new IEclipsePreferences[0]; - } - IEclipsePreferences[] childNodes = new IEclipsePreferences[childNames.length]; - for (int i = 0; i < childNames.length; i++) - childNodes[i] = getChild(childNames[i], null); - return childNodes; - } - @Override public Preferences node(String path) { return getNode(path, true); // create if not found } public Preferences getNode(String path, boolean create) { - if (path.length() == 0 || (path.length() == 1 && path.charAt(0) == IPath.SEPARATOR)) + if (path.length() == 0 || (path.length() == 1 && path.charAt(0) == IPath.SEPARATOR)) { return this; + } int startIndex = path.charAt(0) == IPath.SEPARATOR ? 1 : 0; int endIndex = path.indexOf(IPath.SEPARATOR, startIndex + 1); String scope = path.substring(startIndex, endIndex == -1 ? path.length() : endIndex); IEclipsePreferences child; if (create) { - child = getChild(scope, null); + child = getChild(scope); if (child == null) { child = new EclipsePreferences(this, scope); addChild(scope, child); } } else { child = getChild(scope, null, false); - if (child == null) + if (child == null) { return null; + } } return child.node(endIndex == -1 ? "" : path.substring(endIndex + 1)); //$NON-NLS-1$ } @@ -117,11 +104,13 @@ public void sync() throws BackingStoreException { } catch (BackingStoreException e) { // store the first exception we get and still try and sync // the rest of the children. - if (exception == null) + if (exception == null) { exception = e; + } } } - if (exception != null) + if (exception != null) { throw exception; + } } }