下面列出了怎么用org.eclipse.ui.XMLMemento的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Read all profiles from the given store to this profile manager
* @param ips
*/
public void readFromStore(IPreferenceStore ips) {
int allCount = ips.getInt(idInStore + ID_PROFILES_COUNT);
for (int cnt=0; cnt < allCount; ++cnt) {
try {
String xml = ips.getString(idInStore + ID_PROFILE + cnt);
StringReader reader = new StringReader(xml);
XMLMemento memento = XMLMemento.createReadRoot(reader);
IProfile ip = profileFactory.createFromMemento(memento);
if (ip != null) {
String name = ip.getName();
IProfile ipOld = getProfile(name);
if (ipOld == null) {
profiles.add(ip);
} else {
ipOld.copyFrom(ip);
}
}
} catch (Exception e) {
LogHelper.logError(e);
}
}
setActiveProfileName(ips.getString(idInStore + ID_ACTIVE_PROFILE_NAME));
}
public static IProfile readProfileFromStore(String profName, IPreferenceStore ips, String id, IProfile profileFactory) {
int allCount = ips.getInt(id + ID_PROFILES_COUNT);
for (int cnt=0; cnt < allCount; ++cnt) {
try {
String xml = ips.getString(id + ID_PROFILE + cnt);
StringReader reader = new StringReader(xml);
XMLMemento memento = XMLMemento.createReadRoot(reader);
IProfile ip = profileFactory.createFromMemento(memento);
if (ip != null && profName.equals(ip.getName())) {
return ip;
}
} catch (Exception e) {
LogHelper.logError(e);
}
}
return null;
}
private SdkRegistry loadSdkRegistry(XMLMemento memento) {
List<Sdk> registeredSDKs = new ArrayList<Sdk>();
IMemento[] children = memento.getChildren(TAG_SDK);
IPreferenceStore store = XdsCorePlugin.getDefault().getPreferenceStore();
String actSdk = store.getString(KEY_ACTIVE_SDK_NAME);
if (StringUtils.isEmpty(actSdk)) {
actSdk = null;
}
SdkRegistry sdkRegistry = new SdkRegistry(actSdk);
for (IMemento settingsMemento : children) {
Sdk settings = createSdkFor(settingsMemento);
if (settings != null) {
registeredSDKs.add(settings);
}
}
sdkRegistry.setRegisteredSDKs(registeredSDKs);
return sdkRegistry;
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
viewMemento = memento;
if (memento == null) {
IDialogSettings dialogSettings = FindbugsPlugin.getDefault().getDialogSettings();
String persistedMemento = dialogSettings.get(TAG_MEMENTO);
if (persistedMemento == null) {
// See bug 2504068. First time user opens a view, no settings
// are defined
// but we still need to enforce initialisation of content
// provider
// which can only happen if memento is not null
memento = XMLMemento.createWriteRoot("bugExplorer");
} else {
try {
memento = XMLMemento.createReadRoot(new StringReader(persistedMemento));
} catch (WorkbenchException e) {
// don't do anything. Simply don't restore the settings
}
}
}
super.init(site, memento);
}
@Override
public void dispose() {
// XXX see https://bugs.eclipse.org/bugs/show_bug.cgi?id=223068
XMLMemento memento = XMLMemento.createWriteRoot("bugExplorer"); //$NON-NLS-1$
saveState(memento);
StringWriter writer = new StringWriter();
try {
memento.save(writer);
IDialogSettings dialogSettings = FindbugsPlugin.getDefault().getDialogSettings();
dialogSettings.put(TAG_MEMENTO, writer.getBuffer().toString());
} catch (IOException e) {
// don't do anything. Simply don't store the settings
}
if (selectionListener != null) {
getSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(selectionListener);
selectionListener = null;
}
super.dispose();
}
/**
* Stores dialog settings.
*
* @param settings
* settings used to store dialog
*/
protected void storeDialog(IDialogSettings settings) {
settings.put(SHOW_STATUS_LINE, toggleStatusLineAction.isChecked());
XMLMemento memento = XMLMemento.createWriteRoot(HISTORY_SETTINGS);
this.contentProvider.saveHistory(memento);
StringWriter writer = new StringWriter();
try {
memento.save(writer);
settings.put(HISTORY_SETTINGS, writer.getBuffer().toString());
} catch (IOException e) {
// Simply don't store the settings
StatusManager
.getManager()
.handle(
new Status(
IStatus.ERROR,
PlatformUI.PLUGIN_ID,
IStatus.ERROR,
WorkbenchMessages.FilteredItemsSelectionDialog_storeError,
e));
}
}
/**
* Load history elements from memento.
*
* @param memento
* memento from which the history will be retrieved
*/
public void load(IMemento memento) {
XMLMemento historyMemento = (XMLMemento) memento
.getChild(rootNodeName);
if (historyMemento == null) {
return;
}
IMemento[] mementoElements = historyMemento
.getChildren(infoNodeName);
for (int i = 0; i < mementoElements.length; ++i) {
IMemento mementoElement = mementoElements[i];
Object object = restoreItemFromMemento(mementoElement);
if (object != null) {
historyList.add(object);
}
}
}
public void testSave() {
XMLMemento memento = XMLMemento.createWriteRoot("JavaRef");
// Set up a test JsniJavaRef to serialize
JsniJavaRef ref = JsniJavaRef.parse("@com.hello.Hello::sayHi(Ljava/lang/String;)");
ref.setOffset(25);
ref.setSource(new Path("/MyProject/src/com/hello/Hello.java"));
IndexedJsniJavaRef indexedRef = new IndexedJsniJavaRef(ref);
indexedRef.save(memento);
assertEquals("@com.hello.Hello::sayHi(Ljava/lang/String;)",
memento.getTextData());
assertEquals(25, memento.getInteger("offset").intValue());
assertEquals("/MyProject/src/com/hello/Hello.java",
memento.getString("source"));
}
public void saveIndex() {
XMLMemento memento = XMLMemento.createWriteRoot(TAG_ROOT);
persistIndex(memento);
File indexFile = getIndexFile();
FileWriter writer = null;
try {
try {
writer = new FileWriter(indexFile);
memento.save(writer);
} finally {
if (writer != null) {
writer.close();
}
}
} catch (IOException e) {
CorePluginLog.logError(e, "Error saving index " + indexName);
// Make sure we remove any partially-written file
if (indexFile.exists()) {
indexFile.delete();
}
}
}
private void saveIndex() {
XMLMemento memento = XMLMemento.createWriteRoot(TAG_JAVA_REFS);
saveIndex(memento);
FileWriter writer = null;
try {
try {
writer = new FileWriter(getIndexFile());
memento.save(writer);
} finally {
if (writer != null) {
writer.close();
}
}
} catch (IOException e) {
GWTPluginLog.logError(e, "Error saving search index");
}
}
private void saveIndex(XMLMemento memento) {
for (Entry<IPath, Set<IIndexedJavaRef>> fileEntry : fileIndex.entrySet()) {
for (IIndexedJavaRef ref : fileEntry.getValue()) {
IMemento refNode = memento.createChild(TAG_JAVA_REF);
/*
* Embed the Java reference class name into the index. This ends up
* making the resulting index file larger than it really needs to be
* (around 100 KB for the index containing gwt-user, gwt-lang, and all
* the gwt-dev projects), but it still loads in around 50 ms on average
* on my system, so it doesn't seem to be a bottleneck.
*/
String refClassName = ref.getClass().getName();
refNode.putString(TAG_JAVA_REF_CLASS, refClassName);
// The implementation of IIndexedJavaRef serializes itself
ref.save(refNode);
}
}
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
if (memento == null) {
String persistedMemento= fDialogSettings.get(TAG_MEMENTO);
if (persistedMemento != null) {
try {
memento= XMLMemento.createReadRoot(new StringReader(persistedMemento));
} catch (WorkbenchException e) {
// don't do anything. Simply don't restore the settings
}
}
}
fMemento= memento;
if (memento != null) {
restoreLayoutState(memento);
restoreLinkingEnabled(memento);
restoreRootMode(memento);
}
if (getRootMode() == WORKING_SETS_AS_ROOTS) {
createWorkingSetModel();
}
}
@Override
protected void storeDialog(IDialogSettings settings) {
super.storeDialog(settings);
if (! BUG_184693) {
settings.put(SHOW_CONTAINER_FOR_DUPLICATES, fShowContainerForDuplicatesAction.isChecked());
}
if (fFilterActionGroup != null) {
XMLMemento memento= XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$
fFilterActionGroup.saveState(memento);
fFilterActionGroup.dispose();
StringWriter writer= new StringWriter();
try {
memento.save(writer);
settings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString());
} catch (IOException e) {
// don't do anything. Simply don't store the settings
JavaPlugin.log(e);
}
}
}
static XMLMemento saveState( final SQLBuilderDesignState sqbState )
{
// Save the state of the SQLBuilderStorageEditorInput to a XMLMemento
SQLBuilderStorageEditorInput sqbInput = sqbState.getSQBStorageInput();
XMLMemento memento =
SQLBuilderEditorInputUtil.saveSQLBuilderStorageEditorInput( sqbInput );
// Save the data set design's preparable query text in the memento,
// if it is syntactically different from the query text being edited in SQB
String queryText = sqbState.getPreparableSQL();
if( queryText != null &&
! SQLQueryUtility.isEquivalentSQL( queryText, sqbInput.getSQL() ) )
{
memento.putString( KEY_PREPARABLE_SQL_TEXT, queryText );
}
return memento;
}
@Override
protected void storeDialog(IDialogSettings settings) {
super.storeDialog(settings);
XMLMemento memento = XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$
workingSetFilterActionGroup.saveState(memento);
workingSetFilterActionGroup.dispose();
StringWriter writer = new StringWriter();
try {
memento.save(writer);
settings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString());
} catch (IOException e) {
StatusManager.getManager().handle(
new Status(IStatus.ERROR, AnalysisPlugin.getPluginID(), IStatus.ERROR, "", e)); //$NON-NLS-1$
// don't do anything. Simply don't store the settings
}
}
@Override
protected void restoreDialog(IDialogSettings settings) {
super.restoreDialog(settings);
String setting = settings.get(WORKINGS_SET_SETTINGS);
if (setting != null) {
try {
IMemento memento = XMLMemento.createReadRoot(new StringReader(setting));
workingSetFilterActionGroup.restoreState(memento);
} catch (WorkbenchException e) {
StatusManager.getManager().handle(
new Status(IStatus.ERROR, AnalysisPlugin.getPluginID(), IStatus.ERROR, "", e)); //$NON-NLS-1$
// don't do anything. Simply don't restore the settings
}
}
addListFilter(workingSetFilter);
applyFilter();
}
public void testInfoFactory() throws Exception {
InfoFactory infoFactory = new InfoFactory(new AdditionalInfoAndIInfo(null, null));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/namespaces", false);
factory.setFeature("http://xml.org/sax/features/validation", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("root");
IMemento memento = new XMLMemento(document, root);
infoFactory.saveState(memento);
assertNull(infoFactory.createElement(memento));
ClassInfo info = new ClassInfo(null, null, null, null, null, 0, 0);
infoFactory = new InfoFactory(new AdditionalInfoAndIInfo(null, info));
infoFactory.saveState(memento);
assertNull(infoFactory.createElement(memento));
}
/**
* Retrieves the root memento from the workspace preferences if there were
* existing palette customizations.
*
* @return the root memento if there were existing customizations; null
* otherwise
*/
private XMLMemento getExistingCustomizations() {
if (preferences != null) {
String sValue = preferences.getString(PALETTE_CUSTOMIZATIONS_ID);
if (sValue != null && sValue.length() != 0) { //$NON-NLS-1$
try {
XMLMemento rootMemento = XMLMemento.createReadRoot(new StringReader(sValue));
return rootMemento;
} catch (WorkbenchException e) {
Trace.catching(GefPlugin.getInstance(), GefDebugOptions.EXCEPTIONS_CATCHING, getClass(),
"Problem creating the XML memento when saving the palette customizations.", //$NON-NLS-1$
e);
Log.warning(GefPlugin.getInstance(), GefStatusCodes.IGNORED_EXCEPTION_WARNING,
"Problem creating the XML memento when saving the palette customizations.", //$NON-NLS-1$
e);
}
}
}
return null;
}
/**
* Play export dialog and do the export
*
* @param prof - null to export all or the given profile
* @param pm - profile manager to get profiles from (when 'prof' == null)
*/
public static void exportProfiles(Shell shell, IProfile prof, ProfileManager pm) {
String title = prof==null ? Messages.ProfileManager_ExportProfile : Messages.ProfileManager_ExportProfiles;
String s = SWTFactory.browseFile(shell, true, title, new String[]{"*.xml"}, importExportPath); //$NON-NLS-1$
if (s != null) {
File f = new File(s);
if (f.exists()) {
if (!SWTFactory.YesNoQuestion(shell, title,
String.format(Messages.ProfileManager_ReplaceQuestion, s)))
{
return;
}
}
importExportPath = f.getParentFile().getAbsolutePath();
XMLMemento memento = XMLMemento.createWriteRoot("tagExportedFormatterProfiles"); //$NON-NLS-1$
int memNum = 0;
int total = prof == null ? pm.size() : 1;
for (int num=0; num < total; ++num) {
IProfile ip = prof == null ? pm.get(num) : prof;
IMemento childMem = memento.createChild(XML_FORMATTER_PROFILE_SECTION + memNum++);
ip.toMemento(childMem);
}
try {
f.delete();
FileWriter fw = new FileWriter(f);
memento.save(fw);
fw.close();
} catch(Exception e) {
LogHelper.logError(e);
}
}
}
public InstalledUpdatesRegistry loadInstalledUpdatesRegistry() throws IOException, WorkbenchException {
if (installedUpdatesRegistry == null) {
File installedUpdatesRegistryFile = getInstalledUpdatesRegistryFile();
if (installedUpdatesRegistryFile.exists()) {
Reader reader = new FileReader(installedUpdatesRegistryFile);
XMLMemento memento = XMLMemento.createReadRoot(reader);
installedUpdatesRegistry = loadInstalledUpdatesRegistry(memento);
}
else {
installedUpdatesRegistry = new InstalledUpdatesRegistry(new HashMap<String, InstalledUpdate>());
}
}
return installedUpdatesRegistry;
}
public void saveInstalledUpdatesRegistry(InstalledUpdatesRegistry installedUpdatesRegistry) throws IOException {
XMLMemento memento = XMLMemento.createWriteRoot(TAG_INSTALLED_UPDATES);
saveInstalledUpdatesRegistry(memento, installedUpdatesRegistry);
FileWriter writer = new FileWriter(getInstalledUpdatesRegistryFile());
memento.save(writer);
}
private void saveInstalledUpdatesRegistry(XMLMemento memento, InstalledUpdatesRegistry installedUpdatesRegistry) {
Set<Entry<String, InstalledUpdate>> installedUpdateEntries = installedUpdatesRegistry.getInstalledFile2Descriptor().entrySet();
for (Entry<String, InstalledUpdate> installedUpdateEntry : installedUpdateEntries) {
final InstalledUpdate installedUpdate = installedUpdateEntry.getValue();
if (!getActualFile(installedUpdate).exists()) continue;
IMemento installedUpdateChild = memento.createChild(TAG_INSTALLED_UPDATE);
installedUpdateChild.putString(TAG_FILE_LOCATION, installedUpdate.getFileLocation());
installedUpdateChild.putString(TAG_VERSION, installedUpdate.getFileVersion().toString());
}
}
private static InstalledUpdatesRegistry loadInstalledUpdatesRegistry(XMLMemento memento) {
Map<String, InstalledUpdate> installedFile2Descriptor = new HashMap<String, InstalledUpdate>();
IMemento[] installedUpdateChildren = memento.getChildren(TAG_INSTALLED_UPDATE);
for (IMemento installedUpdateChild : installedUpdateChildren) {
InstalledUpdate installedUpdate = createInstalledUpdateFor(installedUpdateChild);
File file = getActualFile(installedUpdate);
if (file.exists()) {
installedFile2Descriptor.put(installedUpdate.getFileLocation(), installedUpdate);
}
}
return new InstalledUpdatesRegistry(installedFile2Descriptor);
}
private void saveSdkRegistry(XMLMemento memento, SdkRegistry sdkRegistry) {
String actSdk = (sdkRegistry.getDefaultSdk() != null) ? sdkRegistry.getDefaultSdk().getName() : ""; //$NON-NLS-1$
IPreferenceStore store = XdsCorePlugin.getDefault().getPreferenceStore();
store.setValue(KEY_ACTIVE_SDK_NAME, actSdk);
WorkspacePreferencesManager.getInstance().flush();
for (Sdk sdk : sdkRegistry.getRegisteredSDKs()) {
IMemento mementoSdk = memento.createChild(TAG_SDK);
for (Sdk.Property property: Sdk.Property.values()) {
mementoSdk.putString(property.xmlKey, sdk.getPropertyValue(property));
for (Sdk.Tag tag : property.possibleTags) {
String val = sdk.getTag(property, tag);
if (val != null) {
String key = property.xmlKey + "_" + tag.xmlTagName; //$NON-NLS-1$
mementoSdk.putString(key, val);
}
}
}
Map<String, String> environmentVariables = sdk.getEnvironmentVariablesRaw();
if (!environmentVariables.isEmpty()) {
for (Map.Entry<String, String> entry : environmentVariables.entrySet()) {
IMemento mementoEnvVar = mementoSdk.createChild(TAG_ENVIRONMENT_VARIABLE);
mementoEnvVar.putString(TAG_ENVIRONMENT_VARIABLE_NAME, entry.getKey());
mementoEnvVar.putString(TAG_ENVIRONMENT_VARIABLE_VALUE, entry.getValue());
}
}
saveTools(mementoSdk, sdk);
}
}
/**
* Restores dialog using persisted settings. The default implementation
* restores the status of the details line and the selection history.
*
* @param settings
* settings used to restore dialog
*/
protected void restoreDialog(IDialogSettings settings) {
boolean toggleStatusLine = true;
if (settings.get(SHOW_STATUS_LINE) != null) {
toggleStatusLine = settings.getBoolean(SHOW_STATUS_LINE);
}
toggleStatusLineAction.setChecked(toggleStatusLine);
details.setVisible(toggleStatusLine);
String setting = settings.get(HISTORY_SETTINGS);
if (setting != null) {
try {
IMemento memento = XMLMemento.createReadRoot(new StringReader(
setting));
this.contentProvider.loadHistory(memento);
} catch (WorkbenchException e) {
// Simply don't restore the settings
StatusManager
.getManager()
.handle(
new Status(
IStatus.ERROR,
PlatformUI.PLUGIN_ID,
IStatus.ERROR,
WorkbenchMessages.FilteredItemsSelectionDialog_restoreError,
e));
}
}
}
@Override
public void saveState(IMemento memento) {
if (memento == null) {
memento = XMLMemento.createWriteRoot(getFactoryId());
}
setMementoProperties(memento);
saveCurrentMemento(memento);
}
public void testSave() {
XMLMemento memento = XMLMemento.createWriteRoot("JavaRef");
// Set up a test JsniJavaRefParamType to serialize
JsniJavaRefParamType ref = JsniJavaRefParamType.parse(new Path(
"/MyProject/src/com/hello/Hello.java"), 25, "Ljava/lang/String;");
ref.save(memento);
assertEquals("Ljava/lang/String;", memento.getTextData());
assertEquals(25, memento.getInteger("offset").intValue());
assertEquals("/MyProject/src/com/hello/Hello.java",
memento.getString("source"));
}
private void persistIndex(XMLMemento memento) {
for (ICompilationUnit cu : index.getAllLeftElements()) {
IMemento cuNode = memento.createChild(TAG_DEPENDENCIES);
cuNode.putString(ATTR_COMPILATION_UNIT, cu.getHandleIdentifier());
for (IPath resourcePath : index.getRightElements(cu)) {
IMemento resNode = cuNode.createChild(TAG_RESOURCE);
resNode.putString(ATTR_RESOURCE_PATH, resourcePath.toString());
}
}
}
private void loadIndex(XMLMemento memento) {
for (IMemento refNode : memento.getChildren(TAG_JAVA_REF)) {
IIndexedJavaRef ref = loadJavaRef(refNode);
if (ref != null) {
// If we are able to re-instantiate the Java reference object, add it to
// both of the search indices
add(ref);
}
}
}
protected IMemento getMemento() {
File file = UIEplPlugin.getDefault().getStateLocation().append(URLS).addFileExtension(XML).toFile();
if (file.exists()) {
try {
FileReader reader = new FileReader(file);
XMLMemento memento = XMLMemento.createReadRoot(reader);
return memento;
} catch (Exception e) {
IdeLog.logError(UIEplPlugin.getDefault(), e);
}
}
return null;
}