⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 importentrieswizardpage.java

📁 基于Eclipse RCP开发的管理工具
💻 JAVA
字号:
 /*    * Copyright 2006 Marcel Schoffelmeer   *   * Licensed under the Apache License, Version 2.0 (the "License");   * you may not use this file except in compliance with the License.   * You may obtain a copy of the License at   *   *    http://www.apache.org/licenses/LICENSE-2.0   *      * Unless required by applicable law or agreed to in writing, software  * distributed under the License is distributed on an "AS IS" BASIS,   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  * See the License for the specific language governing permissions and  * limitations under the License.  */package com.s10r.manager.exinport;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.eclipse.core.runtime.Path;import org.eclipse.jface.dialogs.IDialogConstants;import org.eclipse.jface.dialogs.IDialogSettings;import org.eclipse.jface.dialogs.MessageDialog;import org.eclipse.jface.wizard.WizardPage;import org.eclipse.swt.SWT;import org.eclipse.swt.graphics.Font;import org.eclipse.swt.graphics.Image;import org.eclipse.swt.layout.GridData;import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.widgets.Button;import org.eclipse.swt.widgets.Combo;import org.eclipse.swt.widgets.Composite;import org.eclipse.swt.widgets.Event;import org.eclipse.swt.widgets.FileDialog;import org.eclipse.swt.widgets.Label;import org.eclipse.swt.widgets.Listener;import org.eclipse.swt.widgets.Widget;import org.eclipse.ui.dialogs.IOverwriteQuery;// This class is derived from the Eclipse SDK source. See preferences import/export classes// at:// eclipse/src/plugins///     org.eclipse.ui.workbench/Eclipse UI///          org/eclipse/ui/internal/wizards/preferencespublic class ImportEntriesWizardPage extends WizardPage implements Listener,		IOverwriteQuery{	protected Combo destinationNameField;	// constants	private Button destinationBrowseButton;	private Button overwriteExistingFilesCheckbox;	protected static final int COMBO_HISTORY_LENGTH = 5;	private static final String STORE_DESTINATION_NAMES_ID = "ExportEntriesWizardPage.STORE_DESTINATION_NAMES_ID";//$NON-NLS-1$	private static final String STORE_OVERWRITE_EXISTING_FILES_ID = "ExportEntriesWizardPage.STORE_OVERWRITE_EXISTING_FILES_ID";	private static final String ENTRIES_IMPORT_PAGE = "entriesimportpage";	private static final String STORE_DESTINATION_ID = null;	private static final int KEEPASS_INDEX = 0;	private String currentMessage;	private Combo combo;	protected void addDestinationItem(String value)	{		destinationNameField.add(value);	}	public ImportEntriesWizardPage()	{		this(ENTRIES_IMPORT_PAGE);		setTitle("Import password entries");		setDescription("Import the password entries from the local file system in XML format. ");	}	protected ImportEntriesWizardPage(String pageName)	{		super(pageName);		// TODO Auto-generated constructor stub	}	public void createControl(Composite parent)	{		// TODO Auto-generated method stub		initializeDialogUnits(parent);		Font wizardFont = parent.getFont();		Composite composite = new Composite(parent, SWT.NULL);		composite.setLayout(new GridLayout());		composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL				| GridData.HORIZONTAL_ALIGN_FILL));		composite.setFont(wizardFont);		createTransferArea(composite);		restoreWidgetValues();		// can not finish initially, but don't want to start with an error		// message either		if (!validateDestinationGroup())		{			setPageComplete(false);		}		// setPreferenceTransfers();		setControl(composite);		giveFocusToDestination();	}	private boolean validateDestinationGroup()	{		if (!validDestination())		{			currentMessage = getInvalidDestinationMessage();			return false;		}		return true;	}	private boolean validDestination()	{		File file = new File(getDestinationValue());		return !(file.getPath().length() <= 0 || file.isDirectory());	}	private String getInvalidDestinationMessage()	{		// TODO Auto-generated method stub		return "Choose a valid destination file to write to";	}	private void giveFocusToDestination()	{		destinationNameField.setFocus();	}	protected void createTransferArea(Composite composite)	{		// createTransfersList(composite);		createDestinationGroup(composite);		createOptionsGroup(composite);	}	protected void createDestinationGroup(Composite parent)	{		// destination specification group		Font parentFont = parent.getFont();		Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);		GridLayout layout = new GridLayout();		layout.numColumns = 3;		destinationSelectionGroup.setLayout(layout);		destinationSelectionGroup.setLayoutData(new GridData(				GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));		destinationSelectionGroup.setFont(parentFont);		Label dest = new Label(destinationSelectionGroup, SWT.NONE);		dest.setText("From file:");		dest.setFont(parentFont);		// destination name entry field		destinationNameField = new Combo(destinationSelectionGroup, SWT.SINGLE				| SWT.BORDER);		destinationNameField.addListener(SWT.Modify, this);		destinationNameField.addListener(SWT.Selection, this);		GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL				| GridData.GRAB_HORIZONTAL);		destinationNameField.setLayoutData(data);		destinationNameField.setFont(parentFont);		// destination browse button		destinationBrowseButton = new Button(destinationSelectionGroup,				SWT.PUSH);		destinationBrowseButton.setText("Browse...");		destinationBrowseButton.setLayoutData(new GridData(				GridData.HORIZONTAL_ALIGN_FILL));		destinationBrowseButton.addListener(SWT.Selection, this);		destinationBrowseButton.setFont(parentFont);		new Label(parent, SWT.NONE); // vertical spacer	}	public void handleEvent(Event e)	{		Widget source = e.widget;		if (source == destinationBrowseButton)		{			handleDestinationBrowseButtonPressed();		}		updatePageCompletion();	}	private void updatePageCompletion()	{		boolean pageComplete = determinePageCompletion();		setPageComplete(pageComplete);		if (pageComplete)		{			setMessage(null);		}	}	private boolean determinePageCompletion()	{		boolean complete = validateDestinationGroup();		// Avoid draw flicker by not clearing the error		// message unless all is valid.		if (complete)		{			setErrorMessage(null);		}		else		{			setErrorMessage(currentMessage);		}		return complete;	}	private void handleDestinationBrowseButtonPressed()	{		System.out.println("handleDestinationBrowseButtonPressed");		FileDialog dialog = new FileDialog(getContainer().getShell(),				getFileDialogStyle());		dialog.setText("Select file");		dialog.setFilterPath(getDestinationValue());		dialog.setFilterExtensions(new String[] { "*.xml", "*.*" }); //$NON-NLS-1$ //$NON-NLS-2$		String selectedFileName = dialog.open();		if (selectedFileName != null)		{			setDestinationValue(selectedFileName);		}	}	protected String getOutputSuffix()	{		return ".xml"; //$NON-NLS-1$	}	protected void setDestinationValue(String value)	{		destinationNameField.setText(value);	}	protected String getDestinationFieldValue()	{		return destinationNameField.getText().trim();	}	protected String getDestinationValue()	{		String idealSuffix = getOutputSuffix();		String destinationText = getDestinationFieldValue();		// only append a suffix if the destination doesn't already have a . in		// its last path segment.		// Also prevent the user from selecting a directory. Allowing this will		// create a ".epf" file in the directory		if (destinationText.length() != 0				&& !destinationText.endsWith(File.separator))		{			int dotIndex = destinationText.lastIndexOf('.');			if (dotIndex != -1)			{				// the last path seperator index				int pathSepIndex = destinationText.lastIndexOf(File.separator);				if (pathSepIndex != -1 && dotIndex < pathSepIndex)				{					destinationText += idealSuffix;				}			}			else			{				destinationText += idealSuffix;			}		}		return destinationText;	}	private int getFileDialogStyle()	{		return SWT.SAVE;	}	protected void createOptionsGroup(Composite parent)	{		// options group		Font parentFont = parent.getFont();		Composite optionsGroup = new Composite(parent, SWT.NONE);		GridLayout layout = new GridLayout();		layout.marginHeight = 0;		optionsGroup.setLayout(layout);		optionsGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL				| GridData.GRAB_HORIZONTAL));		optionsGroup.setFont(parentFont);		// overwrite... checkbox		overwriteExistingFilesCheckbox = new Button(optionsGroup, SWT.CHECK				| SWT.LEFT);		overwriteExistingFilesCheckbox				.setText("Replace existing entries");		overwriteExistingFilesCheckbox.setFont(parentFont);		Label label = new Label(optionsGroup, SWT.NONE);		label.setText("Import file type");        combo = new Combo(optionsGroup, SWT.DROP_DOWN);        combo.add("KeePass XML", KEEPASS_INDEX);        combo.select(KEEPASS_INDEX);	}		public boolean finish()	{		System.out.println("TODO: perform import");		// about to invoke the operation so save our state		saveWidgetValues();		boolean success = true;		File importFile = new File(getDestinationValue());		if (!ensureTargetIsValid(importFile))		{			return false;		}				if (combo.getSelectionIndex() == KEEPASS_INDEX)		{			importKeePassXml(importFile);		}		if (success)		{			saveWidgetValues();						}		return success;	}	private void importKeePassXml(File importFile)	{		try		{			System.out.println("importKeePassXml importFile = " + importFile.getCanonicalPath());		}		catch (IOException e)		{			// TODO Auto-generated catch block			e.printStackTrace();		}							}	protected void restoreWidgetValues()	{		System.out.println("restoreWidgetValues");		IDialogSettings settings = getDialogSettings();		System.out.println("   getDialogSettings returned null!");		if (settings != null)		{			String[] directoryNames = settings					.getArray(STORE_DESTINATION_NAMES_ID);			if (directoryNames != null)			{				// destination				setDestinationValue(directoryNames[0]);				for (int i = 0; i < directoryNames.length; i++)				{					addDestinationItem(directoryNames[i]);				}				String current = settings.get(STORE_DESTINATION_ID);				if (current != null)				{					setDestinationValue(current);				}				// options				if (overwriteExistingFilesCheckbox != null)				{					overwriteExistingFilesCheckbox.setSelection(settings							.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID));				}			}		}	}	protected void saveWidgetValues()	{		// allow subclasses to save values		internalSaveWidgetValues();	}	protected void internalSaveWidgetValues()	{		System.out.println("internalSaveWidgetValues");		// update directory names history		IDialogSettings settings = getDialogSettings();		System.out.println("   getDialogSettings returned null!");		if (settings != null)		{			String[] directoryNames = settings					.getArray(STORE_DESTINATION_NAMES_ID);			if (directoryNames == null)			{				directoryNames = new String[0];			}			directoryNames = addToHistory(directoryNames, getDestinationValue());			settings.put(STORE_DESTINATION_NAMES_ID, directoryNames);			String current = getDestinationValue();			if (current != null && !current.equals("")) { //$NON-NLS-1$				settings.put(STORE_DESTINATION_ID, current);			}			// options			if (overwriteExistingFilesCheckbox != null)			{				settings.put(STORE_OVERWRITE_EXISTING_FILES_ID,						overwriteExistingFilesCheckbox.getSelection());			}		}	}	protected String[] addToHistory(String[] history, String newEntry)	{		List<String> l = new ArrayList<String>(Arrays.asList(history));		addToHistory(l, newEntry);		String[] r = new String[l.size()];		l.toArray(r);		return r;	}	protected void addToHistory(List<String> history, String newEntry)	{		history.remove(newEntry);		history.add(0, newEntry);		// since only one new item was added, we can be over the limit		// by at most one item		if (history.size() > COMBO_HISTORY_LENGTH)		{			history.remove(COMBO_HISTORY_LENGTH);		}	}	public String queryOverwrite(String pathString)	{		System.out.println("queryOverwrite");		Path path = new Path(pathString);		String messageString;		// Break the message up if there is a file name and a directory		// and there are at least 2 segments.		if (path.getFileExtension() == null || path.segmentCount() < 2)		{			messageString = "TODO: path exists mesg";		}		else		{			messageString = "TODO: ok to overwrite msg";		}		final MessageDialog dialog = new MessageDialog(getContainer()				.getShell(), "TODO: questio msg", null, messageString,				MessageDialog.QUESTION, new String[] {						IDialogConstants.YES_LABEL,						IDialogConstants.YES_TO_ALL_LABEL,						IDialogConstants.NO_LABEL,						IDialogConstants.NO_TO_ALL_LABEL,						IDialogConstants.CANCEL_LABEL }, 0);		String[] response = new String[] { YES, ALL, NO, NO_ALL, CANCEL };		// run in syncExec because callback is from an operation,		// which is probably not running in the UI thread.		getControl().getDisplay().syncExec(new Runnable()		{			public void run()			{				dialog.open();			}		});		return dialog.getReturnCode() < 0 ? CANCEL : response[dialog				.getReturnCode()];	}	protected boolean ensureTargetIsValid(File file)	{		if (file.exists())		{			if (!getOverwriteExisting())			{				String msg = "TODO: ok to overwrite?";				if (!queryYesNoQuestion(msg))				{					return false;				}			}			file.delete();		}		else if (!file.isDirectory())		{			File parent = file.getParentFile();			if (parent != null)			{				file.getParentFile().mkdirs();			}		}		return true;	}	private boolean getOverwriteExisting()	{		return overwriteExistingFilesCheckbox.getSelection();	}	protected boolean queryYesNoQuestion(String message)	{		MessageDialog dialog = new MessageDialog(getContainer().getShell(),				"TODO: yes/no question", (Image) null, message,				MessageDialog.NONE, new String[] { IDialogConstants.YES_LABEL,						IDialogConstants.NO_LABEL }, 0);		// ensure yes is the default		return dialog.open() == 0;	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -