下面列出了org.eclipse.ui.services.ISourceProviderService#org.osgi.service.prefs.Preferences 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public IStatus saveState(final IProgressMonitor monitor) {
final IStatus superSaveResult = super.saveState(monitor);
if (superSaveResult.isOK()) {
final Preferences node = getPreferences();
node.put(ORDERED_FILTERS_KEY, Joiner.on(SEPARATOR).join(orderedWorkingSetFilters));
try {
node.flush();
} catch (final BackingStoreException e) {
final String message = "Error occurred while saving state to preference store.";
LOGGER.error(message, e);
return statusHelper.createError(message, e);
}
return statusHelper.OK();
}
return superSaveResult;
}
@Override
public IStatus restoreState(final IProgressMonitor monitor) {
final IStatus superRestoreResult = super.restoreState(monitor);
if (superRestoreResult.isOK()) {
final Preferences node = getPreferences();
final String orderedFilters = node.get(ORDERED_FILTERS_KEY, EMPTY_STRING);
if (!Strings.isNullOrEmpty(orderedFilters)) {
orderedWorkingSetFilters.clear();
orderedWorkingSetFilters.addAll(Arrays.asList(orderedFilters.split(SEPARATOR)));
}
discardWorkingSetCaches();
return statusHelper.OK();
}
return superRestoreResult;
}
@Override
public IStatus saveState(final IProgressMonitor monitor) {
final Preferences node = getPreferences();
// Save ordered labels.
node.put(ORDERED_IDS_KEY, Joiner.on(SEPARATOR).join(orderedWorkingSetIds));
// Save visible labels.
node.put(VISIBLE_IDS_KEY, Joiner.on(SEPARATOR).join(visibleWorkingSetIds));
try {
node.flush();
} catch (final BackingStoreException e) {
final String message = "Error occurred while saving state to preference store.";
LOGGER.error(message, e);
return statusHelper.createError(message, e);
}
return statusHelper.OK();
}
@Override
public IStatus restoreState(final IProgressMonitor monitor) {
final Preferences node = getPreferences();
// Restore ordered labels.
final String orderedLabels = node.get(ORDERED_IDS_KEY, EMPTY_STRING);
if (!Strings.isNullOrEmpty(orderedLabels)) {
orderedWorkingSetIds.clear();
orderedWorkingSetIds.addAll(Arrays.asList(orderedLabels.split(SEPARATOR)));
}
// Restore visible labels.
final String visibleLabels = node.get(VISIBLE_IDS_KEY, EMPTY_STRING);
if (!Strings.isNullOrEmpty(visibleLabels)) {
visibleWorkingSetIds.clear();
visibleWorkingSetIds.addAll(Arrays.asList(visibleLabels.split(SEPARATOR)));
}
discardWorkingSetCaches();
return statusHelper.OK();
}
private IStatus restoreState() {
final Preferences node = getPreferences();
// Top level element.
workingSetTopLevel.set(node.getBoolean(IS_WORKINGSET_TOP_LEVEL_KEY, false));
// Active working set manager.
final String value = node.get(ACTIVE_MANAGER_KEY, "");
WorkingSetManager workingSetManager = contributions.get().get(value);
if (workingSetManager == null) {
if (!contributions.get().isEmpty()) {
workingSetManager = contributions.get().values().iterator().next();
}
}
if (workingSetManager != null) {
setActiveManager(workingSetManager);
}
return Status.OK_STATUS;
}
@Override
public void initializeDefaultPreferences(){
Preferences node = DefaultScope.INSTANCE.getNode(Activator.PLUGIN_ID); //$NON-NLS-1$
// default values
node.putBoolean(PreferenceConstants.REPOSITORIES_VISIBLE, true);
node.putBoolean(PreferenceConstants.SHOW_LATEST_VERSION_ONLY, true);
node.putBoolean(PreferenceConstants.AVAILABLE_SHOW_ALL_BUNDLES, false);
node.putBoolean(PreferenceConstants.INSTALLED_SHOW_ALL_BUNDLES, false);
node.putBoolean(PreferenceConstants.AVAILABLE_GROUP_BY_CATEGORY, true);
node.putBoolean(PreferenceConstants.SHOW_DRILLDOWN_REQUIREMENTS, false);
node.putInt(PreferenceConstants.RESTART_POLICY,
Policy.RESTART_POLICY_PROMPT_RESTART_OR_APPLY);
node.putInt(PreferenceConstants.UPDATE_WIZARD_STYLE, Policy.UPDATE_STYLE_MULTIPLE_IUS);
node.putBoolean(PreferenceConstants.FILTER_ON_ENV, true);
node.putInt(PreferenceConstants.UPDATE_DETAILS_HEIGHT, SWT.DEFAULT);
node.putInt(PreferenceConstants.UPDATE_DETAILS_WIDTH, SWT.DEFAULT);
}
public Ruleset(Preferences subPrefs) throws BackingStoreException {
String[] keys = subPrefs.keys();
for (String key : keys) {
switch (key) {
case "SelectedVersion":
this.selectedVersion = subPrefs.get(key, "");
break;
case "CheckboxState":
this.isChecked = subPrefs.getBoolean(key, false);
break;
case "FolderName":
this.folderName = subPrefs.get(key, "");
break;
case "Url":
this.url = subPrefs.get(key, "");
break;
default:
break;
}
}
}
/**
* Gets the manifest URL.
*
* @return the manifest URL
*/
private String getManifestURL() {
final String res;
final Preferences preferences = InstanceScope.INSTANCE.getNode(AddInPreferenceInitializer.SCOPE);
final String host = preferences.get(AddInPreferenceInitializer.HOST_PREFERENCE,
AddInPreferenceInitializer.DEFAULT_HOST);
final String port = preferences.get(AddInPreferenceInitializer.PORT_PREFERENCE,
String.valueOf(AddInPreferenceInitializer.DEFAULT_PORT));
if (AddInPreferenceInitializer.DEFAULT_HOST.equals(host)) {
res = "http://localhost:" + port + "/assets/manifest.xml";
} else {
res = "http://" + host + ":" + port + "/assets/manifest.xml";
}
return res;
}
private static void addSettings(IProject project, String workspaceRoot, List<String> targets,
List<String> buildFlags) throws BackingStoreException {
IScopeContext projectScope = new ProjectScope(project);
Preferences projectNode = projectScope.getNode(Activator.PLUGIN_ID);
int i = 0;
for (String target : targets) {
projectNode.put("target" + i, target);
i++;
}
projectNode.put("workspaceRoot", workspaceRoot);
i = 0;
for (String flag : buildFlags) {
projectNode.put("buildFlag" + i, flag);
i++;
}
projectNode.flush();
}
public File getPlatformHome() {
if (platformHome == null) {
// Get platform home from workspace preferences
Preferences preferences = InstanceScope.INSTANCE.getNode("com.hybris.hyeclipse.preferences");
String platformHomeStr = preferences.get("platform_home", null);
if (platformHomeStr == null) {
IProject platformProject = ResourcesPlugin.getWorkspace().getRoot().getProject("platform");
IPath platformProjectPath = platformProject.getLocation();
if (platformProjectPath != null) {
setPlatformHome(platformProjectPath.toFile());
}
} else {
setPlatformHome(new File(platformHomeStr));
}
}
return platformHome;
}
public void resetPlatform(String platformHome) {
try {
Preferences preferences = InstanceScope.INSTANCE.getNode("com.hybris.hyeclipse.preferences");
preferences.put("platform_home", platformHome);
preferences.flush();
}
catch (BackingStoreException e) {
logError("Failed to persist platform_home", e);
}
getTypeSystemExporter().setPlatformHome(null);
getTypeSystemExporter().nullifySystemConfig();
getTypeSystemExporter().nullifyPlatformConfig();
getTypeSystemExporter().nullifyTypeSystem();
getTypeSystemExporter().nullifyAllTypes();
getTypeSystemExporter().nullifyAllTypeNames();
}
public static void initializeDefaultPreferences() {
Preferences node = DefaultScope.INSTANCE.getNode(SharedCorePlugin.DEFAULT_PYDEV_PREFERENCES_SCOPE);
node.put(PyLintPreferences.PYLINT_FILE_LOCATION, "");
node.putBoolean(PyLintPreferences.USE_PYLINT, PyLintPreferences.DEFAULT_USE_PYLINT);
node.putInt(PyLintPreferences.SEVERITY_ERRORS, PyLintPreferences.DEFAULT_SEVERITY_ERRORS);
node.putInt(PyLintPreferences.SEVERITY_WARNINGS, PyLintPreferences.DEFAULT_SEVERITY_WARNINGS);
node.putInt(PyLintPreferences.SEVERITY_FATAL, PyLintPreferences.DEFAULT_SEVERITY_FATAL);
node.putInt(PyLintPreferences.SEVERITY_CODING_STANDARD, PyLintPreferences.DEFAULT_SEVERITY_CODING_STANDARD);
node.putInt(PyLintPreferences.SEVERITY_REFACTOR, PyLintPreferences.DEFAULT_SEVERITY_REFACTOR);
node.putBoolean(PyLintPreferences.USE_CONSOLE, PyLintPreferences.DEFAULT_USE_CONSOLE);
node.put(PyLintPreferences.PYLINT_ARGS, PyLintPreferences.DEFAULT_PYLINT_ARGS);
}
/** Mock a somewhat clever Saros, with a version number and a preference store. */
public static Saros mockSaros() {
// saros.getBundle() is final --> need PowerMock
Saros saros = PowerMock.createNiceMock(Saros.class);
Bundle bundle = createNiceMock(Bundle.class);
expect(bundle.getVersion()).andStubReturn(new Version("1.0.0.dummy"));
expect(saros.getBundle()).andStubReturn(bundle);
expect(saros.getPreferenceStore()).andStubReturn(new EclipseMemoryPreferenceStore());
Preferences globalPref = createNiceMock(Preferences.class);
expect(saros.getGlobalPreferences()).andStubReturn(globalPref);
replay(bundle, globalPref, saros);
return saros;
}
public IEclipsePreferences preApply(IEclipsePreferences node) {
// the node does not need to be the root of the hierarchy
Preferences root = node.node("/"); //$NON-NLS-1$
try {
// we must not create empty preference nodes, so first check if the node exists
if (root.nodeExists(InstanceScope.SCOPE)) {
Preferences instance = root.node(InstanceScope.SCOPE);
// we must not create empty preference nodes, so first check if the node exists
if (instance.nodeExists(JavaCore.PLUGIN_ID)) {
cleanJavaCore(instance.node(JavaCore.PLUGIN_ID));
}
}
} catch (BackingStoreException e) {
// do nothing
}
return super.preApply(node);
}
@Override
public Preferences node(String path) {
if (path.endsWith("/")) {
if (!"/".equals(path)) {
throw new IllegalArgumentException("Path can't end with /");
}
}
if (path.startsWith("/")) {
if (myParent != null) {
return myParent.node(path);
}
path = path.substring(1);
}
if ("".equals(path)) {
return this;
}
int firstSlash = path.indexOf('/');
String prefix = firstSlash == -1 ? path : path.substring(0, firstSlash);
String suffix = firstSlash == -1 ? "" : path.substring(firstSlash + 1);
Preferences child = myChildren.get(prefix);
if (child == null) {
child = createChild(prefix);
}
return child.node(suffix);
}
@Override
public void initializeDefaultPreferences() {
Preferences node = DefaultScope.INSTANCE.getNode(DEFAULT_SCOPE);
for (int i = 0; i < AnalysisPreferences.completeSeverityMap.length; i++) {
Object[] s = AnalysisPreferences.completeSeverityMap[i];
node.putInt((String) s[1], (Integer) s[2]);
}
node.put(NAMES_TO_IGNORE_UNUSED_VARIABLE, DEFAULT_NAMES_TO_IGNORE_UNUSED_VARIABLE);
node.put(NAMES_TO_IGNORE_UNUSED_IMPORT, DEFAULT_NAMES_TO_IGNORE_UNUSED_IMPORT);
node.put(NAMES_TO_CONSIDER_GLOBALS, DEFAULT_NAMES_TO_CONSIDER_GLOBALS);
node.putBoolean(DO_CODE_ANALYSIS, DEFAULT_DO_CODE_ANALYSIS);
node.putBoolean(DO_AUTO_IMPORT, DEFAULT_DO_AUT_IMPORT);
node.putBoolean(DO_AUTO_IMPORT_ON_ORGANIZE_IMPORTS, DEFAULT_DO_AUTO_IMPORT_ON_ORGANIZE_IMPORTS);
node.putBoolean(DO_IGNORE_IMPORTS_STARTING_WITH_UNDER, DEFAULT_DO_IGNORE_FIELDS_WITH_UNDER);
//pep8 related.
node.putBoolean(USE_PEP8_CONSOLE, DEFAULT_USE_PEP8_CONSOLE);
node.putBoolean(PEP8_USE_SYSTEM, DEFAULT_PEP8_USE_SYSTEM);
}
public FontSubstitutionModel(TTFontCache fontCache, ITextStylesheet stylesheet, Preferences prefs) {
myFontCache = fontCache;
List<FontSubstitution> unresolvedFonts = new ArrayList<FontSubstitution>();
List<FontSubstitution> resolvedFonts = new ArrayList<FontSubstitution>();
for (Iterator<String> families = stylesheet.getFontFamilies().iterator(); families.hasNext();) {
String nextFamily = families.next();
FontSubstitution fs = new FontSubstitution(nextFamily, prefs, myFontCache);
Font awtFont = fs.getSubstitutionFont();
if (awtFont == null) {
unresolvedFonts.add(fs);
} else {
resolvedFonts.add(fs);
}
}
addSubstitutions(unresolvedFonts);
addSubstitutions(resolvedFonts);
myIndexedSubstitutions = new ArrayList<FontSubstitution>(mySubstitutions.values());
}
protected void storeDefaults()
{
// Don't store builtin themes default copy in prefs!
if (getThemeManager().isBuiltinTheme(getName()))
{
return;
}
// Only save to defaults if it has never been saved there. Basically take a snapshot of first version and
// use that as the "default"
IEclipsePreferences prefs = EclipseUtil.defaultScope().getNode(ThemePlugin.PLUGIN_ID);
if (prefs == null)
{
return; // TODO Log something?
}
Preferences preferences = prefs.node(ThemeManager.THEMES_NODE);
if (preferences == null)
{
return;
}
String value = preferences.get(getName(), null);
if (value == null)
{
save(EclipseUtil.defaultScope());
}
}
@Override
protected ExternalLibraryPreferenceModel doLoad() {
final Preferences node = InstanceScope.INSTANCE.getNode(QUALIFIER);
final String jsonString = node.get(CONFIGURATION_KEY, "");
if (isNullOrEmpty(jsonString)) {
return ExternalLibraryPreferenceModel.createDefaultForN4Product();
}
return ExternalLibraryPreferenceModel.createFromJson(jsonString);
}
@Override
protected Map<Binary, URI> init() {
final Map<Binary, URI> initState = super.init();
final Preferences node = InstanceScope.INSTANCE.getNode(QUALIFIER);
for (final Binary binary : binariesProvider.getRegisteredBinaries()) {
recursivePreferencesRead(initState, node, binary);
}
return initState;
}
/**
* Recursive read of the given preferences node based on the provided binary and its {@link Binary#getChildren()
* children}. Information read from preference node is stored in the provided state instance (instance is mutated).
*
* @param state
* state instance to read to
* @param node
* preferences node to read
* @param binary
* the binary for which we read config
*/
private void recursivePreferencesRead(final Map<Binary, URI> state, final Preferences node,
final Binary binary) {
final String value = node.get(binary.getId(), "");
if (!Strings.isNullOrEmpty(value)) {
final File file = new File(value);
if (file.isDirectory()) {
state.put(binary, file.toURI());
}
}
binary.getChildren().forEach(child -> recursivePreferencesRead(state, node, child));
}
/**
* This method fetches the list of rule sets which are stored in preference file
*
* @return list of rule sets
*/
private List<Ruleset> getRulesetsFromPrefs() {
List<Ruleset> ruleSets = new ArrayList<Ruleset>();
try {
String[] listOfNodes = rulePreferences.childrenNames();
for (String currentNode : listOfNodes) {
Ruleset loadedRuleset = new Ruleset(currentNode);
Preferences subPref = rulePreferences.node(currentNode);
String[] keys = subPref.keys();
for (String key : keys) {
switch (key) {
case "FolderName":
loadedRuleset.setFolderName(subPref.get(key, ""));
break;
case "CheckboxState":
loadedRuleset.setChecked(subPref.getBoolean(key, false));
break;
case "SelectedVersion":
loadedRuleset.setSelectedVersion(subPref.get(key, ""));
break;
case "Url":
loadedRuleset.setUrl(subPref.get(key, ""));
break;
default:
break;
}
}
ruleSets.add(loadedRuleset);
}
}
catch (BackingStoreException e) {
Activator.getDefault().logError(e);
}
return ruleSets;
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
final Preferences preferences = InstanceScope.INSTANCE.getNode(AddInPreferenceInitializer.SCOPE);
final String started = preferences.get(AddInPreferenceInitializer.STARTED_PREFERENCE,
String.valueOf(false));
if (Boolean.valueOf(started)) {
final String host = preferences.get(AddInPreferenceInitializer.HOST_PREFERENCE,
AddInPreferenceInitializer.DEFAULT_HOST);
final String port = preferences.get(AddInPreferenceInitializer.PORT_PREFERENCE,
String.valueOf(AddInPreferenceInitializer.DEFAULT_PORT));
startServer(host, Integer.valueOf(port));
}
}
/**
* Starts the server.
*/
private void startServer() {
final Preferences preferences = InstanceScope.INSTANCE.getNode(AddInPreferenceInitializer.SCOPE);
final String host = preferences.get(AddInPreferenceInitializer.HOST_PREFERENCE,
AddInPreferenceInitializer.DEFAULT_HOST);
final String port = preferences.get(AddInPreferenceInitializer.PORT_PREFERENCE,
String.valueOf(AddInPreferenceInitializer.DEFAULT_PORT));
M2DocAddInPlugin.getPlugin().startServer(host, Integer.valueOf(port));
}
@Override
public void initializeDefaultPreferences() {
Preferences node = DefaultScope.INSTANCE.getNode(SharedCorePlugin.DEFAULT_PYDEV_PREFERENCES_SCOPE);
node.putInt(PYDEV_REMOTE_DEBUGGER_PORT, DEFAULT_REMOTE_DEBUGGER_PORT);
node.putInt(DEBUG_SERVER_STARTUP, DEFAULT_DEBUG_SERVER_ALWAYS_ON);
node.putInt(FORCE_SHOW_SHELL_ON_BREAKPOINT, DEFAULT_FORCE_SHOW_SHELL_ON_BREAKPOINT);
}
/**
* List of build flags for <code>project</code>, taken from the project configuration
*/
public static List<String> getBuildFlags(IProject project) throws BackingStoreException {
// Get the list of targets from the preferences
IScopeContext projectScope = new ProjectScope(project);
Preferences projectNode = projectScope.getNode(Activator.PLUGIN_ID);
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (String s : projectNode.keys()) {
if (s.startsWith("buildArgs")) {
builder.add(projectNode.get(s, ""));
}
}
return builder.build();
}
/**
* Return the {@link BazelInstance} corresponding to the given <code>project</code>. It looks for
* the instance that runs for the workspace root configured for that project.
*
* @throws BazelNotFoundException
*/
public static BazelCommand.BazelInstance getBazelCommandInstance(IProject project)
throws BackingStoreException, IOException, InterruptedException, BazelNotFoundException {
IScopeContext projectScope = new ProjectScope(project.getProject());
Preferences projectNode = projectScope.getNode(Activator.PLUGIN_ID);
File workspaceRoot =
new File(projectNode.get("workspaceRoot", project.getLocation().toFile().toString()));
return Activator.getDefault().getCommand().getInstance(workspaceRoot);
}
@Override
public void initializeDefaultPreferences() {
Preferences node = DefaultScope.INSTANCE.getNode(InteractiveConsolePlugin.PLUGIN_ID);
//console history
node.putInt(ScriptConsoleUIConstants.INTERACTIVE_CONSOLE_PERSISTENT_HISTORY_MAXIMUM_ENTRIES,
ScriptConsoleUIConstants.DEFAULT_INTERACTIVE_CONSOLE_PERSISTENT_HISTORY_MAXIMUM_ENTRIES);
}
@Override
public void initializeDefaultPreferences() {
Preferences node = DefaultScope.INSTANCE.getNode(SharedUiPlugin.PLUGIN_ID);
node.putBoolean(MinimapOverviewRulerPreferencesPage.USE_MINIMAP, true);
node.putBoolean(MinimapOverviewRulerPreferencesPage.SHOW_VERTICAL_SCROLLBAR, false);
node.putBoolean(MinimapOverviewRulerPreferencesPage.SHOW_HORIZONTAL_SCROLLBAR, true);
node.putBoolean(MinimapOverviewRulerPreferencesPage.SHOW_MINIMAP_CONTENTS, false);
node.putInt(MinimapOverviewRulerPreferencesPage.MINIMAP_WIDTH, 25); // Change default from 70 -> 25
node.put(MinimapOverviewRulerPreferencesPage.MINIMAP_SELECTION_COLOR,
StringConverter.asString(new RGB(51, 153, 255)));
}
private void persistSelections() {
// persist checkbox selections for next time
Preferences preferences = InstanceScope.INSTANCE.getNode("com.hybris.hyeclipse.preferences");
preferences.putBoolean(ImportPlatformPage.FIX_CLASS_PATH_ISSUES_PREFERENCE, fixClasspathIssuesButton.getSelection());
preferences.putBoolean(ImportPlatformPage.REMOVE_HYBRIS_BUILDER_PREFERENCE, removeHybrisItemsXmlGeneratorButton.getSelection());
preferences.putBoolean(ImportPlatformPage.CREATE_WORKING_SETS_PREFERENCE, createWorkingSetsButton.getSelection());
preferences.putBoolean(ImportPlatformPage.USE_MULTI_THREAD_PREFERENCE, useMultiThreadButton.getSelection());
preferences.putBoolean(ImportPlatformPage.SKIP_JAR_SCANNING_PREFERENCE, skipJarScanningButton.getSelection());
try {
preferences.flush();
} catch (BackingStoreException e) {
throw new IllegalStateException("Could not save preferences", e);
}
}